"""
AWS FinServ GenAI Risk Assessment Lambda
=========================================
Implements 65 security checks (64 standalone + 1 shared FS-27 entry for the new
Automated Reasoning Policies check) derived from the AWS guide:
"Financial Services risk management of the use of Generative AI"
https://d1.awsstatic.com/onedam/marketing-channels/website/public/global-FinServ-ComplianceGuide-GenAIRisks-public.pdf

Check ID namespace: FS-01 through FS-69
  FS-01 to FS-63 — original 63 checks across 15 risk categories
                   (FS-17, FS-18, FS-19 merged into upstream SM-07, SM-23, SM-22)
  FS-64 to FS-69 — 6 material gap checks covering mitigations explicitly
                   called out in the Guide but absent from FS-01..63 and
                   the existing BR/SM/AC checks in the AIML Security Assessment.
                   (FS-64 merged into upstream BR-04)

5 checks (FS-17, FS-18, FS-19, FS-23, FS-64) are contributed as upstream extensions
rather than standalone entries — see extension notes in the
SECURITY_CHECKS_RESPONSIBLE_AI_GRC Part 1 and Part 3 markdown files.

FS-27 is split into two check functions sharing the same check_id:
  1. check_guardrail_contextual_grounding() — verifies contextualGroundingPolicy
     on guardrails (threshold-based, per-inference filtering).
  2. check_automated_reasoning_policies() — verifies Bedrock Automated Reasoning
     policies (formal verification, GA August 2025, limited regions).
Both use FS-27 in the CSV and both appear in the build_finserv_checks() registry.

These checks complement the existing BR/SM/AC checks in the AIML Security Assessment.

COMPLIANCE_PLACEHOLDER: Each check maps to FinServ regulatory frameworks via the
COMPLIANCE_MAP dict below. These mappings now travel with every finding row in the
CSV report (the Compliance_Frameworks column) — see COMPLIANCE_MAP and create_finding.
Frameworks referenced: FFIEC CAT, SR 11-7, NYDFS 500.06, PCI-DSS 12.3.2, SOC 2 CC6,
ISO 27001 A.12, DORA Art.6, MAS TRM 9.

Contribution workflow:
  - Upstream repo: aws-samples/sample-aiml-security-assessment (OSPO-managed, so forks
    are auto-approved by Amazon Code Defender).
  - This Lambda is delivered via a personal fork + feature branch + PR. See
    GIT_WORKFLOW.md for the full 9-step process (fork, branch, ASH scan, commit, push,
    PR, GitHub Actions verification, reviewer assignment, optional Git Defender
    exception ticket).

Pre-commit quality gates (run every edit):
  1. ruff check + ruff format --check on this directory.
  2. sam local invoke ResponsibleAIGRCAssessmentFunction against a test event.
  3. cfn-lint / sam validate on the updated SAM templates.
  4. ash --source-dir <repo> --fail-on-findings --config-overrides
     'global_settings.severity_threshold=MEDIUM' — resolve every Critical and High
     finding before opening the PR.
  5. git defender scan on the staged diff.
"""

import boto3
import csv
import functools
import json
import logging
import os
import re
from dataclasses import dataclass
from fnmatch import fnmatchcase
from datetime import datetime, timezone
from io import StringIO
from typing import Any, Dict, List, Optional

from botocore.config import Config
from botocore.exceptions import (
    ClientError,
    EndpointConnectionError,
    ParamValidationError,
)

from schema import create_finding

# ---------------------------------------------------------------------------
# Boto3 config with adaptive retries
# ---------------------------------------------------------------------------
boto3_config = Config(retries=dict(max_attempts=10, mode="adaptive"))

logger = logging.getLogger()
logger.setLevel(logging.WARNING)

GLOBAL_REGION_LABEL = "Global"


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _is_valid_permissions_cache(cache: Any) -> bool:
    """Return whether cache has the IAM inventory shape produced upstream."""
    return (
        isinstance(cache, dict)
        and isinstance(cache.get("role_permissions"), dict)
        and isinstance(cache.get("user_permissions"), dict)
    )


def _has_role_permissions_cache(cache: Any) -> bool:
    """Return whether a role-only control has the collection it needs."""
    return isinstance(cache, dict) and isinstance(cache.get("role_permissions"), dict)


def get_permissions_cache(execution_id: str) -> Optional[Dict[str, Any]]:
    """Retrieve IAM permissions cache from S3 (same pattern as other assessments)."""
    try:
        s3_client = boto3.client("s3", config=boto3_config)
        s3_key = f"permissions_cache_{execution_id}.json"
        s3_bucket = os.environ.get("AIML_ASSESSMENT_BUCKET_NAME")
        response = s3_client.get_object(Bucket=s3_bucket, Key=s3_key)
        cache = json.loads(response["Body"].read().decode("utf-8"))
        if not _is_valid_permissions_cache(cache):
            logger.error(
                f"Permissions cache has an invalid schema for execution {execution_id}"
            )
            return None
        return cache
    except ClientError as e:
        logger.warning(f"Could not load permissions cache: {e}")
        return None
    except Exception as e:
        logger.error(f"Unexpected error loading permissions cache: {e}", exc_info=True)
        return None


def _empty_findings(check_name: str) -> Dict[str, Any]:
    return {"check_name": check_name, "status": "PASS", "details": "", "csv_data": []}


def _permission_cache_unavailable_findings(
    check_id: str, finding_name: str
) -> Dict[str, Any]:
    """Emit an explicit incomplete row for a cache-dependent GRC control."""
    details = (
        "The IAM permissions cache is missing, unreadable, or malformed, so this "
        "identity-based control could not be assessed."
    )
    return {
        "check_name": finding_name,
        "status": "N/A",
        "details": details,
        "csv_data": [
            create_finding(
                check_id=check_id,
                finding_name=f"{finding_name} Incomplete",
                finding_details=details,
                resolution=(
                    "Review the IAM Permission Caching task and the execution-scoped "
                    "permissions_cache_<execution-id>.json object, then rerun the "
                    "assessment."
                ),
                reference="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP[check_id],
            )
        ],
    }


UNRECORDED_PRINCIPAL_ERRORS_NOTE = (
    "The IAM permissions cache predates schema version 2 and did not record "
    "per-principal read errors, so a principal whose policies could not be read "
    "looks the same as one with no policies."
)

SCP_NOT_EVALUATED_NOTE = (
    "Service control policies were not evaluated per principal. They only remove "
    "permissions, so an SCP can make this finding a false Failed but cannot hide "
    "a grant it reports."
)


def _principal_read_errors(
    cache: Dict[str, Any], principal_type: str
) -> Optional[Dict[str, List[str]]]:
    """Map each principal of ``principal_type`` whose cache read failed to the
    stages that failed. None when the cache predates ``principal_errors``."""
    errors = cache.get("principal_errors")
    if not isinstance(errors, list):
        return None
    failed: Dict[str, List[str]] = {}
    for error in errors:
        if (
            isinstance(error, dict)
            and error.get("type") == principal_type
            and error.get("name")
        ):
            failed.setdefault(str(error["name"]), []).append(
                str(error.get("stage", "unknown"))
            )
    return failed


def _name_list(names: List[str], limit: int = 10) -> str:
    shown = ", ".join(f"'{n}'" for n in names[:limit])
    if len(names) > limit:
        shown += f" and {len(names) - limit} more"
    return shown


def _as_list(value: Any) -> List[Any]:
    if value is None:
        return []
    return value if isinstance(value, list) else [value]


def _action_covers(pattern: str, action: str) -> bool:
    """Whether IAM action ``pattern`` matches every action ``action`` names.

    Exact for a concrete ``action``. For a wildcard ``action`` only a bare
    ``*`` or a literal prefix ending in ``*`` is credited, so an uncertain
    case reads as not covered."""
    pattern, action = pattern.lower(), action.lower()
    if not any(c in action for c in "*?"):
        return fnmatchcase(action, pattern)
    if pattern == "*":
        return True
    return (
        pattern.endswith("*")
        and not any(c in pattern[:-1] for c in "*?")
        and action.startswith(pattern[:-1])
    )


def _actions_overlap(pattern: str, action: str) -> bool:
    """Whether IAM action patterns could name a common action. Wildcards on
    both sides read as overlapping unless their service prefixes differ."""
    pattern, action = pattern.lower(), action.lower()
    if fnmatchcase(action, pattern) or fnmatchcase(pattern, action):
        return True
    if not any(c in pattern for c in "*?") or not any(c in action for c in "*?"):
        return False
    p_service, a_service = pattern.split(":", 1)[0], action.split(":", 1)[0]
    return fnmatchcase(p_service, a_service) or fnmatchcase(a_service, p_service)


def _boundary_removes(boundary: Any, action: str) -> bool:
    """Whether a permissions boundary removes every action ``action`` names.

    The effective grant is the intersection of the identity policy and the
    boundary, so an action no boundary Allow reaches is not granted. Conditions
    and resources on a boundary Allow are ignored, and only an unconditional
    Deny on Resource ``*`` removes an action, so each approximation keeps a
    grant and can only over-report."""
    if boundary is None:
        return False
    if isinstance(boundary, str):
        try:
            boundary = json.loads(boundary)
        except (ValueError, TypeError):
            return False
    if not isinstance(boundary, dict):
        return False
    statements = [s for s in _as_list(boundary.get("Statement")) if isinstance(s, dict)]
    for stmt in statements:
        if (
            stmt.get("Effect") == "Deny"
            and "Condition" not in stmt
            and "*" in _as_list(stmt.get("Resource"))
            and any(
                isinstance(p, str) and _action_covers(p, action)
                for p in _as_list(stmt.get("Action"))
            )
        ):
            return True
    for stmt in statements:
        if stmt.get("Effect") != "Allow":
            continue
        if any(
            isinstance(p, str) and _actions_overlap(p, action)
            for p in _as_list(stmt.get("Action"))
        ):
            return False
        if "NotAction" in stmt and not any(
            isinstance(p, str) and _action_covers(p, action)
            for p in _as_list(stmt.get("NotAction"))
        ):
            return False
    return True


def _bucket_name_from_arn(bucket_arn: str) -> str:
    """Extract the bucket name from an S3 bucket ARN (arn:aws:s3:::name).

    Returns "" when the value is empty or is not a well-formed S3 bucket ARN, so
    a malformed/unexpected value is skipped rather than mistakenly used as a
    bucket name (which would then fail the subsequent S3 API call)."""
    if not bucket_arn or ":::" not in bucket_arn:
        return ""
    return bucket_arn.split(":::", 1)[1]


def _paginate(
    client,
    operation_name: str,
    result_key: str,
    *,
    token: "tuple[str, str] | None" = None,
    **kwargs,
) -> List[Dict[str, Any]]:
    """Collect all items across pages for a paginated list/describe operation by
    calling the operation directly and following its continuation token.

    Calling the bound method directly (rather than via get_paginator) keeps this
    uniform across services and unit-test mocks. The AWS APIs this Lambda uses
    employ three continuation-token conventions, all handled here:
      - NextToken / NextToken            (organizations, sagemaker, config, events, ...)
      - nextToken / nextToken            (bedrock, bedrock-agent, ecr, ...)
      - Marker / NextMarker              (lambda)
      - position / position              (apigateway)

    A single-page response (no continuation token) yields exactly one call, so
    this is a safe drop-in for previously non-paginated reads and for mocks that
    stub the operation with a single return value.

    Args:
        token: Optional explicit ``(output_field, input_param)`` pair that
            bypasses the convention table entirely.  When set, ``token[0]`` is
            read from each response to find the continuation value and
            ``token[1]`` is the request kwarg used to send it on the next call.
            Use this for operations whose token convention is not in the table,
            or where the output and input names differ from every entry already
            there (e.g. WAFv2 ``NextMarker``/``NextMarker`` vs Lambda's
            ``NextMarker``/``Marker``).  When ``None`` (the default) the
            existing convention table is used unchanged — all current callers
            pass no ``token`` argument and are therefore byte-for-byte identical
            to before this parameter was added.
    """
    # (output token field in response, input token kwarg on request)
    token_conventions = [
        ("NextToken", "NextToken"),
        ("nextToken", "nextToken"),
        ("NextMarker", "Marker"),
        ("position", "position"),
    ]
    method = getattr(client, operation_name)
    items: List[Dict[str, Any]] = []
    call_kwargs = dict(kwargs)
    seen_tokens = set()
    while True:
        resp = method(**call_kwargs)
        items.extend(resp.get(result_key, []) or [])
        next_token = None
        input_field = None
        if token is not None:
            # Explicit override: bypass the convention table.
            out_field, in_field = token
            if resp.get(out_field):
                next_token = resp[out_field]
                input_field = in_field
        else:
            for out_field, in_field in token_conventions:
                if resp.get(out_field):
                    next_token = resp[out_field]
                    input_field = in_field
                    break
        # Stop when there is no token, or if a token repeats (guards against a
        # mock that returns the same token every call → infinite loop).
        if not next_token or next_token in seen_tokens:
            break
        seen_tokens.add(next_token)
        call_kwargs[input_field] = next_token
    return items


def _error_findings(check_name: str, err: Exception) -> Dict[str, Any]:
    return {
        "check_name": check_name,
        "status": "ERROR",
        "details": str(err),
        "csv_data": [],
    }


# Error codes that mean "we were not allowed to read this resource" rather than
# "the control is absent." Treating an access error as a compliance failure
# produces a false non-compliant finding caused purely by a missing permission
# (the credibility problem a compliance tool must avoid).
_ACCESS_ERROR_CODES = frozenset(
    {
        "AccessDenied",
        "AccessDeniedException",
        "UnauthorizedOperation",
        "AuthorizationError",
        "Forbidden",
    }
)


def _is_access_error(err: "ClientError") -> bool:
    """True if a ClientError is a permission/authorization error (not a real
    'control absent' signal). Used so a missing IAM permission surfaces as a
    could-not-assess condition instead of a false non-compliant finding."""
    try:
        return err.response.get("Error", {}).get("Code", "") in _ACCESS_ERROR_CODES
    except AttributeError:
        return False


# Error codes meaning the S3 bucket a data source points to no longer exists.
# This is a distinct, actionable condition (a dangling KB data-source reference
# to a deleted bucket) — NOT "versioning/notifications absent." Surfacing it
# separately avoids a misleading "bucket without versioning" label when the real
# problem is the bucket was deleted out from under the Knowledge Base.
_MISSING_BUCKET_ERROR_CODES = frozenset({"NoSuchBucket", "404", "NotFound"})


def _is_missing_bucket_error(err: "ClientError") -> bool:
    """True if a ClientError indicates the S3 bucket does not exist (deleted /
    dangling data-source reference) rather than a missing control or a missing
    permission."""
    try:
        return (
            err.response.get("Error", {}).get("Code", "") in _MISSING_BUCKET_ERROR_CODES
        )
    except AttributeError:
        return False


# Findings whose name starts with this prefix were emitted because the check
# could not run (e.g., missing IAM permission). They are visible in the report
# (Status="N/A") so a failed/permission-denied check does not silently vanish.
COULD_NOT_ASSESS_PREFIX = "COULD NOT ASSESS: "
FINSERV_GUIDE_URL = (
    "https://d1.awsstatic.com/onedam/marketing-channels/website/public/"
    "global-FinServ-ComplianceGuide-GenAIRisks-public.pdf"
)

# ---------------------------------------------------------------------------
# ResourceInventory data model and helpers (REQ-3, REQ-4.1, REQ-6.4)
# ---------------------------------------------------------------------------


class _Unavailable:
    """Sentinel marking an inventory field whose collection failed. Carries the
    originating exception so dependent checks can reproduce the exact
    COULD_NOT_ASSESS output that the check would have produced had it made the
    call itself (design DD-3)."""

    __slots__ = ("error",)

    def __init__(self, error: Exception):
        self.error = error


@dataclass(frozen=True)
class GuardrailInventory:
    """Per-invocation guardrail enumeration. ``frozen=True`` prevents field
    reassignment; the contained list/dict are read-only *by convention*."""

    summaries: list  # raw list_guardrails 'guardrails' entries
    detail_by_id: dict  # id -> get_guardrail(DRAFT) response (or _Unavailable)


@dataclass(frozen=True)
class KbInventory:
    """Per-invocation Knowledge Base enumeration."""

    summaries: list  # knowledgeBaseSummaries
    data_sources_by_kb: (
        dict  # knowledgeBaseId -> list of dataSourceSummaries (or _Unavailable)
    )
    data_source_detail: dict  # (knowledgeBaseId, dataSourceId) -> get_data_source resp (or _Unavailable)


@dataclass(frozen=True)
class WebAclInventory:
    """Per-invocation WAFv2 REGIONAL Web ACL enumeration."""

    summaries: list  # WebACLs list
    detail_by_id: dict  # Id -> get_web_acl response (or _Unavailable)


@dataclass(frozen=True)
class ResourceInventory:
    """Per-invocation, read-only inventory of shared AWS resources.

    Each field is EITHER the collected data structure OR an ``_Unavailable``
    sentinel (carrying the original exception). Checks MUST NOT mutate the
    lists/dicts stored here; the equivalence tests catch any such mutation.

    This is constructed once in ``lambda_handler`` and injected like
    ``permission_cache`` (design DD-1, INV-6)."""

    lambda_functions: "list | _Unavailable"
    guardrails: "GuardrailInventory | _Unavailable"
    knowledge_bases: "KbInventory | _Unavailable"
    buckets: "list | _Unavailable"
    web_acls: "WebAclInventory | _Unavailable"


def inv_available(field) -> bool:
    """Return True when *field* holds real data; False when it is an
    ``_Unavailable`` sentinel."""
    return not isinstance(field, _Unavailable)


def require(inventory: "ResourceInventory | None", field_name: str):
    """Return ``inventory.<field_name>`` when available; raise the stored
    exception when the field is ``_Unavailable``; raise ``RuntimeError`` when
    ``inventory`` is ``None`` (the test-only default from design DD-2b).

    The caller's existing outer ``try/except`` turns the raised exception into
    ``_error_findings`` → ``COULD_NOT_ASSESS``, matching today's behavior."""
    if inventory is None:
        raise RuntimeError("resource inventory not provided")
    value = getattr(inventory, field_name)
    if isinstance(value, _Unavailable):
        raise value.error
    return value


# ---------------------------------------------------------------------------
# COMPLIANCE_MAP — per-check regulatory framework mappings
#
# Each value is a pipe-separated string of FinServ framework identifiers that
# travel with every finding row in the CSV report (Compliance_Frameworks column).
# This mirrors the ASFF Compliance.RelatedRequirements pattern used by AWS
# Security Hub: compliance metadata is embedded in the finding itself, not kept
# in a separate sidecar document.
#
# Disclaimer: mappings are PRELIMINARY and ILLUSTRATIVE. They have not been
# reviewed by AWS Security Assurance Services, external auditors, or the
# regulators named. Each firm should have its own MRM, Legal, and Compliance
# teams validate these mappings against their specific interpretation of each
# framework before relying on them as audit evidence.
# ---------------------------------------------------------------------------
COMPLIANCE_MAP: Dict[str, str] = {
    # Category 1: Unbounded Consumption
    "FS-01": "FFIEC CAT | DORA Art.6",
    "FS-02": "FFIEC CAT | DORA Art.6 | PCI-DSS 12.3.2",
    "FS-03": "FFIEC CAT | SR 11-7",
    "FS-04": "FFIEC CAT | SR 11-7",
    "FS-05": "FFIEC CAT | DORA Art.6",
    "FS-06": "FFIEC CAT | SR 11-7",
    # Category 2: Excessive Agency
    "FS-07": "SR 11-7 | FFIEC CAT",
    "FS-08": "SR 11-7 | MAS TRM 9.1",
    "FS-09": "FFIEC CAT | SR 11-7",
    "FS-10": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-11": "FFIEC CAT | DORA Art.6",
    # Category 3: Supply Chain Vulnerabilities
    "FS-12": "SR 11-7 | FFIEC CAT | ISO 27001 A.15.2",
    "FS-13": "SR 11-7 | ISO 27001 A.12.5 | FFIEC CAT",
    "FS-14": "SR 11-7 | FFIEC CAT | ISO 27001 A.15.1",
    "FS-15": "SR 11-7 | FFIEC CAT | MAS TRM 9.3",
    "FS-16": "ISO 27001 A.12.6 | FFIEC CAT | DORA Art.6",
    # Category 4: Training Data & Model Poisoning
    "FS-20": "SR 11-7 | FFIEC CAT",
    "FS-21": "SR 11-7 | ISO 27001 A.12.3 | FFIEC CAT",
    # Category 5: Vector & Embedding Weaknesses
    "FS-22": "NYDFS 500 | FFIEC CAT | PCI-DSS 12.3.2",
    "FS-24": "NYDFS 500 | FFIEC CAT | PCI-DSS 12.3.2",
    "FS-25": "NYDFS 500 | PCI-DSS 3.5 | FFIEC CAT",
    "FS-26": "NYDFS 500 | FFIEC CAT | PCI-DSS 1.3",
    # Category 6: Non-Compliant Output
    "FS-27": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-28": "SR 11-7 | FFIEC CAT | NYDFS 500 | MAS TRM 9.2",
    "FS-29": "SR 11-7 | FFIEC CAT | NYDFS 500 | MAS TRM 9.2",
    "FS-30": "SR 11-7 | FFIEC CAT | NYDFS 500",
    # Category 7: Misinformation
    "FS-31": "SR 11-7 | FFIEC CAT",
    "FS-32": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-33": "SR 11-7 | FFIEC CAT | ISO 27001 A.12",
    "FS-34": "SR 11-7 | FFIEC CAT",
    # Category 8: Abusive or Harmful Output
    "FS-35": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-36": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-37": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-38": "SR 11-7 | FFIEC CAT",
    # Category 9: Biased Output
    "FS-39": "SR 11-7 | FFIEC CAT | ECOA/Fair Housing",
    "FS-40": "SR 11-7 | FFIEC CAT | ECOA",
    "FS-41": "SR 11-7 | FFIEC CAT | ECOA Adverse Action",
    "FS-42": "SR 11-7 | FFIEC CAT | MAS TRM 9.3",
    # Category 10: Sensitive Information Disclosure
    "FS-43": "NYDFS 500 | PCI-DSS | GDPR Art.25",
    "FS-44": "NYDFS 500 | FFIEC CAT | PCI-DSS | GDPR Art.25",
    "FS-45": "NYDFS 500 | PCI-DSS | GDPR Art.25",
    "FS-46": "NYDFS 500 | FFIEC CAT | ISO 27001 A.12",
    # Category 11: Hallucination
    "FS-47": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-48": "SR 11-7 | FFIEC CAT",
    "FS-49": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-50": "SR 11-7 | FFIEC CAT",
    # Category 12: Prompt Injection
    "FS-51": "NYDFS 500 | FFIEC CAT | OWASP LLM Top 10",
    "FS-52": "NYDFS 500 | FFIEC CAT | ISO 27001 A.12",
    "FS-53": "NYDFS 500 | PCI-DSS | FFIEC CAT | OWASP LLM Top 10",
    "FS-54": "NYDFS 500 | FFIEC CAT | DORA Art.26 | PCI-DSS 11.4",
    # Category 13: Improper Output Handling
    "FS-55": "FFIEC CAT | OWASP LLM Top 10 | NYDFS 500.06",
    "FS-56": "NYDFS 500 | PCI-DSS | OWASP LLM Top 10 | FFIEC CAT",
    "FS-57": "NYDFS 500.06 | FFIEC CAT | OWASP LLM Top 10",
    "FS-58": "FFIEC CAT | OWASP LLM Top 10 | NYDFS 500.06",
    # Category 14: Off-Topic & Inappropriate Output
    "FS-59": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-60": "SR 11-7 | FFIEC CAT",
    # Category 15: Out-of-Date Training Data
    "FS-61": "SR 11-7 | FFIEC CAT",
    "FS-62": "SR 11-7 | FFIEC CAT | MAS TRM 9.2",
    "FS-63": "SR 11-7 | FFIEC CAT | ISO 27001 A.12",
    # Material Gap Checks
    "FS-65": "FFIEC CAT | ISO 27001 A.12 | SR 11-7",
    "FS-66": "NYDFS 500 | SR 11-7 | MAS TRM 9",
    "FS-67": "SR 11-7 | FFIEC CAT | MAS TRM 9 | PCI-DSS",
    "FS-68": "DORA Art.6 | FFIEC CAT | PCI-DSS | OWASP LLM Top 10",
    "FS-69": "NYDFS 500 | FFIEC CAT | OWASP LLM Top 10",
}


# ---------------------------------------------------------------------------
# SEVERITY METHODOLOGY (see
# docs/SECURITY_CHECKS_RESPONSIBLE_AI_GRC_SEVERITY_METHODOLOGY.md, including its
# #severity-register section)
#
# Severity = property of the CONTROL (the risk it mitigates), assigned once via a
# Likelihood (L) x Impact (I) matrix mapped to the AWS Security Hub ASFF label set,
# then applied to every Passed/Failed row of that control. The N/A family follows a
# fixed disposition rule so "nothing to assess" rows are consistent.
#
#   Matrix (I x L -> label), 1=Low 2=Medium 3=High:
#       I=3: L1->Medium  L2->High    L3->High
#       I=2: L1->Low     L2->Medium  L3->High
#       I=1: L1->Low     L2->Low     L3->Medium
#   (Critical is intentionally NOT used in this round — see methodology §6.)
#
#   Disposition -> severity:
#       PASS / FAIL          -> control severity (from the matrix)
#       NOT_APPLICABLE       -> Informational  (ASFF: "no issue was found")
#       ADVISORY             -> Informational  (no API can verify it)
#       COULD_NOT_ASSESS     -> Low            (unknown state; re-run after fixing access)
#       SOFT_WARNING         -> control severity (intentional non-failing assessed state)
# ---------------------------------------------------------------------------

_SEVERITY_MATRIX = {
    (3, 1): "Medium",
    (3, 2): "High",
    (3, 3): "High",
    (2, 1): "Low",
    (2, 2): "Medium",
    (2, 3): "High",
    (1, 1): "Low",
    (1, 2): "Low",
    (1, 3): "Medium",
}


def _label_from_matrix(impact: int, likelihood: int) -> str:
    """Map an (Impact, Likelihood) pair (each 1-3) to an ASFF severity label."""
    return _SEVERITY_MATRIX[(impact, likelihood)]


# Disposition tiers whose severity is fixed by the disposition, not by I x L.
_DISPOSITION_SEVERITY = {
    "NOT_APPLICABLE": "Informational",
    "ADVISORY": "Informational",
    "COULD_NOT_ASSESS": "Low",
}


# Authoritative per-finding severity register (keyed by finding-name).
# This dict is the enforced source of truth; the Severity Register section of
# docs/SECURITY_CHECKS_RESPONSIBLE_AI_GRC_SEVERITY_METHODOLOGY.md mirrors it. The
# test suite (test_severity_register.py) asserts emitted severities match this map.
# Entries: finding_name -> severity. Disposition and I/L rationale live in the doc.
SEVERITY_REGISTER: Dict[str, str] = {
    # --- FS-00 (not a control: the regional not-applicable row. Registered so
    #     severity drift on it is caught, since FS-00 is absent from the check
    #     registry and a registry-based audit cannot see it.) ---
    "Responsible AI GRC — Regional Scope Not Applicable": "Informational",
    # --- FS-01 (Shield = Low; WAF = Medium) ---
    "AWS Shield Advanced Not Enabled": "Low",
    "AWS Shield Advanced Enabled": "Low",
    "No Regional WAF Web ACLs Found": "Medium",
    "Regional WAF Web ACLs Present": "Medium",
    # --- FS-02 (rate limiting = Medium) ---
    "No API Gateway Usage Plans Found": "Informational",
    "API Gateway Usage Plans Missing Throttle": "Medium",
    "API Gateway Rate Limiting Configured": "Medium",
    # --- FS-03 (token quotas = Medium) ---
    "No Bedrock Token Quotas Returned": "Medium",
    "Bedrock Default Quotas Unavailable — Customization Undetermined": "Medium",
    "Bedrock Token Quotas Customized": "Medium",
    "Bedrock Token Quotas At Default": "Medium",
    # --- FS-04 ---
    "No Cost Anomaly Detection Monitors": "Medium",
    "Cost Anomaly Monitors Do Not Cover Bedrock/SageMaker": "Medium",
    "Cost Anomaly Detection Configured": "Medium",
    # --- FS-05 ---
    "No Bedrock CloudWatch Alarms Found": "Medium",
    "Bedrock CloudWatch Alarms Present": "Medium",
    # --- FS-06 ---
    "No AI/ML Service Budgets Configured": "Medium",
    "AI/ML Service Budgets Configured": "Medium",
    # --- FS-07 (agent action boundaries = High) ---
    "Agent Action Boundary Check": "Informational",
    "Bedrock Agent Overly Broad Action Permissions": "High",
    "Agent Action Boundaries Look Appropriate": "High",
    # --- FS-08 (AgentCore runtime inbound authorizer = High) ---
    "AgentCore Runtime Inbound Authorizer — Access Check": "Low",
    "No AgentCore Runtimes Found": "Informational",
    "AgentCore Runtimes Without Inbound Authorizer": "High",
    "AgentCore Runtimes With Inbound Authorizer Configured": "High",
    "COULD NOT ASSESS: AgentCore Runtime Inbound Authorizer Check": "Low",
    # --- FS-09 ---
    "Agent Lambda Functions Without Concurrency Limits": "Medium",
    "Agent Lambda Concurrency Limits Present": "Medium",
    # --- FS-10 (human-in-the-loop = High) ---
    "Human-in-the-Loop Check — No Agent Workflows Found": "Informational",
    "Human Approval Steps Found in Agent Workflows": "High",
    "Agent Workflows Missing Human Approval Steps": "High",
    # --- FS-11 ---
    "No Agent Rate Alarms Found": "Medium",
    "Agent Rate Alarms Present": "Medium",
    # --- FS-12 (SCPs = High) ---
    "SCP Model Access Check — Not in Organization": "Informational",
    "No Bedrock-Scoped SCPs Found": "High",
    "Bedrock SCPs Found": "High",
    # --- FS-13 ---
    "Models Missing Provenance Tags": "Medium",
    "Model Provenance Tags Present": "Medium",
    # --- FS-14 ---
    "No Model Governance Config Rules Found": "Medium",
    "Model Governance Config Rules Present": "Medium",
    # --- FS-15 (eval jobs exist = Medium; absence is a real FAIL) ---
    "No Bedrock Evaluation Jobs Found": "Medium",
    "Bedrock Evaluation Jobs Present": "Medium",
    # --- FS-16 (ECR scanning = High) ---
    "No ECR Repositories Found": "Informational",
    "ECR Repositories Without Image Scanning": "High",
    "ECR Image Scanning Enabled": "High",
    "ECR Image Scanning Covered by Inspector Enhanced Scanning": "High",
    "COULD NOT ASSESS: ECR Image Scanning Check": "Low",
    # --- FS-20 ---
    "No SageMaker Feature Groups Found": "Informational",
    "Feature Groups Without Offline Store": "Medium",
    "Feature Groups With Offline Store Configured": "Medium",
    "COULD NOT ASSESS: Feature Store Rollback Check": "Low",
    # --- FS-21 (training-data integrity = High) ---
    "No Training Data Buckets Identified": "Informational",
    "Training Data Buckets Without Versioning": "High",
    "Training Data Buckets Have Versioning": "High",
    # --- FS-22 (KB IAM least privilege = High) ---
    "Overly Permissive Knowledge Base IAM Roles": "High",
    "Knowledge Base IAM Permissions Look Appropriate": "High",
    # --- FS-24 (advisory) ---
    "No Knowledge Bases Found": "Informational",
    "ADVISORY: Knowledge Base Metadata Filtering — Manual Review Required": "Informational",
    # --- FS-25 (KB encryption = High) ---
    "No OpenSearch Serverless Collections Found": "Informational",
    "OpenSearch Serverless Collections Using AWS-Owned Encryption Keys": "High",
    "OpenSearch Serverless Collections Using Customer-Managed Keys": "High",
    "COULD NOT ASSESS: OpenSearch Serverless Encryption Check": "Low",
    # --- FS-26 (VPC isolation = High) ---
    "No OpenSearch Serverless Network Policies": "High",
    "OpenSearch Serverless Collections Not VPC-Restricted": "High",
    "OpenSearch Serverless VPC Access Configured": "High",
    # --- FS-27 (contextual grounding = High; ARC = Medium) ---
    "No Guardrails — Contextual Grounding Not Applicable": "Informational",
    "No Guardrails With Contextual Grounding": "High",
    "Contextual Grounding Enabled on Guardrails": "High",
    "Automated Reasoning Policies — Access Check": "Low",
    "No Automated Reasoning Policies Found": "Medium",
    "Automated Reasoning Policies Found": "Medium",
    # --- FS-28 (denied topics = High) ---
    "No Guardrails — Topic Policy Not Applicable": "Informational",
    "No Guardrails With Topic Policies": "High",
    "Topic Policies Configured on CLASSIC Tier": "High",
    "Guardrails With Topic Policies Found": "High",
    # --- FS-29 (advisory) ---
    "ADVISORY: Compliance Disclaimer — Manual Review Required": "Informational",
    # --- FS-30 (advisory — cannot inspect dataset content) ---
    "ADVISORY: Compliance Dataset Coverage — Manual Review Required": "Informational",
    # --- FS-31 ---
    "No Knowledge Base Data Sources Found": "Informational",
    "Knowledge Base Data Sources Past Review Threshold": "Medium",
    "Knowledge Base Data Sources Never Successfully Synced": "Medium",
    "Knowledge Base Data Sources Recently Synced": "Medium",
    "COULD NOT ASSESS: Knowledge Base Data Source Sync Check": "Low",
    # --- FS-32 (advisory) ---
    "ADVISORY: Source Attribution — Manual Review Required": "Informational",
    # --- FS-33 (distinct risks: deleted bucket High, versioning Medium) ---
    "KB Data Source References a Deleted S3 Bucket": "High",
    "KB Data Source Buckets Without Versioning": "Medium",
    "KB Data Source Buckets Have Versioning": "Medium",
    # --- FS-34 ---
    "Legacy Foundation Models Available in Region": "Informational",
    "Foundation Models Are Current": "Medium",
    # --- FS-35 (advisory) ---
    "ADVISORY: Harmful-Content Test Coverage — Manual Review Required": "Informational",
    # --- FS-36 (content filters = High) ---
    "No Guardrails — Content Filters Not Applicable": "Informational",
    "No Guardrails With Content Filters": "High",
    "Guardrail Content Filters on CLASSIC Tier": "High",
    "Guardrails With Content Filters Found": "High",
    # --- FS-37 (advisory) ---
    "ADVISORY: User Feedback Mechanism — Manual Review Required": "Informational",
    # --- FS-38 (word filters = Medium) ---
    "No Guardrails — Word Filters Not Applicable": "Informational",
    "No Guardrails With Word Filters": "Medium",
    "Guardrail Word Filters Configured": "Medium",
    # --- FS-39 (bias = High) ---
    "No SageMaker Clarify Bias Monitoring": "High",
    "SageMaker Clarify Bias Monitoring Schedules Found": "High",
    "SageMaker Clarify Bias Monitoring Schedules Not Running": "High",
    # --- FS-40 (advisory) ---
    "ADVISORY: Bias Dataset Coverage — Manual Review Required": "Informational",
    # --- FS-41 (explainability = High) ---
    "No SageMaker Clarify Explainability Monitoring": "High",
    "SageMaker Clarify Explainability Monitoring Schedules Found": "High",
    "SageMaker Clarify Explainability Schedules Not Running": "High",
    # --- FS-42 (absence is Informational: Bedrock-only estates have no model cards) ---
    "No SageMaker Model Cards Found": "Informational",
    "SageMaker Model Cards Not Approved": "Medium",
    "SageMaker Model Cards Approved": "Medium",
    # --- FS-43 (log data protection = High; N/A when logs never reach CloudWatch) ---
    "Bedrock Invocation Logging Not Enabled": "Informational",
    "Bedrock Invocation Logs Not Delivered to CloudWatch Logs": "Informational",
    "No CloudWatch Logs Data Protection Policies": "High",
    "CloudWatch Logs Data Protection Policies Present": "High",
    "COULD NOT ASSESS: CloudWatch Log PII Masking Check": "Low",
    # --- FS-44 (Macie = High) ---
    "Amazon Macie Not Enabled": "High",
    "Amazon Macie Enabled but Automated Discovery Disabled": "High",
    "Amazon Macie Automated Discovery Enabled": "High",
    "COULD NOT ASSESS: Macie Automated Discovery Status": "Low",
    "COULD NOT ASSESS: Amazon Macie PII Scanning Check": "Low",
    # --- FS-45 (PII filters = High) ---
    "No Guardrails — PII Filters Not Applicable": "Informational",
    "No Guardrails With PII Filters": "High",
    "Guardrail PII Filters Configured": "High",
    # --- FS-46 (classification = Medium) ---
    "No AI/ML Data Buckets Identified": "Informational",
    "AI/ML Buckets Without Data Classification Tags": "Medium",
    "AI/ML Buckets Have Classification Tags": "Medium",
    # --- FS-47 (grounding threshold = High) ---
    "No Guardrails — Grounding Threshold Not Applicable": "Informational",
    "Guardrails With Low Grounding Thresholds": "High",
    "No Guardrails With a Grounding Filter": "High",
    "Guardrail Grounding Thresholds Appropriate": "High",
    # --- FS-48 ---
    "No Active Knowledge Bases for RAG": "Medium",
    "Active Knowledge Bases for RAG Present": "Medium",
    # --- FS-49 (advisory) ---
    "ADVISORY: Hallucination Disclaimer — Manual Review Required": "Informational",
    # --- FS-50 (relevance grounding = Medium) ---
    "No Guardrails With Relevance Grounding Filters": "Medium",
    "Relevance Grounding Filters Present": "Medium",
    # --- FS-51 (prompt attack = High) ---
    "No Guardrails — Prompt Attack Filters Not Applicable": "Informational",
    "No Guardrails With Prompt Attack Filters": "High",
    "Prompt Attack Filters on CLASSIC Tier": "High",
    "Guardrails With Prompt Attack Filters Found": "High",
    # --- FS-52 ---
    "No Bedrock-Related Lambda Functions Found": "Informational",
    "Bedrock Lambda Functions on Deprecated Runtimes": "Medium",
    "Bedrock Lambda Functions on Current Runtimes": "Medium",
    # --- FS-53 (injection rules = High) ---
    "No WAF Web ACLs — Injection Rules Not Applicable": "Informational",
    "WAF ACLs Missing Injection Protection Rules": "High",
    "WAF Injection Protection Rules Present": "High",
    # --- FS-54 (advisory) ---
    "ADVISORY: Penetration Testing — Manual Review Required": "Informational",
    # --- FS-55 ---
    "No Output Validation Functions Found": "Medium",
    "Output Validation Functions Present": "Medium",
    # --- FS-56 (XSS = Medium; now has a FAIL path) ---
    "No WAF ACLs — XSS Prevention Not Applicable": "Informational",
    "WAF ACLs Missing Common Rule Set (XSS)": "Medium",
    "XSS Prevention Common Rule Set Present": "Medium",
    # --- FS-57 (advisory) ---
    "ADVISORY: Output Encoding — Manual Review Required": "Informational",
    # --- FS-58 (advisory) ---
    "ADVISORY: Output Schema Validation — Manual Review Required": "Informational",
    # --- FS-59 (topic allowlist = Medium) ---
    "No Guardrails — Topic Allowlist Not Applicable": "Informational",
    "No Guardrails With Topic Restrictions": "Medium",
    "Topic Restrictions Configured on CLASSIC Tier": "Medium",
    "Guardrail Topic Restrictions Configured": "Medium",
    # --- FS-60 (advisory) ---
    "ADVISORY: Contextual Grounding for Off-Topic Prevention": "Informational",
    # --- FS-61 ---
    "No Automated KB Sync Schedules Detected": "Medium",
    "Automated KB Sync Schedules Present": "Medium",
    # --- FS-62 (advisory) ---
    "ADVISORY: Data Currency Disclaimer — Manual Review Required": "Informational",
    # --- FS-63 (verdict keys off account-side governance, not the region catalogue) ---
    "No Foundation Model Lifecycle Governance Detected": "Medium",
    "Foundation Model Lifecycle Governance Detected": "Medium",
    "COULD NOT ASSESS: Foundation Model Lifecycle Policy Check": "Low",
    # --- FS-65 (distinct risks) ---
    "KB Data Source Buckets Missing S3 Event Notifications": "Medium",
    "KB Data Source S3 Event Notifications Configured": "Medium",
    # --- FS-66 (identity propagation = High) ---
    "AgentCore Identity Propagation — Access Check": "Low",
    "AgentCore Runtimes Without JWT Authorizer": "High",
    "AgentCore Runtimes With JWT Authorizer Configured": "High",
    "COULD NOT ASSESS: AgentCore End-User Identity Propagation Check": "Low",
    # --- FS-67 (transaction thresholds = High) ---
    "No Agent Action-Group Lambda Functions Found": "Informational",
    "Agent Action-Group Lambdas May Lack Transaction Thresholds": "High",
    "Agent Action-Group Lambdas Have Threshold-Named Variables": "High",
    # --- FS-68 (body-size = Medium; now has N/A branch) ---
    "API Gateway Request Body Size Limits Not Enforced": "Medium",
    "API Gateway Request Body Size Limits — Not Applicable": "Informational",
    "API Gateway Request Body Size Limits Configured": "Medium",
    # --- FS-69 ---
    "No Prompt Input Validation Function Found": "Medium",
    "Prompt Input Validation Functions Present": "Medium",
}


def _could_not_assess_row(check_id: str, check_name: str, err: Any) -> Dict[str, Any]:
    """
    Synthesize one visible finding row for a check that errored out and produced
    no rows. Uses Status="N/A", Severity="Low" (the COULD_NOT_ASSESS disposition —
    see SECURITY_CHECKS_RESPONSIBLE_AI_GRC_SEVERITY_METHODOLOGY.md §3.4) so the gap surfaces in the report as an
    unknown/assessment-gap without inflating the Failed count or implying a
    confirmed control failure.
    """
    return create_finding(
        check_id=check_id,
        finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
        finding_details=(
            f"This check could not be completed (error: {err}). The most common cause "
            "is a missing IAM permission for the assessment role; it may also indicate "
            "an unsupported region or an outdated botocore. This control was NOT assessed "
            "— verify the role's permissions and re-run, and assess this control manually "
            "until resolved."
        ),
        resolution=(
            "1. Confirm the assessment role grants the actions this check requires "
            "(see the documented IAM permission set in the README).\n"
            "2. Confirm the service/feature is supported in the assessed region.\n"
            "3. Ensure botocore meets the version floor in requirements.txt.\n"
            "4. Re-run the assessment; assess this control manually until it succeeds."
        ),
        reference="https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_access-denied.html",
        severity="Low",
        status="N/A",
        compliance_frameworks=COMPLIANCE_MAP.get(check_id, ""),
    )


def _self_lambda_name_prefix() -> str:
    """Return the shared name prefix of this assessment's own Lambda functions.

    The assessment deploys its functions as
    ``aiml-security-{stack-name}-{Suffix}``. AWS_LAMBDA_FUNCTION_NAME gives the
    running function's full physical name, so dropping the final ``-{Suffix}``
    segment yields the prefix shared by every sibling assessment function.

    Returns "" when the name does not match that shape (for example under a unit
    test or a local invoke), in which case no self-exclusion is applied.
    """
    own_name = os.environ.get("AWS_LAMBDA_FUNCTION_NAME", "")
    if not own_name.startswith("aiml-security-") or "-" not in own_name:
        return ""
    return own_name.rsplit("-", 1)[0] + "-"


def _is_assessment_own_lambda(function_name: str) -> bool:
    """True when function_name belongs to this assessment's own deployment.

    Name-keyword heuristics elsewhere in this module match on fragments such as
    "finserv" and "agent", which the assessment's own functions satisfy. Without
    this exclusion the assessment reports findings against its own
    infrastructure.
    """
    prefix = _self_lambda_name_prefix()
    return bool(prefix) and function_name.startswith(prefix)


def _describe_schedules(schedules: List[Dict[str, Any]], limit: int = 10) -> str:
    """Render monitoring schedules as name(status, endpoint) for finding details.

    Used by the SageMaker Clarify checks so a finding reports the observed
    MonitoringScheduleStatus rather than implying a schedule is running.
    """
    parts = []
    for s in schedules[:limit]:
        name = s.get("MonitoringScheduleName", "<unnamed>")
        status = s.get("MonitoringScheduleStatus") or "status unknown"
        endpoint = s.get("EndpointName")
        parts.append(f"{name} ({status}{f', endpoint {endpoint}' if endpoint else ''})")
    suffix = "" if len(schedules) <= limit else f" and {len(schedules) - limit} more"
    return f"Schedules: {'; '.join(parts)}{suffix}."


def _no_regional_genai_resources_row(region: str) -> Dict[str, Any]:
    """Visible N/A row used when a target region has no GenAI resource footprint."""
    return create_finding(
        check_id="FS-00",
        finding_name="Responsible AI GRC — Regional Scope Not Applicable",
        finding_details=(
            f"No regional Bedrock, AgentCore, or SageMaker resources were found in {region}; "
            "Responsible AI GRC checks were not applied to this region."
        ),
        resolution="No action required unless GenAI workloads are expected in this region.",
        reference=FINSERV_GUIDE_URL,
        severity="Informational",
        status="N/A",
        region=region,
    )


# ===========================================================================
# CATEGORY 1: UNBOUNDED CONSUMPTION (FS-01 to FS-06)
# Risk: GenAI workloads can be exploited to exhaust compute/cost budgets
# COMPLIANCE_PLACEHOLDER: [FFIEC CAT, DORA Art.6, SR 11-7 Appendix A]
# ===========================================================================


def check_waf_shield_on_bedrock_endpoints(inventory) -> Dict[str, Any]:
    """
    FS-01 — Verify AWS WAF is associated with API Gateway or ALB endpoints
    that front Bedrock/GenAI workloads, and that AWS Shield Advanced is enabled.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT Cyber Risk Management, DORA Art.6 ICT Risk]
    """
    findings = _empty_findings("WAF and Shield Protection Check")
    try:
        shield = boto3.client("shield", config=boto3_config)

        # Check Shield Advanced subscription
        shield_enabled = False
        try:
            shield.describe_subscription()
            shield_enabled = True
        except shield.exceptions.ResourceNotFoundException:
            pass
        except ClientError:
            pass

        # Check WAF Web ACLs exist (regional, covering API GW / ALB)
        # require() raises if inventory is None or the field is _Unavailable,
        # which propagates to the outer except and yields COULD_NOT_ASSESS.
        acls = require(inventory, "web_acls").summaries

        if not shield_enabled:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-01",
                    finding_name="AWS Shield Advanced Not Enabled",
                    finding_details=(
                        "AWS Shield Advanced is not subscribed. GenAI API endpoints are "
                        "vulnerable to volumetric DDoS attacks that can exhaust token quotas "
                        "and inflate costs."
                    ),
                    resolution=(
                        "1. Subscribe to AWS Shield Advanced for DDoS protection.\n"
                        "2. After subscribing, explicitly add resource protections in the "
                        "Shield Advanced console for each Bedrock-facing resource "
                        "(API Gateway stages, ALBs, CloudFront distributions, Route 53 hosted zones). "
                        "Shield Advanced subscription alone does NOT automatically protect resources — "
                        "each resource must be individually added to receive protection.\n"
                        "3. Enable Shield Response Team (SRT) access and configure proactive engagement.\n"
                        "4. Alternatively, use AWS Firewall Manager with a Shield Advanced policy "
                        "to automate resource protection based on tags or resource types."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/shield-chapter.html",
                    severity="Low",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-01"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-01",
                    finding_name="AWS Shield Advanced Enabled",
                    finding_details="AWS Shield Advanced subscription is active.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/shield-chapter.html",
                    severity="Low",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-01"],
                )
            )

        if not acls:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-01",
                    finding_name="No Regional WAF Web ACLs Found",
                    finding_details=(
                        "No AWS WAF regional Web ACLs found. Without WAF, GenAI endpoints "
                        "lack rate-based rules to block abusive callers."
                    ),
                    resolution=(
                        "1. Create a WAF Web ACL with rate-based rules (e.g., 1000 req/5 min per IP).\n"
                        "2. Associate the ACL with API Gateway stages or ALBs fronting Bedrock.\n"
                        "3. Add AWS Managed Rules for known bad inputs."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-01"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-01",
                    finding_name="Regional WAF Web ACLs Present",
                    finding_details=f"Found {len(acls)} regional WAF Web ACL(s).",
                    resolution="Verify ACLs are associated with Bedrock-facing endpoints.",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/waf-chapter.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-01"],
                )
            )
    except Exception as e:
        return _error_findings("WAF and Shield Protection Check", e)
    return findings


def check_api_gateway_rate_limiting() -> Dict[str, Any]:
    """
    FS-02 — Verify API Gateway usage plans enforce throttling on GenAI endpoints.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, DORA Art.6, PCI-DSS 12.3.2]
    """
    findings = _empty_findings("API Gateway Rate Limiting Check")
    try:
        apigw = boto3.client("apigateway", config=boto3_config)
        plans = _paginate(apigw, "get_usage_plans", "items")

        plans_without_throttle = [
            p["name"]
            for p in plans
            if not p.get("throttle") or p["throttle"].get("rateLimit", 0) == 0
        ]

        if not plans:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-02",
                    finding_name="No API Gateway Usage Plans Found",
                    finding_details="No usage plans configured. GenAI API endpoints may have no rate limits.",
                    resolution=(
                        "Create API Gateway usage plans with throttle settings "
                        "(rateLimit and burstLimit) for all Bedrock-facing APIs."
                    ),
                    reference="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-02"],
                )
            )
        elif plans_without_throttle:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-02",
                    finding_name="API Gateway Usage Plans Missing Throttle",
                    finding_details=(
                        f"Usage plans without throttling: {', '.join(plans_without_throttle)}. "
                        "Unbounded API calls can exhaust Bedrock token quotas and inflate costs."
                    ),
                    resolution=(
                        "Set rateLimit and burstLimit on all usage plans associated with "
                        "GenAI API stages. Consider per-consumer API keys with individual quotas."
                    ),
                    reference="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-02"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-02",
                    finding_name="API Gateway Rate Limiting Configured",
                    finding_details=f"All {len(plans)} usage plan(s) have throttle settings.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-request-throttling.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-02"],
                )
            )
    except Exception as e:
        return _error_findings("API Gateway Rate Limiting Check", e)
    return findings


def check_bedrock_token_quotas() -> Dict[str, Any]:
    """
    FS-03 — Check whether Bedrock service quotas for tokens-per-minute (TPM)
    have been reviewed and raised above AWS defaults.

    Token-based quotas are the primary signal. RPM (requests-per-minute) quotas
    are model-specific on the bedrock-runtime endpoint: some models (e.g., Claude
    Opus 4.7/4.8) are governed solely by TPM with no RPM quota; others have both.
    Because RPM applicability varies by model, only TPM quotas drive this verdict
    and an absent RPM quota must never trigger a failure.

    Note: The bedrock-mantle endpoint (OpenAI-compatible, GA May 2026) exposes
    separate input-tokens-per-minute and output-tokens-per-minute quotas also
    under ServiceCode "bedrock". This check focuses on bedrock-runtime on-demand
    TPM quotas; bedrock-mantle quotas are not explicitly separated here.

    Verdict logic (value-based, not adjustability-based):
      - at least one applied token-quota Value > its AWS default  → customized → PASS/Passed
      - all applied token-quota Values == their defaults          → at default → WARN/N-A (soft)
      - no applied token quotas returned                          → WARN/Failed + explanation
      - AWS default quotas could not be retrieved                 → WARN/Failed + "undetermined"
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, SR 11-7]
    """
    findings = _empty_findings("Bedrock Token Quota Review")
    try:
        sq = boto3.client("service-quotas", config=boto3_config)

        # Applied quotas (paginated). TPM quotas are the primary signal; RPM quotas
        # are model-specific and their absence must not trigger a failure verdict.
        applied = []
        for page in sq.get_paginator("list_service_quotas").paginate(
            ServiceCode="bedrock"
        ):
            applied.extend(page.get("Quotas", []))
        token_quotas = [q for q in applied if "token" in q.get("QuotaName", "").lower()]

        # Empty-applied-list branch: no token quotas found at all.
        if not token_quotas:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-03",
                    finding_name="No Bedrock Token Quotas Returned",
                    finding_details=(
                        "No Bedrock token-based service quotas were returned. This may indicate "
                        "a permissions issue (servicequotas:ListServiceQuotas), an unsupported "
                        "region, or that no Bedrock-specific quotas exist for this account. "
                        "Verify manually in the Service Quotas console."
                    ),
                    resolution=(
                        "1. Confirm the assessment role has servicequotas:ListServiceQuotas.\n"
                        "2. Verify Bedrock is available in the assessed region.\n"
                        "3. Review Bedrock token quotas in the Service Quotas console."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/quotas.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-03"],
                )
            )
            return findings

        # AWS default quotas for comparison (paginated).
        default_values = {}
        for page in sq.get_paginator("list_aws_default_service_quotas").paginate(
            ServiceCode="bedrock"
        ):
            for q in page.get("Quotas", []):
                if q.get("QuotaCode") is not None:
                    default_values[q["QuotaCode"]] = q.get("Value")

        # Default-lookup-fail branch: cannot compare without defaults. Do NOT
        # silently compare a value against itself (which would always Fail).
        if not default_values:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-03",
                    finding_name="Bedrock Default Quotas Unavailable — Customization Undetermined",
                    finding_details=(
                        "AWS default service quotas for Bedrock could not be retrieved "
                        "(list_aws_default_service_quotas returned nothing), so whether the "
                        "applied quotas have been customized cannot be determined. This is "
                        "commonly a permissions issue (servicequotas:ListAWSDefaultServiceQuotas) "
                        "or an unsupported region."
                    ),
                    resolution=(
                        "1. Confirm the assessment role has servicequotas:ListAWSDefaultServiceQuotas.\n"
                        "2. Re-run the assessment once defaults are retrievable.\n"
                        "3. Until then, verify Bedrock token quotas manually in the Service Quotas console."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/quotas.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-03"],
                )
            )
            return findings

        # Value-based comparison. An applied Value == default Value is the
        # expected, non-customized state (ListServiceQuotas may return only
        # default values for some quotas) — this is NOT an error. At-default is
        # reported as a soft warning (WARN/N-A), not a failure, since it is a
        # legitimate verified posture.
        any_customized = any(
            q.get("QuotaCode") in default_values
            and default_values[q["QuotaCode"]] is not None
            and q.get("Value", 0) > default_values[q["QuotaCode"]]
            for q in token_quotas
        )

        if any_customized:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-03",
                    finding_name="Bedrock Token Quotas Customized",
                    finding_details=(
                        f"Found {len(token_quotas)} Bedrock token-based quota(s); at least one "
                        "applied value exceeds the AWS default, indicating quotas have been "
                        "reviewed and raised."
                    ),
                    resolution="No action required. Periodically re-review quotas against expected peak load.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/quotas.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-03"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-03",
                    finding_name="Bedrock Token Quotas At Default",
                    finding_details=(
                        f"All {len(token_quotas)} Bedrock token-based quota(s) are at their AWS "
                        "default values — no quota increase has been applied. Running at default "
                        "is a legitimate posture, but it should be a reviewed decision aligned "
                        "with expected peak load rather than an oversight."
                    ),
                    resolution=(
                        "1. Review current Bedrock TPM/TPD quotas in the Service Quotas console.\n"
                        "2. Request increases aligned with expected peak load, or document a "
                        "deliberate decision to remain at default after review.\n"
                        "3. Implement client-side token counting and pre-flight quota checks.\n"
                        "4. Use Bedrock cross-region inference profiles to distribute load."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/quotas.html",
                    severity="Medium",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-03"],
                )
            )
    except Exception as e:
        return _error_findings("Bedrock Token Quota Review", e)
    return findings


def check_cost_anomaly_detection() -> Dict[str, Any]:
    """
    FS-04 — Verify AWS Cost Anomaly Detection monitors are configured for
    Bedrock and SageMaker services.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, SR 11-7 Appendix A]
    """
    findings = _empty_findings("Cost Anomaly Detection Check")
    try:
        ce = boto3.client("ce", config=boto3_config)
        # get_anomaly_monitors is paginated (NextPageToken). Read every page so a
        # Bedrock-covering monitor beyond the first page is not missed (which would
        # otherwise produce a false "no coverage" finding).
        monitors = []
        next_token = None
        while True:
            kwargs = {"NextPageToken": next_token} if next_token else {}
            resp = ce.get_anomaly_monitors(**kwargs)
            monitors.extend(resp.get("AnomalyMonitors", []))
            next_token = resp.get("NextPageToken")
            if not next_token:
                break

        # A monitor provides Bedrock/SageMaker service-level coverage if its
        # spec mentions bedrock (rarely populated for DIMENSIONAL+SERVICE
        # monitors, kept for completeness) OR it is a DIMENSIONAL monitor scoped
        # to the SERVICE dimension. DIMENSIONAL+SERVICE is the operative signal;
        # a DIMENSIONAL monitor on LINKED_ACCOUNT/TAG/COST_CATEGORY does NOT
        # provide service-level Bedrock coverage and must not count.
        bedrock_monitors = [
            m
            for m in monitors
            if "bedrock" in json.dumps(m.get("MonitorSpecification", {})).lower()
            or (
                m.get("MonitorType") == "DIMENSIONAL"
                and m.get("MonitorDimension") == "SERVICE"
            )
        ]

        if not monitors:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-04",
                    finding_name="No Cost Anomaly Detection Monitors",
                    finding_details=(
                        "No AWS Cost Anomaly Detection monitors found. Unexpected spikes in "
                        "Bedrock/SageMaker usage (e.g., from prompt injection loops) will go undetected."
                    ),
                    resolution=(
                        "1. Create a Cost Anomaly Detection monitor scoped to AWS/Bedrock and AWS/SageMaker.\n"
                        "2. Configure alert subscriptions (SNS/email) for anomalies above threshold.\n"
                        "3. Set daily spend budgets with AWS Budgets as a secondary control."
                    ),
                    reference="https://docs.aws.amazon.com/cost-management/latest/userguide/getting-started-ad.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-04"],
                )
            )
        elif not bedrock_monitors:
            # Monitors exist, but none provide Bedrock/SageMaker service-level
            # coverage. This is the previously-masked false positive: the old
            # code passed whenever ANY monitor existed.
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-04",
                    finding_name="Cost Anomaly Monitors Do Not Cover Bedrock/SageMaker",
                    finding_details=(
                        f"Found {len(monitors)} anomaly monitor(s), but none provide service-level "
                        "coverage for Bedrock/SageMaker (no DIMENSIONAL monitor scoped to the SERVICE "
                        "dimension, and no monitor specification referencing Bedrock). A generic or "
                        "linked-account monitor does not detect GenAI cost anomalies."
                    ),
                    resolution=(
                        "1. Create a DIMENSIONAL Cost Anomaly Detection monitor scoped to the SERVICE "
                        "dimension so AWS/Bedrock and AWS/SageMaker are covered.\n"
                        "2. Configure alert subscriptions (SNS/email) for anomalies above threshold.\n"
                        "3. Set daily spend budgets with AWS Budgets as a secondary control."
                    ),
                    reference="https://docs.aws.amazon.com/cost-management/latest/userguide/getting-started-ad.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-04"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-04",
                    finding_name="Cost Anomaly Detection Configured",
                    finding_details=f"Found {len(monitors)} anomaly monitor(s); {len(bedrock_monitors)} provide Bedrock/SageMaker service-level coverage.",
                    resolution="Verify monitors cover Bedrock and SageMaker service dimensions.",
                    reference="https://docs.aws.amazon.com/cost-management/latest/userguide/getting-started-ad.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-04"],
                )
            )
    except Exception as e:
        return _error_findings("Cost Anomaly Detection Check", e)
    return findings


def check_cloudwatch_token_alarms() -> Dict[str, Any]:
    """
    FS-05 — Check for CloudWatch alarms on Bedrock InvocationThrottles and
    TokensProcessed metrics to detect runaway consumption.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, DORA Art.6]
    """
    findings = _empty_findings("CloudWatch Token Usage Alarms Check")
    try:
        cw = boto3.client("cloudwatch", config=boto3_config)
        paginator = cw.get_paginator("describe_alarms")
        all_alarms = []
        for page in paginator.paginate(AlarmTypes=["MetricAlarm"]):
            all_alarms.extend(page.get("MetricAlarms", []))

        bedrock_alarms = [
            a
            for a in all_alarms
            if a.get("Namespace", "").startswith("AWS/Bedrock")
            or "bedrock" in a.get("AlarmName", "").lower()
        ]

        throttle_alarms = [
            a
            for a in bedrock_alarms
            if "throttl" in a.get("MetricName", "").lower()
            or "throttl" in a.get("AlarmName", "").lower()
        ]

        if not bedrock_alarms:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-05",
                    finding_name="No Bedrock CloudWatch Alarms Found",
                    finding_details=(
                        "No CloudWatch alarms found for Bedrock metrics. "
                        "Token exhaustion and throttling events will not trigger operational alerts."
                    ),
                    resolution=(
                        "Create CloudWatch alarms for:\n"
                        "- AWS/Bedrock InvocationThrottles (threshold > 0)\n"
                        "- AWS/Bedrock TokensProcessed (threshold based on quota)\n"
                        "- Custom application-level token counters via EMF"
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-runtime-metrics.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-05"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-05",
                    finding_name="Bedrock CloudWatch Alarms Present",
                    finding_details=(
                        f"Found {len(bedrock_alarms)} Bedrock-related alarm(s), "
                        f"{len(throttle_alarms)} covering throttling."
                    ),
                    resolution="Ensure alarms have SNS actions and are in OK state.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-runtime-metrics.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-05"],
                )
            )
    except Exception as e:
        return _error_findings("CloudWatch Token Usage Alarms Check", e)
    return findings


def check_aws_budgets_for_aiml() -> Dict[str, Any]:
    """
    FS-06 — Verify AWS Budgets are configured with alerts for AI/ML service spend.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, SR 11-7]
    """
    findings = _empty_findings("AWS Budgets AI/ML Spend Check")
    try:
        budgets_client = boto3.client("budgets", config=boto3_config)
        sts = boto3.client("sts", config=boto3_config)
        account_id = sts.get_caller_identity()["Account"]

        def _paginate_budgets(show_filter_expression: bool):
            kwargs = {"AccountId": account_id}
            if show_filter_expression:
                kwargs["ShowFilterExpression"] = True
            pages = []
            for page in budgets_client.get_paginator("describe_budgets").paginate(
                **kwargs
            ):
                pages.extend(page.get("Budgets", []))
            return pages

        # FilterExpression is opt-in: DescribeBudgets only returns it when
        # ShowFilterExpression=True. Modern budgets use the structured
        # FilterExpression instead of the deprecated flat CostFilters map.
        # On an old botocore that does not accept ShowFilterExpression, the call
        # raises ParamValidationError (NOT a ClientError) — degrade gracefully
        # to a CostFilters-only check rather than letting the check vanish.
        try:
            all_budgets = _paginate_budgets(show_filter_expression=True)
        except ParamValidationError:
            logger.warning(
                "describe_budgets does not accept ShowFilterExpression on this "
                "botocore; falling back to CostFilters-only budget detection. "
                "Upgrade botocore to check new-style FilterExpression budgets."
            )
            all_budgets = _paginate_budgets(show_filter_expression=False)

        aiml_budgets = [
            b
            for b in all_budgets
            if any(
                svc in json.dumps(b.get("CostFilters", {})).lower()
                or svc in json.dumps(b.get("FilterExpression", {})).lower()
                for svc in ["bedrock", "sagemaker"]
            )
        ]

        if not aiml_budgets:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-06",
                    finding_name="No AI/ML Service Budgets Configured",
                    finding_details=(
                        "No AWS Budgets found scoped to Bedrock or SageMaker. "
                        "Unbounded GenAI spend can go undetected until the monthly bill."
                    ),
                    resolution=(
                        "1. Create cost budgets for AWS Bedrock and SageMaker with 80%/100% alert thresholds.\n"
                        "2. Add SNS notifications to on-call channels.\n"
                        "3. Consider budget actions to apply IAM deny policies when thresholds are breached."
                    ),
                    reference="https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-06"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-06",
                    finding_name="AI/ML Service Budgets Configured",
                    finding_details=f"Found {len(aiml_budgets)} budget(s) covering AI/ML services.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/cost-management/latest/userguide/budgets-managing-costs.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-06"],
                )
            )
    except Exception as e:
        return _error_findings("AWS Budgets AI/ML Spend Check", e)
    return findings


# ===========================================================================
# CATEGORY 2: EXCESSIVE AGENCY (FS-07 to FS-11)
# Risk: Agents take unintended real-world actions beyond their intended scope
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, DORA Art.6, MAS TRM 9]
# ===========================================================================


def check_bedrock_agent_action_boundaries(permission_cache) -> Dict[str, Any]:
    """
    FS-07 — Verify Bedrock agent execution roles have narrow action boundaries
    (no wildcard actions on sensitive services like s3:*, iam:*, ec2:*).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT Cyber Risk Management]
    """
    if not _has_role_permissions_cache(permission_cache):
        return _permission_cache_unavailable_findings(
            "FS-07", "Agent Action Boundary Check"
        )

    findings = _empty_findings("Agent Action Boundary Check")
    try:
        bedrock_agent = boto3.client("bedrock-agent", config=boto3_config)
        agents = _paginate(bedrock_agent, "list_agents", "agentSummaries")

        if not agents:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-07",
                    finding_name="Agent Action Boundary Check",
                    finding_details="No Bedrock agents found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-permissions.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-07"],
                )
            )
            return findings

        SENSITIVE_WILDCARDS = ["iam:*", "s3:*", "ec2:*", "lambda:*", "*"]
        agents_with_issues = []
        unread = []
        role_permissions = permission_cache.get("role_permissions", {})
        read_errors = _principal_read_errors(permission_cache, "role")

        for agent_summary in agents:
            agent_id = agent_summary["agentId"]
            agent_name = agent_summary["agentName"]
            try:
                detail = bedrock_agent.get_agent(agentId=agent_id)
            except ClientError as e:
                logger.warning(f"Could not describe agent {agent_name}: {e}")
                unread.append(
                    f"agent '{agent_name}' (GetAgent failed: "
                    f"{e.response.get('Error', {}).get('Code', 'error')})"
                )
                continue
            role_arn = detail.get("agent", {}).get("agentResourceRoleArn", "")
            if not role_arn:
                unread.append(
                    f"agent '{agent_name}' (GetAgent returned no execution role ARN)"
                )
                continue
            role_name = role_arn.split("/")[-1]
            agent_unread = False
            if read_errors is not None and role_name in read_errors:
                unread.append(
                    f"agent '{agent_name}' role '{role_name}' (cache read failed at "
                    f"{', '.join(read_errors[role_name])})"
                )
                agent_unread = True
            elif role_name not in role_permissions:
                unread.append(
                    f"agent '{agent_name}' role '{role_name}' (not in the permissions cache)"
                )
                agent_unread = True
            role_perms = role_permissions.get(role_name) or {}
            boundary = role_perms.get("permissions_boundary")
            if boundary is None and "permissions_boundary" in (
                (read_errors or {}).get(role_name, [])
            ):
                continue
            for policy in role_perms.get("attached_policies", []) + role_perms.get(
                "inline_policies", []
            ):
                doc = policy.get("document", {})
                if isinstance(doc, str):
                    try:
                        doc = json.loads(doc)
                    except (ValueError, TypeError):
                        doc = None
                if not isinstance(doc, dict):
                    if not agent_unread:
                        unread.append(
                            f"agent '{agent_name}' role '{role_name}' (policy "
                            f"'{policy.get('name', 'unnamed')}' is not a readable "
                            "policy document)"
                        )
                        agent_unread = True
                    continue
                for stmt in _as_list(doc.get("Statement")):
                    if not isinstance(stmt, dict) or stmt.get("Effect") != "Allow":
                        continue
                    actions = stmt.get("Action", [])
                    if isinstance(actions, str):
                        actions = [actions]
                    for action in actions:
                        if action in SENSITIVE_WILDCARDS and not _boundary_removes(
                            boundary, action
                        ):
                            agents_with_issues.append(
                                f"Agent '{agent_name}' role '{role_name}' allows '{action}'"
                            )

        notes = []
        if unread:
            notes.append(f"Not read ({len(unread)}): " + "; ".join(unread[:10]) + ".")
        if read_errors is None:
            notes.append(UNRECORDED_PRINCIPAL_ERRORS_NOTE)

        if agents_with_issues:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-07",
                    finding_name="Bedrock Agent Overly Broad Action Permissions",
                    finding_details=(
                        "The following agents have execution roles with wildcard or overly broad actions:\n"
                        + "\n".join(f"- {i}" for i in agents_with_issues[:10])
                        + "\n"
                        + " ".join(notes + [SCP_NOT_EVALUATED_NOTE])
                    ),
                    resolution=(
                        "1. Replace wildcard actions with specific actions the agent needs.\n"
                        "2. Apply permission boundaries to agent execution roles.\n"
                        "3. Use resource-level conditions to restrict to specific ARNs.\n"
                        "4. Implement human-in-the-loop approval for high-impact actions."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-permissions.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-07"],
                )
            )
        elif unread:
            findings["status"] = "N/A"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-07",
                    finding_name="Agent Action Boundary Check Incomplete",
                    finding_details=(
                        f"Reviewed {len(agents) - len(unread)} of {len(agents)} "
                        "agent(s) with no wildcard sensitive actions found, but the "
                        "rest could not be assessed. " + " ".join(notes)
                    ),
                    resolution=(
                        "Review the IAM Permission Caching Lambda logs for the "
                        "listed roles (access denied, throttling or deletion) and "
                        "the bedrock:GetAgent error for the listed agents, correct "
                        "the cause, and rerun the assessment."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-permissions.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-07"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-07",
                    finding_name="Agent Action Boundaries Look Appropriate",
                    finding_details=" ".join(
                        [
                            f"Reviewed {len(agents)} agent(s); no wildcard sensitive actions found."
                        ]
                        + notes
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/agents-permissions.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-07"],
                )
            )
    except Exception as e:
        return _error_findings("Agent Action Boundary Check", e)
    return findings


def check_agentcore_runtime_inbound_authorizer() -> Dict[str, Any]:
    """
    FS-08 — Report whether each Bedrock AgentCore runtime has an inbound
    authorizer configured.

    Evidence collected: ListAgentRuntimes (paginated) for the runtime
    inventory, then GetAgentRuntime per runtime to read
    ``authorizerConfiguration``. The list operation does NOT return that field —
    only GetAgentRuntime does — so the per-runtime call is required for the
    check to observe anything at all.

    Deliberately NOT asserted, because none of it is observable here:
      - that an AgentCore Policy Engine resource exists,
      - that policies are associated with every relevant tool,
      - that individual tool calls receive action-level authorization.
    An inbound authorizer gates *callers of the runtime endpoint*; it is not a
    tool-level authorization control. Policy semantics require manual review.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, MAS TRM 9.1]
    """
    check_name = "AgentCore Runtime Inbound Authorizer Check"
    reference = "https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html"
    manual_review = (
        "Inbound authorizer presence does not prove tool-level authorization; "
        "review authorizer and policy semantics manually."
    )
    findings = _empty_findings(check_name)
    try:
        agentcore = boto3.client("bedrock-agentcore-control", config=boto3_config)
        try:
            runtimes = _paginate(agentcore, "list_agent_runtimes", "agentRuntimes")
        except ClientError as e:
            if "AccessDenied" in str(e) or "UnrecognizedClientException" in str(e):
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-08",
                        finding_name="AgentCore Runtime Inbound Authorizer — Access Check",
                        finding_details="Unable to enumerate AgentCore runtimes (access denied or service unavailable in region).",
                        resolution="Ensure assessment role has bedrock-agentcore:ListAgentRuntimes permission.",
                        reference=reference,
                        severity="Low",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-08"],
                    )
                )
                return findings
            raise

        if not runtimes:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-08",
                    finding_name="No AgentCore Runtimes Found",
                    finding_details="No AgentCore runtimes found; inbound authorizer check not applicable.",
                    resolution="If using AgentCore, configure an inbound authorizer on each runtime.",
                    reference=reference,
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-08"],
                )
            )
            return findings

        # authorizerConfiguration is only returned by GetAgentRuntime, so the
        # runtime must be described individually. A runtime we cannot describe
        # is reported as un-assessed rather than silently counted either way.
        with_authorizer: List[str] = []
        without_authorizer: List[str] = []
        undetermined: List[str] = []

        for runtime in runtimes:
            name = runtime.get("agentRuntimeName") or runtime.get("agentRuntimeId", "")
            runtime_id = runtime.get("agentRuntimeId")
            if not runtime_id:
                undetermined.append(f"{name} (no agentRuntimeId in list response)")
                continue
            try:
                detail = agentcore.get_agent_runtime(agentRuntimeId=runtime_id)
            except ClientError as e:
                undetermined.append(f"{name} ({e.response['Error']['Code']})")
                continue
            except Exception as e:  # noqa: BLE001 - per-runtime isolation
                undetermined.append(f"{name} ({type(e).__name__})")
                continue
            if detail.get("authorizerConfiguration"):
                with_authorizer.append(name)
            else:
                without_authorizer.append(name)

        if without_authorizer:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-08",
                    finding_name="AgentCore Runtimes Without Inbound Authorizer",
                    finding_details=(
                        f"Runtimes with no authorizerConfiguration: {', '.join(without_authorizer)}. "
                        "Requests to these runtime endpoints are not gated by an inbound authorizer. "
                        + manual_review
                    ),
                    resolution=(
                        "Configure an inbound authorizer (for example a custom JWT authorizer) on each "
                        "AgentCore runtime, and separately verify tool-level authorization policies."
                    ),
                    reference=reference,
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-08"],
                )
            )

        if with_authorizer:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-08",
                    finding_name="AgentCore Runtimes With Inbound Authorizer Configured",
                    finding_details=(
                        f"{len(with_authorizer)} of {len(runtimes)} runtime(s) have an "
                        f"authorizerConfiguration: {', '.join(with_authorizer)}. "
                        + manual_review
                    ),
                    resolution="No action required for inbound authorizer presence.",
                    reference=reference,
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-08"],
                )
            )

        if undetermined:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-08",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        "Could not read authorizerConfiguration for: "
                        f"{', '.join(undetermined)}."
                    ),
                    resolution="Ensure the assessment role has bedrock-agentcore:GetAgentRuntime permission.",
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-08"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_agent_transaction_limits(inventory) -> Dict[str, Any]:
    """
    FS-09 — Check for application-level transaction/action limits on agents
    via Lambda concurrency limits or Step Functions execution limits.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, SR 11-7]
    """
    findings = _empty_findings("Agent Transaction Limits Check")
    try:
        functions = require(inventory, "lambda_functions")

        # Look for agent-related Lambda functions without reserved concurrency
        agent_lambdas = [
            f
            for f in functions
            if any(
                kw in f["FunctionName"].lower() for kw in ["agent", "bedrock", "aiml"]
            )
        ]

        lambda_client = boto3.client("lambda", config=boto3_config)
        lambdas_without_concurrency = []
        for fn in agent_lambdas:
            try:
                config = lambda_client.get_function_concurrency(
                    FunctionName=fn["FunctionName"]
                )
                if not config.get("ReservedConcurrentExecutions"):
                    lambdas_without_concurrency.append(fn["FunctionName"])
            except ClientError:
                lambdas_without_concurrency.append(fn["FunctionName"])

        if lambdas_without_concurrency:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-09",
                    finding_name="Agent Lambda Functions Without Concurrency Limits",
                    finding_details=(
                        f"Agent-related Lambda functions without reserved concurrency: "
                        f"{', '.join(lambdas_without_concurrency[:10])}. "
                        "Unlimited concurrency allows runaway agent loops to exhaust account limits."
                    ),
                    resolution=(
                        "1. Set reserved concurrency on agent Lambda functions.\n"
                        "2. Implement maximum iteration counts in agent orchestration logic.\n"
                        "3. Use Step Functions with MaxConcurrency and timeout states.\n"
                        "4. Add circuit-breaker patterns to agent tool invocations."
                    ),
                    reference="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-09"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-09",
                    finding_name="Agent Lambda Concurrency Limits Present",
                    finding_details=f"Reviewed {len(agent_lambdas)} agent Lambda(s); concurrency limits appear configured.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html",
                    severity="Medium",
                    status="Passed" if agent_lambdas else "N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-09"],
                )
            )
    except Exception as e:
        return _error_findings("Agent Transaction Limits Check", e)
    return findings


def check_human_in_the_loop_for_high_risk_actions() -> Dict[str, Any]:
    """
    FS-10 — Check for Step Functions or SNS-based human approval steps in
    agent workflows that perform high-risk financial actions.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Human-in-the-Loop Approval Check")
    try:
        sfn = boto3.client("stepfunctions", config=boto3_config)
        machines = _paginate(sfn, "list_state_machines", "stateMachines")

        agent_machines = [
            m
            for m in machines
            if any(
                kw in m["name"].lower()
                for kw in ["agent", "approval", "human", "review"]
            )
        ]

        machines_with_wait = []
        for machine in agent_machines:
            defn = sfn.describe_state_machine(
                stateMachineArn=machine["stateMachineArn"]
            ).get("definition", "{}")
            if '"waitForTaskToken"' in defn or '"TaskToken"' in defn:
                machines_with_wait.append(machine["name"])

        if not agent_machines:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-10",
                    finding_name="Human-in-the-Loop Check — No Agent Workflows Found",
                    finding_details=(
                        "No Step Functions state machines with agent/approval naming found. "
                        "Verify that high-risk agent actions (e.g., fund transfers, account changes) "
                        "have human approval gates."
                    ),
                    resolution=(
                        "Implement Step Functions .waitForTaskToken patterns for high-risk agent actions. "
                        "Route approval requests to human reviewers via SNS/SES/Slack."
                    ),
                    reference="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-10"],
                )
            )
        elif machines_with_wait:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-10",
                    finding_name="Human Approval Steps Found in Agent Workflows",
                    finding_details=f"State machines with waitForTaskToken (human approval): {', '.join(machines_with_wait)}.",
                    resolution="No action required. Verify approval routing reaches the correct reviewers.",
                    reference="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-10"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-10",
                    finding_name="Agent Workflows Missing Human Approval Steps",
                    finding_details=(
                        f"Found {len(agent_machines)} agent-related state machine(s) but none use "
                        "waitForTaskToken for human approval. High-risk financial actions may execute autonomously."
                    ),
                    resolution=(
                        "Add .waitForTaskToken states before irreversible financial actions. "
                        "Define risk tiers and require human approval for Tier 1 actions."
                    ),
                    reference="https://docs.aws.amazon.com/step-functions/latest/dg/connect-to-resource.html#connect-wait-token",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-10"],
                )
            )
    except Exception as e:
        return _error_findings("Human-in-the-Loop Approval Check", e)
    return findings


def check_agent_rate_alarms() -> Dict[str, Any]:
    """
    FS-11 — Check for CloudWatch alarms on agent invocation rates to detect
    runaway or looping agent behavior.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, DORA Art.6]
    """
    findings = _empty_findings("Agent Rate Alarms Check")
    try:
        cw = boto3.client("cloudwatch", config=boto3_config)
        paginator = cw.get_paginator("describe_alarms")
        all_alarms = []
        for page in paginator.paginate(AlarmTypes=["MetricAlarm"]):
            all_alarms.extend(page.get("MetricAlarms", []))

        agent_alarms = [
            a
            for a in all_alarms
            if "agent" in a.get("AlarmName", "").lower()
            or "agent" in a.get("Namespace", "").lower()
        ]

        if not agent_alarms:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-11",
                    finding_name="No Agent Rate Alarms Found",
                    finding_details=(
                        "No CloudWatch alarms found for agent invocation rates. "
                        "Looping or runaway agents will not trigger operational alerts."
                    ),
                    resolution=(
                        "Create CloudWatch alarms on:\n"
                        "- Bedrock agent invocation counts (threshold based on expected max)\n"
                        "- Lambda invocation errors for agent functions\n"
                        "- Step Functions execution failures and timeouts"
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-agents-cw-metrics.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-11"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-11",
                    finding_name="Agent Rate Alarms Present",
                    finding_details=f"Found {len(agent_alarms)} agent-related CloudWatch alarm(s).",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/monitoring-agents-cw-metrics.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-11"],
                )
            )
    except Exception as e:
        return _error_findings("Agent Rate Alarms Check", e)
    return findings


# ===========================================================================
# CATEGORY 3: SUPPLY CHAIN VULNERABILITIES (FS-12 to FS-16)
# Risk: Third-party models, datasets, or plugins introduce malicious code/data
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, DORA Art.6, ISO 27001 A.15]
# ===========================================================================


def check_scp_model_access_restrictions() -> Dict[str, Any]:
    """
    FS-12 — Verify SCPs restrict Bedrock model access to an approved model list,
    preventing use of unapproved third-party models.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ISO 27001 A.15.2]
    """
    findings = _empty_findings("SCP Model Access Restriction Check")
    try:
        orgs = boto3.client("organizations", config=boto3_config)
        try:
            policies = _paginate(
                orgs, "list_policies", "Policies", Filter="SERVICE_CONTROL_POLICY"
            )
        except ClientError as e:
            if "AccessDenied" in str(e) or "AWSOrganizationsNotInUseException" in str(
                e
            ):
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-12",
                        finding_name="SCP Model Access Check — Not in Organization",
                        finding_details="Account is not part of an AWS Organization or lacks SCP read access.",
                        resolution="If using AWS Organizations, ensure SCPs restrict Bedrock model access to approved models.",
                        reference="https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html",
                        severity="Informational",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-12"],
                    )
                )
                return findings
            raise

        bedrock_scps = []
        for policy in policies:
            doc_response = orgs.describe_policy(PolicyId=policy["Id"])
            doc = json.loads(doc_response["Policy"]["Content"])
            if "bedrock" in json.dumps(doc).lower():
                bedrock_scps.append(policy["Name"])

        if not bedrock_scps:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-12",
                    finding_name="No Bedrock-Scoped SCPs Found",
                    finding_details=(
                        "No Service Control Policies reference Bedrock. "
                        "Without SCPs, any account in the organization can access any Bedrock model, "
                        "including unapproved third-party models."
                    ),
                    resolution=(
                        "1. Create an SCP that denies bedrock:InvokeModel, "
                        "bedrock:InvokeModelWithResponseStream, and "
                        "bedrock:CreateModelInvocationJob outside approved model access.\n"
                        "2. Use Resource or NotResource with approved foundation-model, "
                        "custom-model, provisioned-model, and inference-profile ARNs to "
                        "express the allowlist.\n"
                        "3. Maintain a model inventory and update the SCP when models are approved/retired."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-12"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-12",
                    finding_name="Bedrock SCPs Found",
                    finding_details=f"SCPs referencing Bedrock: {', '.join(bedrock_scps)}.",
                    resolution=(
                        "Verify the SCPs deny inference outside approved model and "
                        "inference-profile ARNs using Resource or NotResource scoping."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/security_iam_id-based-policy-examples.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-12"],
                )
            )
    except Exception as e:
        return _error_findings("SCP Model Access Restriction Check", e)
    return findings


def check_model_inventory_tagging() -> Dict[str, Any]:
    """
    FS-13 — Check that custom Bedrock models and SageMaker models are tagged
    with provenance metadata (source, version, approval-date).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, ISO 27001 A.12.5, FFIEC CAT]
    """
    findings = _empty_findings("Model Inventory Tagging Check")
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)
        sm = boto3.client("sagemaker", config=boto3_config)
        REQUIRED_TAGS = {"source", "version", "approval-date"}

        untagged_models = []

        # Check Bedrock custom models
        for model in _paginate(bedrock, "list_custom_models", "modelSummaries"):
            tags_response = bedrock.list_tags_for_resource(
                resourceARN=model["modelArn"]
            )
            tag_keys = {t["key"].lower() for t in tags_response.get("tags", [])}
            missing = REQUIRED_TAGS - tag_keys
            if missing:
                untagged_models.append(
                    f"Bedrock model '{model['modelName']}' missing tags: {missing}"
                )

        # Check SageMaker registered models
        for model in _paginate(sm, "list_models", "Models"):
            tags_response = sm.list_tags(ResourceArn=model["ModelArn"])
            tag_keys = {t["Key"].lower() for t in tags_response.get("Tags", [])}
            missing = REQUIRED_TAGS - tag_keys
            if missing:
                untagged_models.append(
                    f"SageMaker model '{model['ModelName']}' missing tags: {missing}"
                )

        if untagged_models:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-13",
                    finding_name="Models Missing Provenance Tags",
                    finding_details=(
                        f"{len(untagged_models)} model(s) missing required provenance tags:\n"
                        + "\n".join(f"- {m}" for m in untagged_models[:10])
                    ),
                    resolution=(
                        "Tag all models with: source (e.g., 'aws-marketplace', 'internal'), "
                        "version, and approval-date. "
                        "Enforce tagging via SCP or AWS Config rule."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/tagging.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-13"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-13",
                    finding_name="Model Provenance Tags Present",
                    finding_details="All reviewed models have required provenance tags.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/tagging.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-13"],
                )
            )
    except Exception as e:
        return _error_findings("Model Inventory Tagging Check", e)
    return findings


def check_model_onboarding_governance() -> Dict[str, Any]:
    """
    FS-14 — Check for AWS Config rules or Service Catalog constraints that
    enforce model onboarding governance (approved sources only).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ISO 27001 A.15.1]
    """
    findings = _empty_findings("Model Onboarding Governance Check")
    try:
        config = boto3.client("config", config=boto3_config)
        rules = _paginate(config, "describe_config_rules", "ConfigRules")

        bedrock_rules = [
            r
            for r in rules
            if "bedrock" in r.get("ConfigRuleName", "").lower()
            or "model" in r.get("ConfigRuleName", "").lower()
        ]

        if not bedrock_rules:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-14",
                    finding_name="No Model Governance Config Rules Found",
                    finding_details=(
                        "No AWS Config rules found for Bedrock model governance. "
                        "Unapproved models may be deployed without detection."
                    ),
                    resolution=(
                        "1. Create custom AWS Config rules to detect use of non-approved Bedrock models.\n"
                        "2. Use AWS Service Catalog to publish approved model configurations.\n"
                        "3. Implement a model risk management (MRM) process per SR 11-7."
                    ),
                    reference="https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-14"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-14",
                    finding_name="Model Governance Config Rules Present",
                    finding_details=f"Found {len(bedrock_rules)} model-related Config rule(s).",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/config/latest/developerguide/evaluate-config.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-14"],
                )
            )
    except Exception as e:
        return _error_findings("Model Onboarding Governance Check", e)
    return findings


def check_bedrock_model_evaluation_adversarial() -> Dict[str, Any]:
    """
    FS-15 — Check whether Bedrock Model Evaluation jobs include adversarial
    test datasets (robustness/red-team evaluations).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.3]
    """
    findings = _empty_findings("Adversarial Model Evaluation Check")
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)
        evals = _paginate(bedrock, "list_evaluation_jobs", "jobSummaries")

        if not evals:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-15",
                    finding_name="No Bedrock Evaluation Jobs Found",
                    finding_details=(
                        "No Bedrock Model Evaluation jobs found. Models have not been evaluated "
                        "for adversarial robustness. Model-risk management (SR 11-7) "
                        "expects documented model validation/evaluation."
                    ),
                    resolution=(
                        "1. Run Bedrock Model Evaluation with adversarial/red-team datasets.\n"
                        "2. Use FMEval library for automated robustness testing.\n"
                        "3. Schedule periodic re-evaluation after model updates."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-automatic.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-15"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-15",
                    finding_name="Bedrock Evaluation Jobs Present",
                    finding_details=f"Found {len(evals)} evaluation job(s). Verify adversarial datasets are included.",
                    resolution="Ensure evaluation datasets include adversarial/red-team test cases.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-automatic.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-15"],
                )
            )
    except Exception as e:
        return _error_findings("Adversarial Model Evaluation Check", e)
    return findings


def check_ecr_image_scanning() -> Dict[str, Any]:
    """
    FS-16 — Report whether ECR repositories that may hold model containers are
    covered by vulnerability scanning, from either mechanism.

    Evidence collected: DescribeRepositories for
    ``imageScanningConfiguration.scanOnPush`` per repository, plus
    inspector2 BatchGetAccountStatus for ``resourceState.ecr.status``.

    Both mechanisms must be considered together. Amazon Inspector enhanced
    scanning is account-wide and continuously scans ECR repositories,
    superseding per-repository scan-on-push. An earlier revision read only
    scanOnPush and therefore raised a High finding for every repository in an
    Inspector-enabled account — verified live against an account with
    resourceState.ecr=ENABLED and five repositories at scanOnPush=false.

    A subsequent revision fixed that but introduced a related defect: a
    ClientError from BatchGetAccountStatus was caught and the Inspector state
    set to an "UNKNOWN (...)" string, which then compared unequal to
    "ENABLED" the same way "DISABLED" would. So a permissions gap on the
    Inspector call was indistinguishable from Inspector genuinely being off,
    and any repository without scan-on-push produced a Failed finding even
    though whether Inspector covered it was never actually determined. The
    Inspector lookup failure is now tracked separately and reported as
    COULD NOT ASSESS whenever it is the reason a repository cannot be
    classified, rather than defaulting to "not enabled".

    That still missed a case: BatchGetAccountStatus can fail *without*
    raising. Verified live — an account ID Inspector cannot resolve comes
    back as a normal 200 response, ``{"accounts": [], "failedAccounts":
    [{"accountId": ..., "errorCode": "ACCESS_DENIED", ...}]}``, so the
    ClientError handler never runs and the account is simply absent from the
    array the code iterated. The status is now matched to the queried
    account ID explicitly (not assumed to be the first entry); a matching
    failedAccounts entry, or the account appearing in neither array, both set
    the same unknown-reason path as a raised ClientError.

    Deliberately NOT asserted:
      - that any image has actually been scanned,
      - that scan findings have been triaged or remediated,
      - that a repository holds model containers at all (scope is every
        repository in the region, not only AI/ML ones).

    COMPLIANCE_PLACEHOLDER: [ISO 27001 A.12.6, FFIEC CAT, DORA Art.6]
    """
    findings = _empty_findings("ECR Image Scanning Check")
    try:
        ecr = boto3.client("ecr", config=boto3_config)
        repos = _paginate(ecr, "describe_repositories", "repositories")

        if not repos:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-16",
                    finding_name="No ECR Repositories Found",
                    finding_details="No ECR repositories found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-16"],
                )
            )
            return findings

        # Inspector enhanced scanning is account-wide and continuously scans ECR
        # repositories, superseding per-repository scan-on-push. Reporting
        # scanOnPush=false as a failure without checking it produces a false
        # positive on every repository in an Inspector-enabled account.
        #
        # inspector_unknown_reason is kept separate from inspector_ecr_state so
        # a lookup failure can never be compared equal or unequal to "ENABLED" —
        # collapsing it into a state string is what let a permissions gap on
        # this call default to "not enabled" and produce a false Failed finding.
        #
        # BatchGetAccountStatus can also fail *without* raising: a 200 response
        # can report the requested account in failedAccounts instead of
        # accounts (verified live — an account Inspector cannot resolve comes
        # back as {"accounts": [], "failedAccounts": [{"accountId": ...,
        # "errorCode": ...}]} with no exception at all), or in principle omit
        # it from both. The account is matched explicitly by ID rather than
        # trusting accounts[0], and any of those three outcomes — a matching
        # failedAccounts entry, or no entry anywhere — sets
        # inspector_unknown_reason so it is never mistaken for "not enabled".
        inspector_ecr_state = None
        inspector_unknown_reason: Optional[str] = None
        try:
            inspector = boto3.client("inspector2", config=boto3_config)
            account_id = boto3.client("sts", config=boto3_config).get_caller_identity()[
                "Account"
            ]
            status = inspector.batch_get_account_status(accountIds=[account_id])
            matched = next(
                (
                    a
                    for a in status.get("accounts", [])
                    if a.get("accountId") == account_id
                ),
                None,
            )
            if matched is not None:
                inspector_ecr_state = (
                    matched.get("resourceState", {}).get("ecr", {}).get("status")
                )
            else:
                failed = next(
                    (
                        f
                        for f in status.get("failedAccounts", [])
                        if f.get("accountId") == account_id
                    ),
                    None,
                )
                inspector_unknown_reason = (
                    failed.get("errorCode", "BATCH_GET_ACCOUNT_STATUS_FAILED")
                    if failed is not None
                    else "ACCOUNT_STATUS_NOT_RETURNED"
                )
        except ClientError as e:
            inspector_unknown_reason = e.response["Error"]["Code"]
        except Exception as e:  # noqa: BLE001 - Inspector is advisory context here
            inspector_unknown_reason = type(e).__name__

        enhanced_scanning = inspector_ecr_state == "ENABLED"

        repos_without_scanning = [
            r["repositoryName"]
            for r in repos
            if not r.get("imageScanningConfiguration", {}).get("scanOnPush", False)
        ]

        if repos_without_scanning and inspector_unknown_reason:
            # Whether Inspector covers these repositories is unknown, not
            # false — reporting Failed here would be exactly the false
            # failure this check exists to avoid.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-16",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}ECR Image Scanning Check",
                    finding_details=(
                        f"{len(repos_without_scanning)} repository(ies) do not set scan-on-push "
                        f"({', '.join(sorted(repos_without_scanning)[:10])}), and whether Amazon "
                        "Inspector enhanced scanning covers them could not be determined "
                        f"(BatchGetAccountStatus did not return a usable status: "
                        f"{inspector_unknown_reason}). This is a permissions or availability gap, "
                        "not evidence that these repositories are unscanned."
                    ),
                    resolution=(
                        "Ensure the assessment role has inspector2:BatchGetAccountStatus "
                        "permission, then re-run the assessment."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html",
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-16"],
                )
            )
        elif repos_without_scanning and enhanced_scanning:
            # Covered by Inspector: report as passed, naming the compensating
            # control rather than raising a High finding the operator cannot act on.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-16",
                    finding_name="ECR Image Scanning Covered by Inspector Enhanced Scanning",
                    finding_details=(
                        f"Amazon Inspector enhanced scanning for ECR is ENABLED account-wide, so all "
                        f"{len(repos)} repository(ies) are continuously scanned. "
                        f"{len(repos_without_scanning)} repository(ies) do not set scan-on-push "
                        f"({', '.join(sorted(repos_without_scanning)[:10])}), which is expected when "
                        "enhanced scanning supersedes basic scanning."
                    ),
                    resolution=(
                        "No action required while Inspector enhanced scanning stays enabled. "
                        "If it is disabled, enable scan-on-push per repository."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-16"],
                )
            )
        elif repos_without_scanning:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-16",
                    finding_name="ECR Repositories Without Image Scanning",
                    finding_details=(
                        f"{len(repos_without_scanning)} ECR repo(s) without scan-on-push: "
                        f"{', '.join(sorted(repos_without_scanning)[:10])}. "
                        f"Amazon Inspector enhanced scanning for ECR is not enabled "
                        f"(state: {inspector_ecr_state}), so these repositories have no "
                        "vulnerability scanning from either mechanism."
                    ),
                    resolution=(
                        "Enable scan-on-push for all ECR repositories containing model containers. "
                        "Consider enabling Enhanced Scanning (Inspector) for CVE detection."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-16"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-16",
                    finding_name="ECR Image Scanning Enabled",
                    finding_details=(
                        f"All {len(repos)} ECR repo(s) have scan-on-push enabled. "
                        f"Inspector enhanced scanning for ECR state: {inspector_ecr_state}."
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonECR/latest/userguide/image-scanning.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-16"],
                )
            )
    except Exception as e:
        return _error_findings("ECR Image Scanning Check", e)
    return findings


# ===========================================================================
# CATEGORY 4: TRAINING DATA & MODEL POISONING (FS-17 to FS-21)
# Risk: Malicious data corrupts model behavior during training or fine-tuning
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.3, ISO 27001 A.12]
#
# NOTE: FS-17 (Model Monitor Data Quality → SM-07), FS-18 (Model Drift Detection → SM-23),
# and FS-19 (Model Registry Approval → SM-22) are merged into upstream checks.
# See extension notes in SECURITY_CHECKS_RESPONSIBLE_AI_GRC.md.
# ===========================================================================


def check_feature_store_rollback_capability() -> Dict[str, Any]:
    """
    FS-20 — Report whether each SageMaker Feature Group has an offline store,
    which is the precondition for rolling back poisoned feature data.

    Evidence collected: ListFeatureGroups for the inventory, then
    DescribeFeatureGroup per group to read ``OfflineStoreConfig``.

    Field note: ``OfflineStoreStatus`` is NOT a usable signal. It is absent
    from ListFeatureGroups summaries and from DescribeFeatureGroup responses
    even for groups that do have an offline store — verified against a live
    account where a group with a valid OfflineStoreConfig S3Uri returned no
    OfflineStoreStatus at all. An earlier revision tested
    ``OfflineStoreStatus.Status != "Active"``, which therefore flagged every
    group and made the passing branch unreachable.

    Deliberately NOT asserted:
      - that offline-store data is retained, versioned, or complete,
      - that a rollback has ever been tested,
      - that the offline store bucket is protected against deletion.
    Offline-store presence is a precondition for rollback, not evidence of it.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    findings = _empty_findings("Feature Store Rollback Check")
    try:
        sm = boto3.client("sagemaker", config=boto3_config)
        groups = _paginate(sm, "list_feature_groups", "FeatureGroupSummaries")

        if not groups:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-20",
                    finding_name="No SageMaker Feature Groups Found",
                    finding_details="No SageMaker Feature Store groups found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-20"],
                )
            )
            return findings

        # OfflineStoreStatus is absent from ListFeatureGroups summaries AND from
        # DescribeFeatureGroup responses even for groups that do have an offline
        # store (verified against a live account), so it cannot decide this.
        # The authoritative signal is the presence of OfflineStoreConfig, which
        # only DescribeFeatureGroup returns.
        groups_without_offline: List[str] = []
        groups_with_offline: List[str] = []
        undetermined: List[str] = []
        for g in groups:
            name = g["FeatureGroupName"]
            try:
                detail = sm.describe_feature_group(FeatureGroupName=name)
            except ClientError as e:
                undetermined.append(f"{name} ({e.response['Error']['Code']})")
                continue
            except Exception as e:  # noqa: BLE001 - per-group isolation
                undetermined.append(f"{name} ({type(e).__name__})")
                continue
            if detail.get("OfflineStoreConfig"):
                groups_with_offline.append(name)
            else:
                groups_without_offline.append(name)

        if undetermined:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-20",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}Feature Store Rollback Check",
                    finding_details=(
                        f"Could not read OfflineStoreConfig for: {', '.join(undetermined)}."
                    ),
                    resolution=(
                        "Ensure the assessment role has sagemaker:DescribeFeatureGroup permission."
                    ),
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store-offline.html",
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-20"],
                )
            )

        if groups_without_offline:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-20",
                    finding_name="Feature Groups Without Offline Store",
                    finding_details=(
                        f"{len(groups_without_offline)} feature group(s) have no OfflineStoreConfig: "
                        f"{', '.join(sorted(groups_without_offline)[:10])}. "
                        "Without an offline store, historical feature data cannot be used for rollback."
                    ),
                    resolution=(
                        "1. Enable offline store (S3-backed) for all production feature groups.\n"
                        "2. Enable S3 versioning on the offline store bucket.\n"
                        "3. Document rollback procedures for poisoned feature data."
                    ),
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store-offline.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-20"],
                )
            )
        if groups_with_offline:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-20",
                    finding_name="Feature Groups With Offline Store Configured",
                    finding_details=(
                        f"{len(groups_with_offline)} of {len(groups)} feature group(s) have an "
                        f"OfflineStoreConfig: {', '.join(sorted(groups_with_offline)[:10])}. "
                        "Offline-store presence enables rollback; it does not prove the offline "
                        "data is retained, versioned, or complete."
                    ),
                    resolution=(
                        "1. Enable S3 versioning on each offline store bucket.\n"
                        "2. Document rollback procedures for poisoned feature data."
                    ),
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/feature-store-offline.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-20"],
                )
            )
    except Exception as e:
        return _error_findings("Feature Store Rollback Check", e)
    return findings


def check_training_data_s3_versioning(inventory) -> Dict[str, Any]:
    """
    FS-21 — Verify S3 buckets used for training data have versioning enabled
    to support rollback of poisoned datasets.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, ISO 27001 A.12.3, FFIEC CAT]
    """
    findings = _empty_findings("Training Data S3 Versioning Check")
    try:
        buckets = require(inventory, "buckets")
        s3 = boto3.client("s3", config=boto3_config)

        training_buckets = [
            b
            for b in buckets
            if any(
                kw in b["Name"].lower()
                for kw in ["train", "dataset", "model", "sagemaker", "bedrock"]
            )
        ]

        if not training_buckets:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-21",
                    finding_name="No Training Data Buckets Identified",
                    finding_details="No S3 buckets with training/model naming found.",
                    resolution="Tag training data buckets and enable versioning.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-21"],
                )
            )
            return findings

        unversioned = []
        for bucket in training_buckets:
            try:
                versioning = s3.get_bucket_versioning(Bucket=bucket["Name"])
            except ClientError as e:
                # An access error means we could not read versioning; re-raise so
                # it surfaces as could-not-assess rather than a false finding, and
                # so one inaccessible bucket does not abort the whole check.
                if _is_access_error(e):
                    raise
                logger.warning(
                    f"Could not check versioning for bucket {bucket['Name']}: {e}"
                )
                unversioned.append(f"{bucket['Name']} (error)")
                continue
            if versioning.get("Status") != "Enabled":
                unversioned.append(bucket["Name"])

        if unversioned:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-21",
                    finding_name="Training Data Buckets Without Versioning",
                    finding_details=(
                        f"{len(unversioned)} training data bucket(s) without versioning: "
                        f"{', '.join(unversioned[:10])}."
                    ),
                    resolution=(
                        "Enable S3 versioning on all training data buckets. "
                        "Consider enabling MFA Delete for additional protection against poisoning."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-21"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-21",
                    finding_name="Training Data Buckets Have Versioning",
                    finding_details=f"All {len(training_buckets)} training bucket(s) have versioning enabled.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/Versioning.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-21"],
                )
            )
    except Exception as e:
        return _error_findings("Training Data S3 Versioning Check", e)
    return findings


# ===========================================================================
# CATEGORY 5: VECTOR & EMBEDDING WEAKNESSES (FS-22 to FS-26)
# Risk: Knowledge base / RAG vector stores are improperly secured
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500.06, PCI-DSS 12.3.2]
# ===========================================================================


def _is_overbroad_kb_action(action: Any) -> bool:
    """True if an IAM action grants overly broad Bedrock/Knowledge Base access:
    the full wildcard, a service-wide Bedrock wildcard, or ANY partial wildcard
    within the Bedrock IAM namespace (for example, 'bedrock:Invoke*')."""
    if not isinstance(action, str):
        return False
    a = action.lower()
    if a in ("*", "bedrock:*"):
        return True
    if a.endswith("*") and a.startswith("bedrock:"):
        return True
    return False


_KB_ACTIONS_WITH_RESOURCE_SCOPE = frozenset(
    {
        # Amazon Bedrock service authorization reference: actions with a
        # knowledge-base resource type can be scoped to Knowledge Base ARNs.
        "bedrock:allowvendedlogdeliveryforresource",
        "bedrock:associateagentknowledgebase",
        "bedrock:createdatasource",
        "bedrock:deletedatasource",
        "bedrock:deleteknowledgebase",
        "bedrock:deleteknowledgebasedocuments",
        "bedrock:deleteresourcepolicy",
        "bedrock:disassociateagentknowledgebase",
        "bedrock:getagentknowledgebase",
        "bedrock:getdatasource",
        "bedrock:getingestionjob",
        "bedrock:getknowledgebase",
        "bedrock:getknowledgebasedocuments",
        "bedrock:getresourcepolicy",
        "bedrock:ingestknowledgebasedocuments",
        "bedrock:listdatasources",
        "bedrock:listingestionjobs",
        "bedrock:listknowledgebasedocuments",
        "bedrock:listtagsforresource",
        "bedrock:putresourcepolicy",
        "bedrock:retrieve",
        "bedrock:startingestionjob",
        "bedrock:stopingestionjob",
        "bedrock:tagresource",
        "bedrock:untagresource",
        "bedrock:updatedatasource",
        "bedrock:updateagentknowledgebase",
        "bedrock:updateknowledgebase",
    }
)


def _kb_action_requires_resource_scope(action: Any) -> bool:
    """Return whether an exact KB action supports a knowledge-base ARN."""
    return isinstance(action, str) and action.lower() in _KB_ACTIONS_WITH_RESOURCE_SCOPE


def check_knowledge_base_iam_least_privilege(permission_cache) -> Dict[str, Any]:
    """
    FS-22 — Verify IAM roles accessing Bedrock Knowledge Bases follow
    least privilege.

    Wildcard Bedrock actions are always broad. Exact KB actions are flagged on
    ``Resource: "*"`` only when IAM supports knowledge-base resource ARNs;
    account-level discovery APIs such as ``ListKnowledgeBases`` legitimately
    require a wildcard resource and must not create self-findings.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 12.3.2]
    """
    if not _has_role_permissions_cache(permission_cache):
        return _permission_cache_unavailable_findings(
            "FS-22", "Knowledge Base IAM Least Privilege Check"
        )

    findings = _empty_findings("Knowledge Base IAM Least Privilege Check")
    try:
        issues = []
        read_errors = _principal_read_errors(permission_cache, "role")
        for role_name, perms in (
            (permission_cache or {}).get("role_permissions", {}).items()
        ):
            if not isinstance(perms, dict):
                continue
            boundary = perms.get("permissions_boundary")
            if boundary is None and "permissions_boundary" in (
                (read_errors or {}).get(role_name, [])
            ):
                continue
            for policy in (perms.get("attached_policies", []) or []) + (
                perms.get("inline_policies", []) or []
            ):
                if not isinstance(policy, dict):
                    continue
                doc = policy.get("document", {})
                if isinstance(doc, str):
                    try:
                        doc = json.loads(doc)
                    except (ValueError, TypeError):
                        continue
                if not isinstance(doc, dict):
                    continue
                # IAM allows Statement to be a single object (dict) or a list.
                # Normalize to a list so iterating never yields statement *keys*
                # (the cause of the 'str' object has no attribute 'get' crash).
                statements = doc.get("Statement", [])
                if isinstance(statements, dict):
                    statements = [statements]
                for stmt in statements:
                    if not isinstance(stmt, dict):
                        continue
                    if stmt.get("Effect") != "Allow":
                        continue
                    # NotAction Allow ("allow everything except …") is inherently
                    # broad and the antithesis of least privilege — flag it.
                    if "NotAction" in stmt:
                        issues.append(
                            f"Role '{role_name}' uses a NotAction Allow (overly broad — "
                            "grants all actions except those listed)"
                        )
                    resources = stmt.get("Resource", [])
                    if isinstance(resources, str):
                        resources = [resources]
                    unscoped_resource = "*" in resources
                    actions = stmt.get("Action", [])
                    if isinstance(actions, str):
                        actions = [actions]
                    for action in actions:
                        if isinstance(action, str) and _boundary_removes(
                            boundary, action
                        ):
                            continue
                        if _is_overbroad_kb_action(action):
                            issues.append(f"Role '{role_name}' allows '{action}'")
                        elif unscoped_resource and _kb_action_requires_resource_scope(
                            action
                        ):
                            issues.append(
                                f"Role '{role_name}' allows '{action}' on Resource '*' "
                                "(no ARN scoping to supported Bedrock resources)"
                            )

        unread = sorted(read_errors or {})
        notes = []
        if unread:
            notes.append(
                f"{len(unread)} role(s) could not be fully read from the IAM "
                f"permissions cache, so their grants are unknown: {_name_list(unread)}."
            )
        if read_errors is None:
            notes.append(UNRECORDED_PRINCIPAL_ERRORS_NOTE)

        if issues:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-22",
                    finding_name="Overly Permissive Knowledge Base IAM Roles",
                    finding_details=(
                        f"{len(issues)} broad Knowledge Base permission issue(s):\n"
                        + "\n".join(f"- {i}" for i in issues[:10])
                        + "\n"
                        + " ".join(notes + [SCP_NOT_EVALUATED_NOTE])
                    ),
                    resolution=(
                        "Replace wildcard Bedrock actions (e.g. bedrock:*) with "
                        "specific actions, and scope each action to its supported "
                        "Bedrock resource ARN(s) (such as a Knowledge Base or "
                        "Agent ARN) instead of Resource '*'."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-22"],
                )
            )
        elif unread:
            findings["status"] = "N/A"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-22",
                    finding_name="Knowledge Base IAM Least Privilege Check Incomplete",
                    finding_details=(
                        "No wildcard Bedrock permissions and no unscoped "
                        "(Resource '*') Knowledge Base actions found in the roles "
                        "that were read. " + " ".join(notes)
                    ),
                    resolution=(
                        "Review the IAM Permission Caching Lambda logs for the "
                        "listed roles (access denied, throttling or deletion), "
                        "correct the cause, and rerun the assessment."
                    ),
                    reference="https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-22"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-22",
                    finding_name="Knowledge Base IAM Permissions Look Appropriate",
                    finding_details=" ".join(
                        [
                            "No wildcard Bedrock permissions and no unscoped "
                            "(Resource '*') Knowledge Base actions found in reviewed "
                            "roles."
                        ]
                        + notes
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/security-iam-awsmanpol.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-22"],
                )
            )
    except Exception as e:
        return _error_findings("Knowledge Base IAM Least Privilege Check", e)
    return findings


def check_knowledge_base_metadata_filtering(inventory) -> Dict[str, Any]:
    """
    FS-24 — Check that Bedrock Knowledge Bases have metadata fields configured
    to support tenant-level filtering (multi-tenancy isolation).
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 12.3.2]
    """
    findings = _empty_findings("Knowledge Base Metadata Filtering Check")
    try:
        kbs = require(inventory, "knowledge_bases").summaries

        if not kbs:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-24",
                    finding_name="No Knowledge Bases Found",
                    finding_details="No Bedrock Knowledge Bases found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-test-config.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-24"],
                )
            )
            return findings

        # Advisory check — metadata filtering is a design pattern, not directly inspectable
        findings["csv_data"].append(
            create_finding(
                check_id="FS-24",
                finding_name="ADVISORY: Knowledge Base Metadata Filtering — Manual Review Required",
                finding_details=(
                    f"Found {len(kbs)} Knowledge Base(s). Tenant-isolation metadata filtering is a "
                    "design pattern that cannot be verified via API — manual review required. "
                    "Verify that metadata attributes (e.g., tenantId, classification) are indexed "
                    "and that Retrieve calls include RetrievalFilter conditions for tenant isolation."
                ),
                resolution=(
                    "1. Add metadata fields (tenantId, dataClassification) to KB data sources.\n"
                    "2. Pass RetrievalFilter in all Retrieve/RetrieveAndGenerate calls.\n"
                    "3. Validate filters in integration tests to prevent cross-tenant data leakage."
                ),
                reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-test-config.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP["FS-24"],
            )
        )
    except Exception as e:
        return _error_findings("Knowledge Base Metadata Filtering Check", e)
    return findings


def check_opensearch_serverless_encryption() -> Dict[str, Any]:
    """
    FS-25 — Report the effective encryption key of each OpenSearch Serverless
    collection used as a Bedrock Knowledge Base vector store.

    Evidence collected: ListCollections, reading ``kmsKeyArn`` per collection.

    Signal note: ``kmsKeyArn`` is the effective key for the collection. It is
    the literal string ``"auto"`` when the collection uses an AWS-owned key,
    and a KMS key ARN when it uses a customer-managed key (CMK) — verified
    live against two purpose-built collections.

    Why not the encryption policy documents: ListSecurityPolicies summaries do
    NOT include the policy document (only type, name, policyVersion,
    description and dates), so an earlier revision's
    ``json.loads(policy.get("policy", "{}"))`` always produced ``{}``. The
    subsequent ``"AWSOwnedKey" not in "{}"`` test was therefore always true,
    every policy was classified as CMK, and the Failed branch was unreachable.
    Verified live: an account with six AWS-owned-key policies reported
    "7 use a customer-managed KMS key". Reading the documents would require
    GetSecurityPolicy per policy and then matching policy resource patterns to
    collections; ``kmsKeyArn`` gives the effective answer directly.

    Scope note: the verdict keys off collections, not policies. An encryption
    policy with no matching collection protects nothing, so orphaned policies
    are not reported as a failure.

    Deliberately NOT asserted:
      - that the CMK's key policy, rotation or grants are appropriate,
      - that a collection is actually used by a Knowledge Base,
      - anything about non-OpenSearch vector stores (S3 Vectors, Aurora,
        Pinecone), whose encryption must be verified separately.

    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, PCI-DSS 3.5, FFIEC CAT]
    """
    check_name = "OpenSearch Serverless Encryption Check"
    reference = (
        "https://docs.aws.amazon.com/opensearch-service/latest/developerguide/"
        "serverless-encryption.html"
    )
    findings = _empty_findings(check_name)
    try:
        oss = boto3.client("opensearchserverless", config=boto3_config)
        try:
            collections = _paginate(oss, "list_collections", "collectionSummaries")
        except ClientError as e:
            if "AccessDenied" in str(e) or "UnrecognizedClientException" in str(e):
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-25",
                        finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                        finding_details=(
                            "Unable to enumerate OpenSearch Serverless collections "
                            "(access denied or service unavailable in region)."
                        ),
                        resolution="Ensure the assessment role has aoss:ListCollections permission.",
                        reference=reference,
                        severity="Low",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-25"],
                    )
                )
                return findings
            raise

        if not collections:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-25",
                    finding_name="No OpenSearch Serverless Collections Found",
                    finding_details=(
                        "No OpenSearch Serverless collections exist in this region, so there is "
                        "no OpenSearch vector-store data at rest to encrypt. If Bedrock Knowledge "
                        "Bases use a different vector store (S3 Vectors, Aurora, Pinecone), "
                        "verify its encryption separately."
                    ),
                    resolution=(
                        "If you adopt OpenSearch Serverless as a Bedrock KB vector store, create "
                        "an encryption policy specifying a customer-managed KMS key before "
                        "creating the collection."
                    ),
                    reference=reference,
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-25"],
                )
            )
            return findings

        aws_owned: List[str] = []
        customer_managed: List[str] = []
        undetermined: List[str] = []
        for collection in collections:
            name = collection.get("name") or collection.get("id", "")
            key = (collection.get("kmsKeyArn") or "").strip()
            if not key:
                undetermined.append(f"{name} (no kmsKeyArn in response)")
            elif key.lower() == "auto":
                aws_owned.append(name)
            else:
                customer_managed.append(name)

        if aws_owned:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-25",
                    finding_name="OpenSearch Serverless Collections Using AWS-Owned Encryption Keys",
                    finding_details=(
                        f"{len(aws_owned)} of {len(collections)} collection(s) are encrypted with "
                        f'an AWS-owned key (kmsKeyArn="auto"): '
                        f"{', '.join(sorted(aws_owned)[:10])}. Financial-services data-protection "
                        "controls typically require a customer-managed KMS key for key lifecycle "
                        "control and auditability."
                    ),
                    resolution=(
                        "1. Create a customer-managed KMS key and grant aoss.amazonaws.com the "
                        "required key permissions.\n"
                        "2. Create an encryption policy for the collection with AWSOwnedKey=false "
                        "and KmsARN set to that key.\n"
                        "3. The encryption key is fixed at collection creation, so the collection "
                        "must be recreated and re-indexed to change it."
                    ),
                    reference=reference,
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-25"],
                )
            )

        if customer_managed:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-25",
                    finding_name="OpenSearch Serverless Collections Using Customer-Managed Keys",
                    finding_details=(
                        f"{len(customer_managed)} of {len(collections)} collection(s) are "
                        f"encrypted with a customer-managed KMS key: "
                        f"{', '.join(sorted(customer_managed)[:10])}. Key policy, rotation and "
                        "grants are not assessed here."
                    ),
                    resolution="Review each key's policy, rotation schedule and grants separately.",
                    reference=reference,
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-25"],
                )
            )

        if undetermined:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-25",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        f"Could not determine the encryption key for: {', '.join(undetermined)}."
                    ),
                    resolution="Re-run the assessment; if it persists, inspect the collection in the console.",
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-25"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_knowledge_base_vpc_access() -> Dict[str, Any]:
    """
    FS-26 — Verify OpenSearch Serverless collections have VPC access policies
    restricting access to private network endpoints.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 1.3]
    """
    findings = _empty_findings("Knowledge Base VPC Access Check")
    try:
        oss = boto3.client("opensearchserverless", config=boto3_config)
        network_policies = _paginate(
            oss,
            "list_security_policies",
            "securityPolicySummaries",
            type="network",
        )

        if not network_policies:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-26",
                    finding_name="No OpenSearch Serverless Network Policies",
                    finding_details=(
                        "No OpenSearch Serverless network policies found. "
                        "Vector store collections may be publicly accessible."
                    ),
                    resolution=(
                        "Create network security policies for OpenSearch Serverless collections "
                        "restricting access to VPC endpoints only."
                    ),
                    reference="https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-network.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-26"],
                )
            )
        else:
            vpc_policies = []
            for policy in network_policies:
                doc = json.loads(policy.get("policy", "{}"))
                if "vpc" in json.dumps(doc).lower():
                    vpc_policies.append(policy["name"])

            if not vpc_policies:
                findings["status"] = "WARN"
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-26",
                        finding_name="OpenSearch Serverless Collections Not VPC-Restricted",
                        finding_details=(
                            f"Found {len(network_policies)} network policy(ies) but none restrict to VPC. "
                            "Vector stores may be accessible from the public internet."
                        ),
                        resolution=(
                            "Update network policies to allow access only from VPC endpoints. "
                            "Create an OpenSearch Serverless VPC endpoint in your VPC."
                        ),
                        reference="https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-network.html",
                        severity="High",
                        status="Failed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-26"],
                    )
                )
            else:
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-26",
                        finding_name="OpenSearch Serverless VPC Access Configured",
                        finding_details=f"{len(vpc_policies)} network policy(ies) restrict to VPC.",
                        resolution="No action required.",
                        reference="https://docs.aws.amazon.com/opensearch-service/latest/developerguide/serverless-network.html",
                        severity="High",
                        status="Passed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-26"],
                    )
                )
    except Exception as e:
        return _error_findings("Knowledge Base VPC Access Check", e)
    return findings


# ===========================================================================
# CATEGORY 6: NON-COMPLIANT OUTPUT (FS-27 to FS-30)
# Risk: GenAI outputs violate regulatory requirements (e.g., fair lending, disclosures)
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500, MAS TRM 9.2]
# ===========================================================================


def check_guardrail_contextual_grounding(inventory) -> Dict[str, Any]:
    """
    FS-27 — Check whether Bedrock Guardrails have contextual grounding checks
    configured to validate that outputs are grounded in the provided context and
    are relevant to the user query.

    NOTE: This check verifies *contextual grounding* (guardrails-grounding) — a
    separate, independent feature from Automated Reasoning checks (ARC). True ARC
    is assessed in check_automated_reasoning_policies() below. Both controls are
    recommended for FinServ workloads; they complement each other:
      - Contextual grounding: thresholded relevance/grounding filter applied per
        inference call (no policy authoring required).
      - Automated Reasoning: policy-based formal verification of factual claims
        against a customer-authored business-rules document (GA August 2025;
        limited to US/EU regions; requires bedrock:ListAutomatedReasoningPolicies).

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Guardrail Contextual Grounding Check")
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-27",
                    finding_name="No Guardrails — Contextual Grounding Not Applicable",
                    finding_details="No Bedrock Guardrails configured. Configure a Bedrock guardrail before evaluating its financial-services policy coverage.",
                    resolution=(
                        "Configure Bedrock Guardrails with contextual grounding checks "
                        "(grounding threshold ≥0.7 and relevance threshold ≥0.7 for regulated GenAI use cases)."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                )
            )
            return findings

        guardrails_with_grounding = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            if detail.get("contextualGroundingPolicy"):
                guardrails_with_grounding.append(g["name"])

        if not guardrails_with_grounding:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-27",
                    finding_name="No Guardrails With Contextual Grounding",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have contextual grounding "
                        "filters enabled. Without grounding checks, outputs that are not supported "
                        "by the source context (hallucinations, regulatory violations) will not be "
                        "filtered at inference time."
                    ),
                    resolution=(
                        "Enable contextual grounding checks on Bedrock Guardrails:\n"
                        "- Set grounding threshold ≥0.7 (filters responses not supported by source context)\n"
                        "- Set relevance threshold ≥0.7 (filters off-topic responses)\n"
                        "Also consider enabling Automated Reasoning checks (bedrock:ListAutomatedReasoningPolicies) "
                        "for policy-based formal verification of factual claims — see FS-27 ARC check."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-27",
                    finding_name="Contextual Grounding Enabled on Guardrails",
                    finding_details=f"Guardrails with contextual grounding: {', '.join(guardrails_with_grounding)}.",
                    resolution=(
                        "No action required for contextual grounding. "
                        "Also consider enabling Automated Reasoning checks for formal policy verification."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                )
            )
    except Exception as e:
        return _error_findings("Guardrail Contextual Grounding Check", e)
    return findings


def check_automated_reasoning_policies() -> Dict[str, Any]:
    """
    FS-27b — Check whether Bedrock Automated Reasoning policies have been
    created to provide formal, policy-based verification of GenAI factual claims.

    Automated Reasoning checks (ARC) — GA August 2025 — use formal verification
    to detect hallucinations and ensure outputs comply with authored business rules
    (e.g., loan eligibility criteria, regulatory thresholds). Unlike contextual
    grounding (a threshold applied per call), ARC requires authoring an Automated
    Reasoning Policy document containing the rules to verify against.

    Regions supported (verify against current AWS docs at run time —
    https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-automated-reasoning-checks.html):
    AWS GovCloud (US), us-east-1, us-east-2, us-west-2, eu-central-1, eu-west-1,
    eu-west-3. The list expands over time; treat a region miss as "verify
    availability", not a hard limitation.

    IAM action required: bedrock:ListAutomatedReasoningPolicies

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Automated Reasoning Policies Check")
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)

        try:
            policies = _paginate(
                bedrock,
                "list_automated_reasoning_policies",
                "automatedReasoningPolicySummaries",
            )
        except ClientError as e:
            if _is_access_error(e):
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-27",
                        finding_name="Automated Reasoning Policies — Access Check",
                        finding_details=(
                            "Access denied or service unavailable when listing Automated Reasoning "
                            "policies. The IAM action name (bedrock:ListAutomatedReasoningPolicies) "
                            "is correct, so the most likely causes are, in order: (1) the assessment "
                            "Lambda execution role was deployed before this action was added and "
                            "has not been updated; (2) an AWS Organizations SCP or permission boundary "
                            "denies this newer Bedrock action; (3) the region does not "
                            "support ARC. ARC is available in AWS GovCloud (US) and a growing set "
                            "of commercial regions (e.g., us-east-1, us-east-2, us-west-2, "
                            "eu-central-1, eu-west-1, eu-west-3) — verify the current list in the "
                            "AWS documentation."
                        ),
                        resolution=(
                            "1. Run CodeBuild to redeploy the SAM application so the SAM-created "
                            "ResponsibleAIGRCAssessmentFunction execution role picks up "
                            "bedrock:ListAutomatedReasoningPolicies from "
                            "aiml-security-assessment/template.yaml or "
                            "template-multi-account.yaml.\n"
                            "2. Check for an Organizations SCP / permission boundary denying the action.\n"
                            "3. Confirm the assessed region supports Automated Reasoning checks.\n"
                            "4. Re-run the assessment after redeploying."
                        ),
                        reference="https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_access-denied.html",
                        severity="Low",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                    )
                )
                return findings
            raise

        if not policies:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-27",
                    finding_name="No Automated Reasoning Policies Found",
                    finding_details=(
                        "No Bedrock Automated Reasoning policies have been created. "
                        "ARC (GA August 2025) uses formal verification to guarantee that GenAI "
                        "outputs comply with authored business rules — e.g., loan criteria, "
                        "regulatory thresholds, policy constraints. Without ARC policies, "
                        "factual accuracy of outputs is not formally verified, only heuristically "
                        "filtered by contextual grounding thresholds."
                    ),
                    resolution=(
                        "1. In the Amazon Bedrock console → Guardrails → Automated Reasoning, "
                        "create a policy document encoding your business rules "
                        "(e.g., eligibility criteria, rate limits, regulatory thresholds).\n"
                        "2. Associate the ARC policy with your guardrail "
                        "(automatedReasoningPolicy.policies field in CreateGuardrail/UpdateGuardrail).\n"
                        "3. Set confidenceThreshold on the policy to control strictness.\n"
                        "4. ARC requires cross-Region inference — ensure your guardrail has a "
                        "guardrailProfileArn configured (crossRegionDetails in GetGuardrail response).\n"
                        "5. Reference: AWS Announcement — Automated Reasoning checks GA (August 2025)."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-automated-reasoning-checks.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-27",
                    finding_name="Automated Reasoning Policies Found",
                    finding_details=(
                        f"Found {len(policies)} Automated Reasoning policy(ies): "
                        f"{', '.join(p['name'] for p in policies[:5])}. "
                        "Verify policies are associated with active guardrails via the "
                        "automatedReasoningPolicy field in GetGuardrail."
                    ),
                    resolution=(
                        "Confirm each ARC policy is referenced in a guardrail's "
                        "automatedReasoningPolicy.policies list and that the "
                        "guardrail is applied to your Bedrock inference calls."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-automated-reasoning-checks.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-27"],
                )
            )
    except Exception as e:
        return _error_findings("Automated Reasoning Policies Check", e)
    return findings


def check_guardrail_denied_topics_financial(inventory) -> Dict[str, Any]:
    """
    FS-28 — Report whether Bedrock Guardrails have a topic policy configured,
    and which denied-topic tier each uses.

    Evidence collected: presence of ``topicPolicy.topics`` and the value of
    ``topicPolicy.tier.tierName`` from GetGuardrail.

    Deliberately NOT asserted:
      - that the configured topics cover regulated financial advice,
      - that topic definitions are complete or correctly scoped,
      - that the policy applies to every relevant application,
      - that each topic is enabled — ``inputEnabled`` and ``outputEnabled`` are
        not inspected, so a present topic may be inactive on either path.
    Topic coverage is a semantic question and stays a manual review.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500, MAS TRM 9.2]
    """
    check_name = "Guardrail Topic Policy Check"
    manual_review = (
        "Topic-policy presence does not establish coverage of regulated financial "
        "advice; review topic definitions and their input/output enablement manually."
    )
    findings = _empty_findings(check_name)
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-28",
                    finding_name="No Guardrails — Topic Policy Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with denied topics for regulated financial content.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-28"],
                )
            )
            return findings

        guardrails_with_topics = []
        topics_classic_tier = []
        topics_unknown_tier = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            topic_policy = detail.get("topicPolicy", {})
            if topic_policy.get("topics"):
                guardrails_with_topics.append(g["name"])
                # Denied topics support tiers (GA June 2025). STANDARD adds broader
                # language support and improved detection but requires cross-region
                # inference. An ABSENT tier is reported as unknown rather than
                # assumed CLASSIC — defaulting it would report an assumption as an
                # observation.
                tier = topic_policy.get("tier", {}).get("tierName")
                if tier == "CLASSIC":
                    topics_classic_tier.append(g["name"])
                elif not tier:
                    topics_unknown_tier.append(g["name"])

        tier_note = ""
        if topics_unknown_tier:
            tier_note = (
                " Tier not reported by GetGuardrail for: "
                f"{', '.join(topics_unknown_tier)} (tier unknown, not assumed CLASSIC)."
            )

        if not guardrails_with_topics:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-28",
                    finding_name="No Guardrails With Topic Policies",
                    finding_details=(
                        "No guardrails have topic policies configured, so no denied-topic "
                        "control is in place on any guardrail."
                    ),
                    resolution=(
                        "Add denied topics to guardrails for:\n"
                        "- Specific investment advice (securities recommendations)\n"
                        "- Credit/lending decisions\n"
                        "- Insurance underwriting advice\n"
                        "- Tax advice beyond general information\n"
                        "When authoring denied-topic policies, use existing compliance materials "
                        "as the source: employee policies, training materials, procedure documents, "
                        "and incident reports (as recommended in PDF \u00a71.2.1 Practical guidance). "
                        "Consider the STANDARD tier (GA June 2025) for broader language support; "
                        "it requires cross-region inference on the guardrail."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-28"],
                )
            )
        elif topics_classic_tier:
            # Note: topics_classic_tier and topics_unknown_tier are not mutually
            # exclusive — a guardrail set can have some CLASSIC-tier members and
            # some with no tier reported. tier_note (computed above, independent
            # of which branch fires) discloses any unknown-tier guardrails here
            # too, so a mixed-tier result never reports Passed on CLASSIC alone
            # while silently omitting the unknown-tier guardrails.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-28",
                    finding_name="Topic Policies Configured on CLASSIC Tier",
                    finding_details=(
                        f"Guardrails with topic policies: {', '.join(guardrails_with_topics)}. "
                        f"The following report the CLASSIC tier: {', '.join(topics_classic_tier)}. "
                        "CLASSIC tier supports English, French, and Spanish only. The STANDARD tier "
                        "(GA June 2025) provides broader language support and improved detection for "
                        f"denied topics.{tier_note} {manual_review}"
                    ),
                    resolution=(
                        "Verify topics cover regulated financial advice categories. For multilingual "
                        "deployments, consider upgrading denied topics to the STANDARD tier "
                        "(set topicsTierConfig.tierName=STANDARD via UpdateGuardrail; requires a "
                        "cross-region inference profile on the guardrail). When authoring denied-topic "
                        "policies, use existing compliance materials as the source: employee policies, "
                        "training materials, procedure documents, and incident reports "
                        "(PDF \u00a71.2.1 Practical guidance)."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-28"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-28",
                    finding_name="Guardrails With Topic Policies Found",
                    finding_details=(
                        f"Guardrails with topic policies: {', '.join(guardrails_with_topics)}."
                        f"{tier_note} {manual_review}"
                    ),
                    resolution=(
                        "Verify topics cover regulated financial advice categories. "
                        "When authoring or updating denied-topic policies, use existing compliance "
                        "materials as the source: employee policies, training materials, procedure "
                        "documents, and incident reports (as recommended in PDF \u00a71.2.1 Practical guidance)."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-28"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_compliance_disclaimer_in_outputs() -> Dict[str, Any]:
    """
    FS-29 — Advisory check: verify application-level disclaimers are added to
    GenAI outputs for regulated financial content (not directly checkable via API).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500, MAS TRM 9.2]
    """
    findings = _empty_findings("Compliance Disclaimer Check")
    # This is an advisory/manual check — no AWS API can verify application-level disclaimers
    findings["csv_data"].append(
        create_finding(
            check_id="FS-29",
            finding_name="ADVISORY: Compliance Disclaimer — Manual Review Required",
            finding_details=(
                "Application-level compliance disclaimers cannot be verified via AWS APIs. "
                "Manual review required to confirm GenAI outputs include required regulatory disclosures."
            ),
            resolution=(
                "1. Implement post-processing to append required disclaimers to GenAI outputs.\n"
                "2. Use Bedrock Guardrails word filters to block outputs that omit required disclosures.\n"
                "3. Document disclaimer requirements in the AI use case register.\n"
                "4. Test disclaimer presence in QA/UAT before production deployment."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-29"],
        )
    )
    return findings


def check_bedrock_evaluation_compliance_datasets() -> Dict[str, Any]:
    """
    FS-30 — Advisory: Bedrock Model Evaluation jobs should use compliance-specific
    datasets (e.g., fair lending, UDAP, ECOA test cases).

    The Bedrock evaluation-job APIs do not expose dataset *content*, so whether a
    job actually includes compliance test cases cannot be verified programmatically.
    This is therefore an advisory (manual-review) check. The existence of evaluation
    jobs at all is the verifiable control and is assessed by FS-15.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500]
    """
    findings = _empty_findings("Compliance Evaluation Datasets Check")
    try:
        findings["csv_data"].append(
            create_finding(
                check_id="FS-30",
                finding_name="ADVISORY: Compliance Dataset Coverage — Manual Review Required",
                finding_details=(
                    "Bedrock model-evaluation dataset content cannot be inspected via API. "
                    "Manually verify your model-evaluation jobs include compliance-specific "
                    "datasets (fair lending/ECOA, Fair Housing Act, UDAP/UDAAP, AML/KYC edge cases). "
                    "Whether any evaluation jobs exist at all is assessed by FS-15."
                ),
                resolution=(
                    "Run Bedrock Model Evaluation with compliance-specific datasets:\n"
                    "- Fair lending test cases (ECOA, Fair Housing Act)\n"
                    "- UDAP/UDAAP unfair/deceptive practice scenarios\n"
                    "- AML/KYC edge cases"
                ),
                reference="https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-automatic.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP["FS-30"],
            )
        )
    except Exception as e:
        return _error_findings("Compliance Evaluation Datasets Check", e)
    return findings


# ===========================================================================
# CATEGORY 7: MISINFORMATION (FS-31 to FS-34)
# Risk: GenAI outputs contain false or misleading financial information
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2, NYDFS 500]
# ===========================================================================


def check_knowledge_base_data_source_sync(inventory) -> Dict[str, Any]:
    """
    FS-31 — Report how long ago each Bedrock Knowledge Base data source last
    completed an ingestion job.

    Evidence collected: the shared KB inventory for data sources, then
    ListIngestionJobs per data source, taking the most recent job whose status
    is COMPLETE and reading its updatedAt (falling back to startedAt).

    Timestamp note: a data source's own ``updatedAt`` is when its CONFIGURATION
    last changed, not when it last synced. An earlier revision used that field
    and labelled it "last synced". Verified live: a source whose configuration
    was last modified 2025-11-21 had in fact completed an ingestion on
    2025-11-26, so the config timestamp overstated staleness by five days. In
    the opposite direction, a source edited yesterday that had never synced
    would have been reported as current.

    Deliberately NOT asserted:
      - that a completed ingestion indexed the content you expected,
      - that the source data itself is current,
      - that the configured cadence matches your currency requirement.

    Staleness threshold: AWS does not prescribe a maximum data age for Knowledge
    Bases — the appropriate cadence is workload-specific (intraday for market
    data, weekly/monthly for slow-changing regulatory guidance). This check uses
    a default of 7 days purely as a review prompt; treat a finding as "confirm
    your data-currency requirement is met," not as an AWS-mandated failure.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    # Default review threshold (days). Not an AWS requirement — a configurable
    # heuristic. Firms with stricter or looser currency needs should adjust this.
    STALE_AFTER_DAYS = 7
    findings = _empty_findings("Knowledge Base Data Source Sync Check")
    try:
        kb_inv = require(inventory, "knowledge_bases")
        kbs = kb_inv.summaries

        if not kbs:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name="No Knowledge Bases Found",
                    finding_details="No Bedrock Knowledge Bases found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )
            return findings

        stale_kbs = []
        never_synced = []
        undetermined = []
        fresh = []
        now = datetime.now(timezone.utc)
        agent = boto3.client("bedrock-agent", config=boto3_config)
        for kb in kbs:
            kb_id = kb["knowledgeBaseId"]
            sources = kb_inv.data_sources_by_kb.get(kb_id, [])
            if isinstance(sources, _Unavailable):
                raise sources.error
            for source in sources:
                label = f"KB '{kb['name']}' source '{source['name']}'"
                # A data source's own updatedAt is when its CONFIGURATION last
                # changed, not when it last synced. Ingestion jobs carry the
                # sync timestamps. Verified live: a source whose config was
                # last touched 2025-11-21 had in fact completed an ingestion on
                # 2025-11-26, so the config timestamp overstated staleness.
                try:
                    jobs = _paginate(
                        agent,
                        "list_ingestion_jobs",
                        "ingestionJobSummaries",
                        knowledgeBaseId=kb_id,
                        dataSourceId=source["dataSourceId"],
                    )
                except ClientError as e:
                    undetermined.append(f"{label} ({e.response['Error']['Code']})")
                    continue
                except Exception as e:  # noqa: BLE001 - per-source isolation
                    undetermined.append(f"{label} ({type(e).__name__})")
                    continue

                completed = [
                    j for j in jobs if (j.get("status") or "").upper() == "COMPLETE"
                ]
                if not completed:
                    never_synced.append(
                        f"{label} has no completed ingestion job"
                        + (f" ({len(jobs)} job(s) in other states)" if jobs else "")
                    )
                    continue
                latest = max(
                    completed,
                    key=lambda j: j.get("updatedAt") or j.get("startedAt") or now,
                )
                synced_at = latest.get("updatedAt") or latest.get("startedAt")
                if synced_at:
                    age_days = (now - synced_at).days
                    if age_days > STALE_AFTER_DAYS:
                        stale_kbs.append(
                            f"{label} last completed ingestion {age_days} days ago"
                        )
                    else:
                        fresh.append(label)
                else:
                    undetermined.append(f"{label} (completed job carried no timestamp)")

        if never_synced:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name="Knowledge Base Data Sources Never Successfully Synced",
                    finding_details=(
                        f"{len(never_synced)} data source(s) have no completed ingestion job, so "
                        "no content from them has ever been indexed:\n"
                        + "\n".join(f"- {s}" for s in never_synced[:10])
                    ),
                    resolution=(
                        "1. Run StartIngestionJob for each data source and investigate failures.\n"
                        "2. Confirm the source location exists and the KB role can read it."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )

        if undetermined:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}Knowledge Base Data Source Sync Check",
                    finding_details=(
                        "Could not read ingestion history for: "
                        + ", ".join(undetermined[:10])
                    ),
                    resolution=(
                        "Ensure the assessment role has bedrock:ListIngestionJobs permission."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )

        if stale_kbs:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name="Knowledge Base Data Sources Past Review Threshold",
                    finding_details=(
                        f"{len(stale_kbs)} data source(s) not synced in >{STALE_AFTER_DAYS} days "
                        f"(a configurable review threshold, NOT an AWS-mandated limit):\n"
                        + "\n".join(f"- {s}" for s in stale_kbs[:10])
                        + "\nConfirm this age is acceptable for each data source's currency "
                        "requirement — slow-changing reference data may legitimately sync infrequently."
                    ),
                    resolution=(
                        "1. Define the maximum acceptable data age per use case (e.g., intraday for "
                        "market data, daily for product terms, weekly/monthly for regulatory guidance) "
                        "and adjust the review threshold to match.\n"
                        "2. Configure automated sync (EventBridge Scheduler → StartIngestionJob) at "
                        "that cadence — see FS-61.\n"
                        "3. Set CloudWatch alarms on sync job failures."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )

        # Only claim a clean bill of health when every data source was actually
        # assessed and every one of them was fresh. A never-synced or unreadable
        # source must not be papered over by a Passed row saying "all ... within
        # N days" — that is the false-pass this check previously emitted.
        if fresh and not (stale_kbs or never_synced or undetermined):
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name="Knowledge Base Data Sources Recently Synced",
                    finding_details=(
                        f"All {len(fresh)} reviewed KB data source(s) completed an ingestion "
                        f"job within {STALE_AFTER_DAYS} days (the default review threshold)."
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )
        elif not (fresh or stale_kbs or never_synced or undetermined):
            # Knowledge Bases exist but none has a data source, so there is no
            # ingestion to age. Reporting "recently synced" here would be vacuous.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-31",
                    finding_name="No Knowledge Base Data Sources Found",
                    finding_details=(
                        f"{len(kbs)} Knowledge Base(s) exist but none has a data source "
                        "attached, so there is no ingestion history to assess."
                    ),
                    resolution=(
                        "Attach a data source to each Knowledge Base that is expected to "
                        "serve content, then run an ingestion job."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-31"],
                )
            )
    except Exception as e:
        return _error_findings("Knowledge Base Data Source Sync Check", e)
    return findings


def check_source_attribution_in_guardrails() -> Dict[str, Any]:
    """
    FS-32 — Advisory check: verify application implements source attribution
    (citations) in GenAI responses to enable fact-checking.
    Evidence collected: none. Whether citations reach the end user depends on the
    application passing the right arguments to RetrieveAndGenerate at query time
    and then rendering the returned ``citations`` — neither the request nor the
    rendering is visible to any AWS configuration API, so this check makes zero
    API calls and always returns a single advisory N/A row.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Source Attribution Check")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-32",
            finding_name="ADVISORY: Source Attribution — Manual Review Required",
            finding_details=(
                "Source attribution in GenAI responses cannot be verified via AWS APIs. "
                "Manual review required to confirm responses include citations."
            ),
            resolution=(
                "1. Use Bedrock RetrieveAndGenerate with citations enabled.\n"
                "2. Include source document references in response post-processing.\n"
                "3. Test citation accuracy in QA before production deployment.\n"
                "4. Consider Bedrock Guardrails grounding checks to validate response accuracy."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-test-config.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-32"],
        )
    )
    return findings


def check_knowledge_base_integrity_monitoring(inventory) -> Dict[str, Any]:
    """
    FS-33 — Check for S3 object integrity monitoring (checksums, versioning)
    on Knowledge Base data source buckets.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, ISO 27001 A.12.3, FFIEC CAT]
    """
    findings = _empty_findings("Knowledge Base Integrity Monitoring Check")
    try:
        kb_inv = require(inventory, "knowledge_bases")
        kbs = kb_inv.summaries
        s3 = boto3.client("s3", config=boto3_config)

        if not kbs:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-33",
                    finding_name="No Knowledge Bases Found",
                    finding_details="No Bedrock Knowledge Bases found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-33"],
                )
            )
            return findings

        buckets_without_versioning = []
        missing_buckets = []
        for kb in kbs:
            kb_id = kb["knowledgeBaseId"]
            sources = kb_inv.data_sources_by_kb.get(kb_id, [])
            if isinstance(sources, _Unavailable):
                raise sources.error
            for source in sources:
                ds_id = source["dataSourceId"]
                source_detail = kb_inv.data_source_detail.get((kb_id, ds_id))
                if isinstance(source_detail, _Unavailable):
                    raise source_detail.error
                if source_detail is None:
                    continue
                s3_config = (
                    source_detail.get("dataSource", {})
                    .get("dataSourceConfiguration", {})
                    .get("s3Configuration", {})
                )
                bucket = _bucket_name_from_arn(s3_config.get("bucketArn", ""))
                if bucket:
                    try:
                        versioning = s3.get_bucket_versioning(Bucket=bucket)
                        if versioning.get("Status") != "Enabled":
                            buckets_without_versioning.append(bucket)
                    except ClientError as e:
                        # An access error means we could not read versioning; do
                        # not mislabel the bucket as non-versioned. Re-raise so it
                        # surfaces as could-not-assess instead of a false finding.
                        if _is_access_error(e):
                            raise
                        # The data source points to a bucket that no longer exists
                        # (deleted out from under the KB). This is a distinct,
                        # actionable integrity problem — report it separately, not
                        # as "missing versioning."
                        if _is_missing_bucket_error(e):
                            logger.warning(
                                f"KB '{kb['name']}' data source '{source['name']}' "
                                f"references a deleted bucket: {bucket}"
                            )
                            missing_buckets.append(
                                f"{bucket} (KB '{kb['name']}', source '{source['name']}')"
                            )
                            continue
                        logger.warning(
                            f"Could not check versioning for bucket {bucket}: {e}"
                        )
                        buckets_without_versioning.append(f"{bucket} (error)")

        # A dangling data-source reference to a deleted bucket is a real integrity
        # finding in its own right — emit it as a separate row so it is not
        # conflated with "versioning not enabled."
        if missing_buckets:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-33",
                    finding_name="KB Data Source References a Deleted S3 Bucket",
                    finding_details=(
                        "One or more Knowledge Base data sources point to S3 buckets that no "
                        "longer exist (NoSuchBucket). Retrieval will silently return no results "
                        "for these sources, and the integrity of the KB's grounding data cannot "
                        "be verified:\n"
                        + "\n".join(f"- {b}" for b in missing_buckets[:10])
                    ),
                    resolution=(
                        "1. Investigate why the data-source bucket was deleted (accidental "
                        "deletion, environment teardown, or a stale KB configuration).\n"
                        "2. Recreate/restore the bucket with versioning enabled, or remove the "
                        "orphaned data source from the Knowledge Base.\n"
                        "3. Re-run a KB ingestion job after restoring the data source.\n"
                        "4. Enable S3 versioning and MFA Delete on KB data-source buckets to "
                        "reduce the risk of unrecoverable deletion."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-33"],
                )
            )

        if buckets_without_versioning:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-33",
                    finding_name="KB Data Source Buckets Without Versioning",
                    finding_details=(
                        f"KB data source S3 buckets without versioning: "
                        f"{', '.join(buckets_without_versioning[:10])}."
                    ),
                    resolution=(
                        "Enable S3 versioning on all KB data source buckets. "
                        "Enable S3 Object Integrity (checksum) for tamper detection."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-33"],
                )
            )
        elif not missing_buckets:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-33",
                    finding_name="KB Data Source Buckets Have Versioning",
                    finding_details="All reviewed KB data source buckets have versioning enabled.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/checking-object-integrity.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-33"],
                )
            )
    except Exception as e:
        return _error_findings("Knowledge Base Integrity Monitoring Check", e)
    return findings


def check_fm_version_currency() -> Dict[str, Any]:
    """
    FS-34 — Advisory check: verify foundation model versions in use are current
    and not deprecated (outdated models may have stale training data).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    findings = _empty_findings("Foundation Model Version Currency Check")
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)
        # Do not filter by output modality: legacy/deprecated models exist across
        # TEXT, EMBEDDING, and IMAGE modalities. Embedding models are widely used
        # in FinServ RAG pipelines and a legacy embedding model produces stale
        # embeddings — missing it would be a false-pass. Fetch all modalities and
        # let the LEGACY lifecycle filter identify any deprecated model in use.
        # ListFoundationModels has no continuation token in the Bedrock API
        # model, so there is no paginated form of this operation.
        models = bedrock.list_foundation_models().get("modelSummaries", [])

        deprecated = [
            m["modelId"]
            for m in models
            if m.get("modelLifecycle", {}).get("status") == "LEGACY"
        ]

        if deprecated:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-34",
                    finding_name="Legacy Foundation Models Available in Region",
                    finding_details=(
                        f"Legacy/deprecated foundation models are available in this account/region: "
                        f"{', '.join(deprecated[:10])}. This API reports model *availability*, not "
                        "actual usage — it cannot determine which models your applications invoke. "
                        "Legacy models have older training-data cutoffs and may produce outdated "
                        "information if used. Review whether any are in active use."
                    ),
                    resolution=(
                        "1. Identify which (if any) of these legacy models your applications invoke "
                        "(e.g., via CloudTrail InvokeModel events or application config).\n"
                        "2. Migrate active usage to current model versions.\n"
                        "3. Document training-data cutoff dates for all models in use.\n"
                        "4. Add data-currency disclaimers to outputs from models with old cutoffs."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/model-lifecycle.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-34"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-34",
                    finding_name="Foundation Models Are Current",
                    finding_details="No legacy/deprecated foundation models detected.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/model-lifecycle.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-34"],
                )
            )
    except Exception as e:
        return _error_findings("Foundation Model Version Currency Check", e)
    return findings


# ===========================================================================
# CATEGORY 8: ABUSIVE OR HARMFUL OUTPUT (FS-35 to FS-38)
# CATEGORY 9: BIASED OUTPUT (FS-39 to FS-42)
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2, NYDFS 500]
# ===========================================================================


def check_fmeval_harmful_content() -> Dict[str, Any]:
    """
    FS-35 — Check for FMEval or Bedrock Evaluation jobs testing for harmful
    content (toxicity, hate speech, violence).
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("FMEval Harmful Content Check")
    try:
        findings["csv_data"].append(
            create_finding(
                check_id="FS-35",
                finding_name="ADVISORY: Harmful-Content Test Coverage — Manual Review Required",
                finding_details=(
                    "Bedrock model-evaluation dataset content cannot be inspected via API. "
                    "Manually verify your model-evaluation/FMEval jobs include harmful-content "
                    "datasets (toxicity, hate speech, violence/self-harm). Whether any evaluation "
                    "jobs exist at all is assessed by FS-15."
                ),
                resolution=(
                    "Run Bedrock Model Evaluation or FMEval with harmful content datasets:\n"
                    "- Toxicity detection\n"
                    "- Hate speech classification\n"
                    "- Violence/self-harm content"
                ),
                reference="https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-automatic.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP["FS-35"],
            )
        )
    except Exception as e:
        return _error_findings("FMEval Harmful Content Check", e)
    return findings


def check_guardrail_content_filters(inventory) -> Dict[str, Any]:
    """
    FS-36 — Report whether Bedrock Guardrails have content filters configured
    for hate speech, violence, and sexual content, and which tier each uses.

    Evidence collected: presence of ``contentPolicy.filters`` and the value of
    ``contentPolicy.tier.tierName`` from GetGuardrail.

    Deliberately NOT asserted: that filter strength is adequate, or that
    coverage is complete for a given application. An absent tier is reported
    as unknown rather than assumed CLASSIC — defaulting it would report an
    assumption as an observation, the same defect corrected for FS-28's topic
    policy tier.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    check_name = "Guardrail Content Filters Check"
    findings = _empty_findings(check_name)
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-36",
                    finding_name="No Guardrails — Content Filters Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with content filters.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-content-filters.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-36"],
                )
            )
            return findings

        guardrails_with_filters = []
        guardrails_classic_tier = []
        filters_unknown_tier = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            content_policy = detail.get("contentPolicy", {})
            if content_policy.get("filters"):
                guardrails_with_filters.append(g["name"])
                # Check tier: STANDARD offers better accuracy, multilingual support,
                # and improved prompt-attack detection (GA June 2025). Regulated
                # workloads benefit from STANDARD for its contextual understanding
                # and typo-tolerant detection. STANDARD requires cross-region
                # inference. The tier is nested at contentPolicy.tier.tierName in
                # GetGuardrail response. An ABSENT tier is reported as unknown
                # rather than assumed CLASSIC.
                tier = content_policy.get("tier", {}).get("tierName")
                if tier == "CLASSIC":
                    guardrails_classic_tier.append(g["name"])
                elif not tier:
                    filters_unknown_tier.append(g["name"])

        tier_note = ""
        if filters_unknown_tier:
            tier_note = (
                " Tier not reported by GetGuardrail for: "
                f"{', '.join(filters_unknown_tier)} (tier unknown, not assumed CLASSIC)."
            )

        if not guardrails_with_filters:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-36",
                    finding_name="No Guardrails With Content Filters",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have content filters. "
                        "Harmful content (hate, violence, sexual) may pass through unfiltered."
                    ),
                    resolution=(
                        "1. Add content filters to guardrails for: HATE, INSULTS, SEXUAL, VIOLENCE.\n"
                        "2. Set filter strength to HIGH for financial services use cases.\n"
                        "3. Consider the STANDARD tier (GA June 2025) for improved accuracy, "
                        "typographical error detection, and 60+ language support. STANDARD tier "
                        "requires cross-region inference to be enabled on the guardrail."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-content-filters.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-36"],
                )
            )
        elif guardrails_classic_tier:
            # Note: guardrails_classic_tier and filters_unknown_tier are not
            # mutually exclusive — a guardrail set can have some CLASSIC-tier
            # members and some with no tier reported. tier_note (computed above,
            # independent of which branch fires) discloses any unknown-tier
            # guardrails here too, so a mixed-tier result never reports Passed
            # on CLASSIC alone while silently omitting the unknown-tier ones.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-36",
                    finding_name="Guardrail Content Filters on CLASSIC Tier",
                    finding_details=(
                        f"Guardrails with content filters: {', '.join(guardrails_with_filters)}. "
                        f"The following use the CLASSIC tier: {', '.join(guardrails_classic_tier)}. "
                        "CLASSIC tier supports English, French, and Spanish only. The STANDARD tier "
                        "(GA June 2025) provides improved contextual understanding, typographical error "
                        "detection, 60+ language support, and better prompt-attack classification "
                        f"(distinguishes jailbreaks from prompt injection).{tier_note}"
                    ),
                    resolution=(
                        "Consider upgrading to STANDARD tier content filters for workloads "
                        "that handle multiple languages or require higher detection accuracy. "
                        "STANDARD tier requires cross-region inference "
                        "(crossRegionDetails.guardrailProfileArn on the guardrail). "
                        "To upgrade: update the guardrail's contentPolicy.filtersConfig.contentFiltersTierConfig "
                        "with tierName=STANDARD and configure a guardrail cross-region profile."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-tiers.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-36"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-36",
                    finding_name="Guardrails With Content Filters Found",
                    finding_details=(
                        f"Guardrails with content filters: {', '.join(guardrails_with_filters)}."
                        f"{tier_note}"
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-content-filters.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-36"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_user_feedback_mechanism() -> Dict[str, Any]:
    """
    FS-37 — Advisory check: verify application has a user feedback/reporting
    mechanism for harmful GenAI outputs.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("User Feedback Mechanism Check")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-37",
            finding_name="ADVISORY: User Feedback Mechanism — Manual Review Required",
            finding_details=(
                "User feedback mechanisms for harmful outputs cannot be verified via AWS APIs. "
                "Manual review required."
            ),
            resolution=(
                "1. Implement thumbs-up/down or flag-for-review UI in GenAI applications.\n"
                "2. Route flagged outputs to human reviewers via SQS/SNS.\n"
                "3. Log feedback to DynamoDB/S3 for model improvement.\n"
                "4. Define SLAs for reviewing flagged content."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-37"],
        )
    )
    return findings


def check_guardrail_word_filters(inventory) -> Dict[str, Any]:
    """
    FS-38 — Verify Bedrock Guardrails have word/phrase filters (allowlists/denylists)
    configured for financial services context.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    findings = _empty_findings("Guardrail Word Filters Check")
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-38",
                    finding_name="No Guardrails — Word Filters Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with word filters.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-38"],
                )
            )
            return findings

        guardrails_with_words = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            if detail.get("wordPolicy", {}).get("words") or detail.get(
                "wordPolicy", {}
            ).get("managedWordLists"):
                guardrails_with_words.append(g["name"])

        if not guardrails_with_words:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-38",
                    finding_name="No Guardrails With Word Filters",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have word/phrase filters. "
                        "Profanity and prohibited financial terms may appear in outputs."
                    ),
                    resolution=(
                        "Add word filters to guardrails:\n"
                        "- Enable AWS managed profanity list\n"
                        "- Add custom denylist for prohibited financial terms\n"
                        "- Add allowlist for required regulatory language"
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-38"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-38",
                    finding_name="Guardrail Word Filters Configured",
                    finding_details=f"Guardrails with word filters: {', '.join(guardrails_with_words)}.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-38"],
                )
            )
    except Exception as e:
        return _error_findings("Guardrail Word Filters Check", e)
    return findings


def check_sagemaker_clarify_bias() -> Dict[str, Any]:
    """
    FS-39 — Report presence and schedule status of SageMaker Clarify model-bias
    monitoring schedules.

    Evidence collected: ListMonitoringSchedules entries where MonitoringType is
    ModelBias, plus each entry's MonitoringScheduleStatus and EndpointName.

    Deliberately NOT asserted:
      - association with production financial-decision models,
      - which protected attributes are evaluated,
      - which bias metrics and thresholds are configured,
      - that violations trigger alerting or remediation,
      - ECOA or Fair Housing conformance.
    Note that MonitoringScheduleStatus has no "Active" value; the running state
    is "Scheduled". Findings therefore report the observed status verbatim.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ECOA, Fair Housing Act]
    """
    check_name = "SageMaker Clarify Bias Check"
    manual_review = (
        "Schedule presence does not establish protected-attribute coverage, "
        "threshold adequacy, or fair-lending conformance; review manually."
    )
    findings = _empty_findings(check_name)
    try:
        sm = boto3.client("sagemaker", config=boto3_config)
        schedules = _paginate(
            sm, "list_monitoring_schedules", "MonitoringScheduleSummaries"
        )

        bias_schedules = [
            s for s in schedules if s.get("MonitoringType") == "ModelBias"
        ]
        running = [
            s
            for s in bias_schedules
            if s.get("MonitoringScheduleStatus") == "Scheduled"
        ]
        not_running = [
            s
            for s in bias_schedules
            if s.get("MonitoringScheduleStatus") != "Scheduled"
        ]

        if not bias_schedules:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-39",
                    finding_name="No SageMaker Clarify Bias Monitoring",
                    finding_details=(
                        "No SageMaker Clarify model bias monitoring schedules found. "
                        "Models making financial decisions (credit, insurance) may exhibit "
                        "discriminatory bias without detection."
                    ),
                    resolution=(
                        "1. Configure SageMaker Clarify bias detection for all models making "
                        "credit, insurance, or employment decisions.\n"
                        "2. Define protected attributes (age, gender, race proxies).\n"
                        "3. Set bias metric thresholds and alert on violations.\n"
                        "4. Document bias testing results for regulatory examination."
                    ),
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-39"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-39",
                    finding_name="SageMaker Clarify Bias Monitoring Schedules Found",
                    finding_details=(
                        f"Found {len(bias_schedules)} model bias monitoring schedule(s); "
                        f"{len(running)} with status Scheduled. "
                        + _describe_schedules(bias_schedules)
                        + " "
                        + manual_review
                    ),
                    resolution="No action required for schedule presence.",
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-39"],
                )
            )
            if not_running:
                findings["status"] = "WARN"
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-39",
                        finding_name="SageMaker Clarify Bias Monitoring Schedules Not Running",
                        finding_details=(
                            "Model bias monitoring schedules exist but are not in the "
                            "Scheduled state, so bias monitoring is not currently running: "
                            + _describe_schedules(not_running)
                        ),
                        resolution=(
                            "Investigate and restart the affected monitoring schedules, then "
                            "confirm they reach the Scheduled state."
                        ),
                        reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html",
                        severity="High",
                        status="Failed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-39"],
                    )
                )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_bedrock_evaluation_bias_datasets() -> Dict[str, Any]:
    """
    FS-40 — Advisory prompt for a manual bias-dataset coverage review.

    Evidence collected: none. Bedrock does not expose model-evaluation dataset
    content through any API, so this check makes zero API calls and always
    returns a single advisory N/A row carrying the ADVISORY: prefix.

    This is a manual bias-dataset coverage review, never automated validation.
    Do not describe it as verifying, validating, or testing anything. Whether
    any evaluation jobs exist at all is assessed separately by FS-15.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ECOA]
    """
    findings = _empty_findings("Bedrock Bias Evaluation Datasets Check")
    try:
        findings["csv_data"].append(
            create_finding(
                check_id="FS-40",
                finding_name="ADVISORY: Bias Dataset Coverage — Manual Review Required",
                finding_details=(
                    "Bedrock model-evaluation dataset content cannot be inspected via API. "
                    "Manually verify your model-evaluation jobs include bias/fairness datasets "
                    "(demographic parity, equal-opportunity, counterfactual fairness) for any "
                    "GenAI models used in financial decisions (ECOA/Fair Housing). Whether any "
                    "evaluation jobs exist at all is assessed by FS-15."
                ),
                resolution=(
                    "Run Bedrock Model Evaluation with bias test datasets:\n"
                    "- Demographic parity test cases\n"
                    "- Equal opportunity scenarios\n"
                    "- Counterfactual fairness tests"
                ),
                reference="https://docs.aws.amazon.com/bedrock/latest/userguide/evaluation-automatic.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP["FS-40"],
            )
        )
    except Exception as e:
        return _error_findings("Bedrock Bias Evaluation Datasets Check", e)
    return findings


def check_sagemaker_clarify_explainability() -> Dict[str, Any]:
    """
    FS-41 — Report presence and schedule status of SageMaker Clarify
    model-explainability monitoring schedules.

    Evidence collected: ListMonitoringSchedules entries where MonitoringType is
    ModelExplainability, plus each entry's MonitoringScheduleStatus and
    EndpointName.

    Deliberately NOT asserted:
      - that explanations support adverse-action notices,
      - that SHAP features map to human-readable reason codes,
      - that explanations are stored or delivered to applicants,
      - ECOA conformance.
    Adverse-action reason generation is an application concern and stays a
    manual review. As with FS-39, MonitoringScheduleStatus has no "Active"
    value; the running state is "Scheduled".

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ECOA Adverse Action]
    """
    check_name = "SageMaker Clarify Explainability Check"
    manual_review = (
        "Schedule presence does not establish that explanations are generated, "
        "mapped to reason codes, stored, or delivered; review manually."
    )
    findings = _empty_findings(check_name)
    try:
        sm = boto3.client("sagemaker", config=boto3_config)
        schedules = _paginate(
            sm, "list_monitoring_schedules", "MonitoringScheduleSummaries"
        )

        explainability_schedules = [
            s for s in schedules if s.get("MonitoringType") == "ModelExplainability"
        ]
        running = [
            s
            for s in explainability_schedules
            if s.get("MonitoringScheduleStatus") == "Scheduled"
        ]
        not_running = [
            s
            for s in explainability_schedules
            if s.get("MonitoringScheduleStatus") != "Scheduled"
        ]

        if not explainability_schedules:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-41",
                    finding_name="No SageMaker Clarify Explainability Monitoring",
                    finding_details=(
                        "No SageMaker Clarify explainability monitoring found. "
                        "Models making adverse financial decisions may not provide "
                        "required explanations (ECOA adverse action notices)."
                    ),
                    resolution=(
                        "1. Configure SageMaker Clarify explainability for credit/lending models.\n"
                        "2. Generate SHAP values for feature importance.\n"
                        "3. Map top features to human-readable adverse action reason codes.\n"
                        "4. Store explanations for regulatory examination."
                    ),
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-explainability.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-41"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-41",
                    finding_name="SageMaker Clarify Explainability Monitoring Schedules Found",
                    finding_details=(
                        f"Found {len(explainability_schedules)} explainability monitoring "
                        f"schedule(s); {len(running)} with status Scheduled. "
                        + _describe_schedules(explainability_schedules)
                        + " "
                        + manual_review
                    ),
                    resolution="No action required for schedule presence.",
                    reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-explainability.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-41"],
                )
            )
            if not_running:
                findings["status"] = "WARN"
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-41",
                        finding_name="SageMaker Clarify Explainability Schedules Not Running",
                        finding_details=(
                            "Explainability monitoring schedules exist but are not in the "
                            "Scheduled state, so explanations are not currently being produced: "
                            + _describe_schedules(not_running)
                        ),
                        resolution=(
                            "Investigate and restart the affected monitoring schedules, then "
                            "confirm they reach the Scheduled state."
                        ),
                        reference="https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-explainability.html",
                        severity="High",
                        status="Failed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-41"],
                    )
                )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_ai_service_cards_documentation() -> Dict[str, Any]:
    """
    FS-42 — Report whether SageMaker Model Cards exist and whether each has
    been moved out of Draft.

    Evidence collected: ListModelCards, reading ModelCardName and
    ModelCardStatus from each summary.

    Response-key note: the ListModelCards result key is ``ModelCardSummaries``.
    An earlier revision paginated on ``ModelCardSummaryList``, which does not
    exist in the API response, so the check silently saw zero cards and always
    reported "No SageMaker Model Cards Found" — verified against a live account
    holding two cards. Any change here must keep the key aligned with the API.

    Deliberately NOT asserted:
      - that a card's documented content is accurate, complete or current,
      - that an Approved card was reviewed by a competent approver,
      - that models without a card are undocumented elsewhere.
    Card *content* requires DescribeModelCard per card and is not inspected.

    Absence of Model Cards is reported as Informational rather than Failed:
    SageMaker Model Cards are a SageMaker-specific artifact, and a
    Bedrock-only estate can be fully governed without any.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.3]
    """
    check_name = "AI Service Cards Documentation Check"
    reference = "https://docs.aws.amazon.com/sagemaker/latest/dg/model-cards.html"
    manual_review = (
        "Card presence does not prove the documented content is accurate or "
        "current; review card content manually."
    )
    findings = _empty_findings(check_name)
    try:
        sm = boto3.client("sagemaker", config=boto3_config)
        model_cards = _paginate(sm, "list_model_cards", "ModelCardSummaries")

        if not model_cards:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-42",
                    finding_name="No SageMaker Model Cards Found",
                    finding_details=(
                        "No SageMaker Model Cards found. If GenAI workloads run on Bedrock "
                        "rather than SageMaker, model documentation may legitimately live "
                        "elsewhere; Model Cards are a SageMaker-specific artifact."
                    ),
                    resolution=(
                        "1. For SageMaker models, create a Model Card documenting intended use, "
                        "out-of-scope uses, training data and bias evaluations.\n"
                        "2. For Bedrock-only estates, record the equivalent documentation in your "
                        "model-governance system and reference the AWS AI Service Cards."
                    ),
                    reference=reference,
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-42"],
                )
            )
            return findings

        draft_cards = [
            c["ModelCardName"]
            for c in model_cards
            if (c.get("ModelCardStatus") or "") != "Approved"
        ]
        approved_cards = [
            c["ModelCardName"]
            for c in model_cards
            if (c.get("ModelCardStatus") or "") == "Approved"
        ]

        if draft_cards:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-42",
                    finding_name="SageMaker Model Cards Not Approved",
                    finding_details=(
                        f"{len(draft_cards)} of {len(model_cards)} model card(s) are not in "
                        f"Approved status: {', '.join(sorted(draft_cards)[:10])}. "
                        "An unapproved card has not completed its documented review. "
                        + manual_review
                    ),
                    resolution=(
                        "1. Complete the model-card review and move each card to Approved.\n"
                        "2. Document intended use, out-of-scope uses, training data and bias "
                        "evaluations before approval."
                    ),
                    reference=reference,
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-42"],
                )
            )

        if approved_cards:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-42",
                    finding_name="SageMaker Model Cards Approved",
                    finding_details=(
                        f"{len(approved_cards)} of {len(model_cards)} model card(s) are in "
                        f"Approved status: {', '.join(sorted(approved_cards)[:10])}. "
                        + manual_review
                    ),
                    resolution="Verify cards stay current at each model version release.",
                    reference=reference,
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-42"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


# ===========================================================================
# CATEGORY 10: SENSITIVE INFORMATION DISCLOSURE (FS-43 to FS-46)
# COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 3.4, GDPR Art.25]
# ===========================================================================


def check_cloudwatch_log_pii_masking() -> Dict[str, Any]:
    """
    FS-43 — Report whether the CloudWatch log group that receives Bedrock model
    invocation logs has a data protection policy masking PII.

    Evidence collected: GetModelInvocationLoggingConfiguration to learn whether
    invocation logging is enabled and where it delivers, then
    DescribeAccountPolicies(DATA_PROTECTION_POLICY) for account-scoped policies
    and GetDataProtectionPolicy for the specific log group.

    Applicability matters, and an earlier revision ignored it. That revision
    tested only whether any account-scoped policy existed, which produced two
    wrong answers, both verified live:
      - Bedrock delivering invocation logs to S3 only (no cloudWatchConfig)
        still reported a High failure about plaintext PII in CloudWatch, where
        no Bedrock logs exist at all.
      - A log group carrying its own data protection policy still reported
        "No CloudWatch Logs Data Protection Policies", because a log-group
        policy is invisible to DescribeAccountPolicies.

    A subsequent revision fixed both of those but introduced a third: a
    ClientError from DescribeAccountPolicies or GetDataProtectionPolicy was
    caught and treated as "no policy found" for that call, so an access-denied
    permissions gap on either API silently became a Failed finding indistin-
    guishable from a genuinely unprotected log group. Both calls are now
    tracked tri-state (found / confirmed absent / unknown), and a Failed
    verdict requires that both were confirmed absent — an unknown side, with
    no policy found on the other, is reported as COULD NOT ASSESS instead.

    Deliberately NOT asserted:
      - that the configured data identifiers cover every PII type in the logs,
      - that masking is working on log content already delivered,
      - anything about PII in S3-delivered invocation logs, which CloudWatch
        Logs data protection does not touch.

    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, GDPR Art.25, PCI-DSS 3.4]
    """
    check_name = "CloudWatch Log PII Masking Check"
    reference = "https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/mask-sensitive-log-data.html"
    findings = _empty_findings(check_name)
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)
        logs = boto3.client("logs", config=boto3_config)

        logging_config: Dict[str, Any] = {}
        try:
            logging_config = (
                bedrock.get_model_invocation_logging_configuration().get(
                    "loggingConfig"
                )
                or {}
            )
        except ClientError as e:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        "Unable to read the Bedrock model invocation logging configuration "
                        f"({e.response['Error']['Code']}), so the applicable log destination "
                        "could not be determined."
                    ),
                    resolution=(
                        "Ensure the assessment role has "
                        "bedrock:GetModelInvocationLoggingConfiguration permission."
                    ),
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
            return findings

        cw_config = logging_config.get("cloudWatchConfig") or {}
        log_group = cw_config.get("logGroupName")
        s3_config = logging_config.get("s3Config") or {}

        if not logging_config:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name="Bedrock Invocation Logging Not Enabled",
                    finding_details=(
                        "Bedrock model invocation logging is not enabled, so no invocation logs "
                        "are being delivered and there is no log content to mask. Prompt and "
                        "completion content is therefore also unavailable for audit."
                    ),
                    resolution=(
                        "1. Enable Bedrock model invocation logging.\n"
                        "2. If delivering to CloudWatch Logs, attach a data protection policy "
                        "masking PII to the destination log group."
                    ),
                    reference=reference,
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
            return findings

        if not log_group:
            dest = "Amazon S3" if s3_config else "an unrecognised destination"
            bucket = s3_config.get("bucketName", "")
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name="Bedrock Invocation Logs Not Delivered to CloudWatch Logs",
                    finding_details=(
                        f"Bedrock model invocation logging delivers to {dest}"
                        + (f" (bucket {bucket})" if bucket else "")
                        + ", not CloudWatch Logs. CloudWatch Logs data protection policies do not "
                        "apply to this delivery path, so this control is not applicable. PII "
                        "protection for the delivered objects must be assessed on the destination "
                        "instead."
                    ),
                    resolution=(
                        "Protect the delivery destination directly: enable default encryption and "
                        "restrict access on the S3 bucket, and use Amazon Macie to identify "
                        "sensitive data in the delivered logs (see FS-44). If you also enable "
                        "CloudWatch delivery, attach a data protection policy to that log group."
                    ),
                    reference=reference,
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
            return findings

        # CloudWatch delivery is in use: a policy may be attached at account
        # scope or directly to the log group. Either satisfies the control.
        #
        # A ClientError on either call means that side is UNKNOWN, not that it
        # found no policy — collapsing "denied" into "empty" would turn a
        # permissions gap into a false Failed finding, indistinguishable from a
        # genuinely unprotected log group. Both sides are tracked as tri-state
        # (found / confirmed absent / unknown) so a denial on one side cannot
        # manufacture a Failed verdict, while a policy found on the other side
        # still yields a legitimate Passed regardless of the denial.
        account_policies: List[Dict[str, Any]] = []
        account_policies_unknown: Optional[str] = None
        try:
            account_policies = logs.describe_account_policies(
                policyType="DATA_PROTECTION_POLICY"
            ).get("accountPolicies", [])
        except ClientError as e:
            account_policies_unknown = e.response["Error"]["Code"]

        # GetDataProtectionPolicy does NOT raise for a log group without a
        # policy: it returns a response with no policyDocument member. Testing
        # the response for truthiness would always succeed because of
        # ResponseMetadata, so the presence of policyDocument is the signal.
        # A ClientError here means the group-level policy is unknown, not that
        # it is absent.
        group_policy = None
        group_policy_unknown: Optional[str] = None
        try:
            response = logs.get_data_protection_policy(logGroupIdentifier=log_group)
            if response.get("policyDocument"):
                group_policy = response
        except ClientError as e:
            group_policy_unknown = e.response["Error"]["Code"]

        if not (group_policy or account_policies) and (
            account_policies_unknown or group_policy_unknown
        ):
            # Neither side found a policy, and at least one side is unknown
            # rather than confirmed absent, so "no policy exists" is not
            # established. Reporting Failed here would be exactly the false
            # failure this check exists to avoid.
            unknown = []
            if account_policies_unknown:
                unknown.append(f"DescribeAccountPolicies ({account_policies_unknown})")
            if group_policy_unknown:
                unknown.append(f"GetDataProtectionPolicy ({group_policy_unknown})")
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        "Unable to determine whether CloudWatch log group "
                        f"{log_group} has a data protection policy: {' and '.join(unknown)} "
                        "failed. This is a permissions gap, not evidence that no policy exists."
                    ),
                    resolution=(
                        "Ensure the assessment role has logs:DescribeAccountPolicies and "
                        "logs:GetDataProtectionPolicy permission."
                    ),
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
            return findings

        if group_policy or account_policies:
            scope = []
            if group_policy:
                scope.append(f"a policy attached directly to log group {log_group}")
            if account_policies:
                scope.append(f"{len(account_policies)} account-scoped policy(ies)")
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name="CloudWatch Logs Data Protection Policies Present",
                    finding_details=(
                        f"Bedrock invocation logs are delivered to CloudWatch log group "
                        f"{log_group}, covered by " + " and ".join(scope) + ". "
                        "Whether the configured data identifiers cover every PII type present in "
                        "the logs is not assessed."
                    ),
                    resolution=(
                        "Review the configured data identifiers against the PII types your prompts "
                        "and completions can contain."
                    ),
                    reference=reference,
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-43",
                    finding_name="No CloudWatch Logs Data Protection Policies",
                    finding_details=(
                        f"Bedrock invocation logs are delivered to CloudWatch log group "
                        f"{log_group}, but neither an account-scoped nor a log-group data "
                        "protection policy was found. PII (SSN, account numbers, credit card "
                        "numbers) in prompts and completions may be stored in plaintext."
                    ),
                    resolution=(
                        f"1. Attach a data protection policy to log group {log_group}, or create an "
                        "account-scoped policy covering it.\n"
                        "2. Include identifiers for SSN, credit card numbers, bank account numbers "
                        "and email.\n"
                        "3. Test masking with synthetic PII before relying on it."
                    ),
                    reference=reference,
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-43"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_macie_on_training_data_buckets() -> Dict[str, Any]:
    """
    FS-44 — Report whether Amazon Macie is enabled and whether automated
    sensitive data discovery is actually running.

    Evidence collected: GetMacieSession for the account's Macie status, then
    GetAutomatedDiscoveryConfiguration for the discovery status.

    Both are required. Macie can be ENABLED while automated sensitive data
    discovery is DISABLED, in which case nothing is being scanned — verified
    live on an account showing session ENABLED and discovery DISABLED, where an
    earlier revision reported "Amazon Macie is enabled and scanning S3 buckets"
    as a High pass.

    Error handling note: when Macie has never been enabled, all Macie APIs
    raise AccessDeniedException, which is also what a missing IAM permission
    produces. The messages differ ("Macie is not enabled", "has not been
    onboarded"), so they are distinguished on that basis and a genuine
    permissions gap is reported as COULD NOT ASSESS rather than as a security
    failure.

    Deliberately NOT asserted:
      - that discovery covers the specific buckets holding training data or KB
        data sources,
      - that any sensitive-data finding has been triaged or remediated,
      - that a PII pre-processing step exists in training or ingestion
        pipelines.

    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, GDPR Art.25, PCI-DSS 3.4, FFIEC CAT]
    """
    check_name = "Amazon Macie PII Scanning Check"
    reference = "https://docs.aws.amazon.com/macie/latest/user/what-is-macie.html"
    not_enabled_markers = ("not enabled", "not been onboarded", "no macie account")
    findings = _empty_findings(check_name)
    try:
        macie = boto3.client("macie2", config=boto3_config)

        macie_status = None
        try:
            macie_status = macie.get_macie_session().get("status")
        except ClientError as e:
            message = str(e).lower()
            if any(marker in message for marker in not_enabled_markers):
                macie_status = "NOT_ENABLED"
            else:
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-44",
                        finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                        finding_details=(
                            "Unable to determine whether Amazon Macie is enabled "
                            f"({e.response['Error']['Code']}). This is a permissions or "
                            "availability problem, not evidence that Macie is disabled."
                        ),
                        resolution="Ensure the assessment role has macie2:GetMacieSession permission.",
                        reference=reference,
                        severity="Low",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-44"],
                    )
                )
                return findings

        if macie_status != "ENABLED":
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-44",
                    finding_name="Amazon Macie Not Enabled",
                    finding_details=(
                        f"Amazon Macie is not enabled in this region (status: {macie_status}). "
                        "S3 buckets containing training data and KB data sources are not being "
                        "scanned for PII or other sensitive data."
                    ),
                    resolution=(
                        "1. Enable Amazon Macie in every region where AI/ML data is stored.\n"
                        "2. Enable automated sensitive data discovery.\n"
                        "3. Route Macie findings to Security Hub and SNS.\n"
                        "4. Remediate PII findings before using data for model training."
                    ),
                    reference=reference,
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-44"],
                )
            )
            return findings

        discovery_status = None
        try:
            discovery_status = macie.get_automated_discovery_configuration().get(
                "status"
            )
        except ClientError as e:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-44",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}Macie Automated Discovery Status",
                    finding_details=(
                        "Amazon Macie is enabled, but the automated sensitive data discovery "
                        f"status could not be read ({e.response['Error']['Code']}), so whether "
                        "anything is actually being scanned is unknown."
                    ),
                    resolution=(
                        "Ensure the assessment role has "
                        "macie2:GetAutomatedDiscoveryConfiguration permission."
                    ),
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-44"],
                )
            )
            return findings

        if discovery_status == "ENABLED":
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-44",
                    finding_name="Amazon Macie Automated Discovery Enabled",
                    finding_details=(
                        "Amazon Macie is enabled and automated sensitive data discovery is "
                        "ENABLED, so S3 buckets are evaluated on an ongoing basis. Whether "
                        "discovery covers the specific buckets holding training data or KB data "
                        "sources is not assessed."
                    ),
                    resolution=(
                        "Review the Macie classification scope to confirm it includes your "
                        "training data and Knowledge Base source buckets."
                    ),
                    reference=reference,
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-44"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-44",
                    finding_name="Amazon Macie Enabled but Automated Discovery Disabled",
                    finding_details=(
                        "Amazon Macie is enabled, but automated sensitive data discovery is "
                        f"{discovery_status}. Enabling Macie alone does not scan any data, so S3 "
                        "buckets containing training data and KB data sources are not being "
                        "evaluated for PII."
                    ),
                    resolution=(
                        "1. Enable automated sensitive data discovery in Macie.\n"
                        "2. Confirm the classification scope includes training data and KB source "
                        "buckets.\n"
                        "3. Alternatively, create targeted classification jobs for those buckets."
                    ),
                    reference=reference,
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-44"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_guardrail_pii_filters(inventory) -> Dict[str, Any]:
    """
    FS-45 — Verify Bedrock Guardrails have sensitive information (PII) filters
    configured to block PII in prompts and responses.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, GDPR Art.25, PCI-DSS 3.4]
    """
    findings = _empty_findings("Guardrail PII Filters Check")
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-45",
                    finding_name="No Guardrails — PII Filters Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with PII/sensitive information filters.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-sensitive-filters.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-45"],
                )
            )
            return findings

        guardrails_with_pii = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            if detail.get("sensitiveInformationPolicy", {}).get("piiEntities"):
                guardrails_with_pii.append(g["name"])

        if not guardrails_with_pii:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-45",
                    finding_name="No Guardrails With PII Filters",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have PII entity filters. "
                        "SSN, credit card numbers, and account numbers may appear in GenAI outputs."
                    ),
                    resolution=(
                        "Add PII entity filters to guardrails for:\n"
                        "- US_SOCIAL_SECURITY_NUMBER\n"
                        "- CREDIT_DEBIT_CARD_NUMBER\n"
                        "- BANK_ACCOUNT_NUMBER\n"
                        "- EMAIL, PHONE, NAME (as appropriate)\n"
                        "Set action to ANONYMIZE or BLOCK."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-sensitive-filters.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-45"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-45",
                    finding_name="Guardrail PII Filters Configured",
                    finding_details=f"Guardrails with PII filters: {', '.join(guardrails_with_pii)}.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-sensitive-filters.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-45"],
                )
            )
    except Exception as e:
        return _error_findings("Guardrail PII Filters Check", e)
    return findings


def check_data_classification_tagging(inventory) -> Dict[str, Any]:
    """
    FS-46 — Check that S3 buckets containing AI/ML data are tagged with
    data classification labels (e.g., Confidential, PII, Public).
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, ISO 27001 A.8.2]
    """
    findings = _empty_findings("Data Classification Tagging Check")
    try:
        buckets = require(inventory, "buckets")
        s3 = boto3.client("s3", config=boto3_config)

        aiml_buckets = [
            b
            for b in buckets
            if any(
                kw in b["Name"].lower()
                for kw in ["train", "model", "bedrock", "sagemaker", "kb", "knowledge"]
            )
        ]

        if not aiml_buckets:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-46",
                    finding_name="No AI/ML Data Buckets Identified",
                    finding_details="No S3 buckets with AI/ML naming found.",
                    resolution="Tag AI/ML data buckets with data-classification labels.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-tagging.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-46"],
                )
            )
            return findings

        unclassified = []
        for bucket in aiml_buckets:
            try:
                tags = s3.get_bucket_tagging(Bucket=bucket["Name"]).get("TagSet", [])
                tag_keys = {t["Key"].lower() for t in tags}
                if (
                    "data-classification" not in tag_keys
                    and "classification" not in tag_keys
                ):
                    unclassified.append(bucket["Name"])
            except ClientError as e:
                # A genuine "no tags" response (NoSuchTagSet) means the bucket is
                # unclassified — a real finding. An access error means we could
                # not read the tags; re-raise so it surfaces as could-not-assess
                # rather than a false "unclassified" finding.
                if _is_access_error(e):
                    raise
                unclassified.append(bucket["Name"])

        if unclassified:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-46",
                    finding_name="AI/ML Buckets Without Data Classification Tags",
                    finding_details=(
                        f"{len(unclassified)} AI/ML bucket(s) without data-classification tags: "
                        f"{', '.join(unclassified[:10])}."
                    ),
                    resolution=(
                        "Tag all AI/ML data buckets with 'data-classification' key. "
                        "Values: Public, Internal, Confidential, Restricted. "
                        "Enforce via SCP or AWS Config rule."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-tagging.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-46"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-46",
                    finding_name="AI/ML Buckets Have Classification Tags",
                    finding_details=f"All {len(aiml_buckets)} AI/ML bucket(s) have classification tags.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/object-tagging.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-46"],
                )
            )
    except Exception as e:
        return _error_findings("Data Classification Tagging Check", e)
    return findings


# ===========================================================================
# CATEGORY 11: HALLUCINATION (FS-47 to FS-50)
# CATEGORY 12: PROMPT INJECTION (FS-51 to FS-54)
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2, NYDFS 500]
# ===========================================================================


def check_guardrail_grounding_threshold(inventory) -> Dict[str, Any]:
    """
    FS-47 — Verify Bedrock Guardrails contextual grounding thresholds are
    set appropriately high for financial services use cases.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Guardrail Grounding Threshold Check")
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-47",
                    finding_name="No Guardrails — Grounding Threshold Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with contextual grounding checks.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-47"],
                )
            )
            return findings

        low_threshold_guardrails = []
        guardrails_with_grounding = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            grounding = detail.get("contextualGroundingPolicy", {})
            has_grounding_filter = False
            for filter_item in grounding.get("filters", []):
                if filter_item.get("type") == "GROUNDING":
                    has_grounding_filter = True
                    if filter_item.get("threshold", 1.0) < 0.7:
                        low_threshold_guardrails.append(
                            f"{g['name']} (threshold={filter_item['threshold']})"
                        )
            if has_grounding_filter:
                guardrails_with_grounding.append(g["name"])

        if low_threshold_guardrails:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-47",
                    finding_name="Guardrails With Low Grounding Thresholds",
                    finding_details=(
                        f"Guardrails with grounding threshold <0.7: {', '.join(low_threshold_guardrails)}. "
                        "Low thresholds allow hallucinated responses to pass through."
                    ),
                    resolution=(
                        "Set grounding threshold to 0.7 or higher for financial services use cases "
                        "(valid range is 0 to 0.99; 1.0 is invalid and blocks all content). "
                        "Test threshold impact on response quality before increasing. Note: contextual "
                        "grounding supports summarization, paraphrasing, and Q&A — not conversational "
                        "chatbot use cases; for chatbots use denied topics (FS-28/FS-59) instead."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-47"],
                )
            )
        elif not guardrails_with_grounding:
            # Guardrails exist but NONE has a GROUNDING filter at all. This is a
            # genuine gap (not a pass): without a grounding filter, ungrounded /
            # hallucinated responses are not detected. Previously this fell through
            # to the "Passed" branch because low_threshold_guardrails was empty.
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-47",
                    finding_name="No Guardrails With a Grounding Filter",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have a GROUNDING contextual "
                        "grounding filter configured. Ungrounded or hallucinated responses are not "
                        "detected for summarization/paraphrasing/Q&A use cases."
                    ),
                    resolution=(
                        "Add a GROUNDING contextual grounding filter (threshold ≥0.7; valid range "
                        "0 to 0.99) to each guardrail used for summarization, paraphrasing, or Q&A. "
                        "Note: contextual grounding is not supported for conversational chatbot use "
                        "cases — use denied topics (FS-28/FS-59) for those."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-47"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-47",
                    finding_name="Guardrail Grounding Thresholds Appropriate",
                    finding_details=(
                        f"All {len(guardrails_with_grounding)} guardrail(s) with a GROUNDING filter "
                        "have thresholds ≥0.7."
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-47"],
                )
            )
    except Exception as e:
        return _error_findings("Guardrail Grounding Threshold Check", e)
    return findings


def check_rag_knowledge_base_configured(inventory) -> Dict[str, Any]:
    """
    FS-48 — Verify RAG (Retrieval Augmented Generation) is used via Bedrock
    Knowledge Bases to ground responses in authoritative data.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    findings = _empty_findings("RAG Knowledge Base Configuration Check")
    try:
        kbs = require(inventory, "knowledge_bases").summaries

        active_kbs = [k for k in kbs if k.get("status") == "ACTIVE"]

        if not active_kbs:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-48",
                    finding_name="No Active Knowledge Bases for RAG",
                    finding_details=(
                        "No active Bedrock Knowledge Bases found. "
                        "GenAI responses are not grounded in authoritative data sources, "
                        "increasing hallucination risk."
                    ),
                    resolution=(
                        "1. Create Bedrock Knowledge Bases with authoritative financial data.\n"
                        "2. Use RetrieveAndGenerate API to ground responses.\n"
                        "3. Configure data sources with current regulatory and product information."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-48"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-48",
                    finding_name="Active Knowledge Bases for RAG Present",
                    finding_details=f"Found {len(active_kbs)} active Knowledge Base(s) for RAG grounding.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-48"],
                )
            )
    except Exception as e:
        return _error_findings("RAG Knowledge Base Configuration Check", e)
    return findings


def check_hallucination_disclaimer_advisory() -> Dict[str, Any]:
    """
    FS-49 — Advisory check: verify application adds hallucination disclaimers
    to GenAI outputs in financial contexts.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Hallucination Disclaimer Advisory")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-49",
            finding_name="ADVISORY: Hallucination Disclaimer — Manual Review Required",
            finding_details=(
                "Application-level hallucination disclaimers cannot be verified via AWS APIs. "
                "Manual review required."
            ),
            resolution=(
                "1. Add disclaimers to GenAI outputs: 'AI-generated content may contain errors. "
                "Verify with authoritative sources before acting.'\n"
                "2. Implement post-processing to append disclaimers.\n"
                "3. Test disclaimer presence in QA before production."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-49"],
        )
    )
    return findings


def check_guardrail_relevance_grounding(inventory) -> Dict[str, Any]:
    """
    FS-50 — Check for Bedrock Guardrails contextual grounding RELEVANCE filters
    configured to detect and block responses that are not grounded in the context
    retrieved by the RAG pipeline (hallucination prevention).

    NOTE: This check verifies the *RELEVANCE* filter within contextual grounding
    (a different feature from GROUNDING-type filters). RELEVANCE filters block
    responses that are off-topic relative to the user query. GROUNDING filters
    block responses not supported by the source context. Both are important for
    FinServ hallucination mitigation. For formal policy-based verification of
    factual claims, see check_automated_reasoning_policies() (FS-27b).

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    findings = _empty_findings("Guardrail Relevance Grounding Check")
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        guardrails_with_relevance = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            grounding = detail.get("contextualGroundingPolicy", {})
            for f in grounding.get("filters", []):
                if f.get("type") == "RELEVANCE":
                    guardrails_with_relevance.append(g["name"])

        if not guardrails_with_relevance:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-50",
                    finding_name="No Guardrails With Relevance Grounding Filters",
                    finding_details=(
                        "No guardrails have RELEVANCE contextual grounding filters. "
                        "Without relevance filters, responses that are off-topic or unrelated "
                        "to the user query will not be blocked, increasing hallucination risk "
                        "in RAG-based applications."
                    ),
                    resolution=(
                        "Enable the RELEVANCE contextual grounding filter in Bedrock Guardrails "
                        "with a threshold of ≥0.7 to block responses that are not relevant to "
                        "the user query. Also enable the GROUNDING filter (≥0.7) to block "
                        "responses not supported by the retrieved source context."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-50"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-50",
                    finding_name="Relevance Grounding Filters Present",
                    finding_details=(
                        f"Guardrails with RELEVANCE grounding filters: "
                        f"{', '.join(guardrails_with_relevance)}."
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-50"],
                )
            )
    except Exception as e:
        return _error_findings("Guardrail Relevance Grounding Check", e)
    return findings


def check_prompt_injection_input_validation(inventory) -> Dict[str, Any]:
    """
    FS-51 — Report whether Bedrock Guardrails have PROMPT_ATTACK content
    filters configured to detect prompt injection attempts, and which tier
    each uses.

    Evidence collected: presence of a PROMPT_ATTACK entry in
    ``contentPolicy.filters`` and the value of ``contentPolicy.tier.tierName``
    from GetGuardrail.

    Deliberately NOT asserted: that filter strength or coverage is adequate.
    An absent tier is reported as unknown rather than assumed CLASSIC —
    defaulting it would report an assumption as an observation, the same
    defect corrected for FS-28's topic policy tier.

    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, OWASP LLM01]
    """
    check_name = "Prompt Injection Input Validation Check"
    findings = _empty_findings(check_name)
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-51",
                    finding_name="No Guardrails — Prompt Attack Filters Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with prompt attack filters.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-51"],
                )
            )
            return findings

        guardrails_with_prompt_attack = []
        guardrails_classic_tier_pa = []
        prompt_attack_unknown_tier = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            content_policy = detail.get("contentPolicy", {})
            for f in content_policy.get("filters", []):
                if f.get("type") == "PROMPT_ATTACK":
                    guardrails_with_prompt_attack.append(g["name"])
                    # STANDARD tier (GA June 2025) improves PROMPT_ATTACK detection
                    # by distinguishing jailbreaks from prompt injection attacks.
                    # An ABSENT tier is reported as unknown rather than assumed
                    # CLASSIC.
                    tier = content_policy.get("tier", {}).get("tierName")
                    if tier == "CLASSIC":
                        guardrails_classic_tier_pa.append(g["name"])
                    elif not tier:
                        prompt_attack_unknown_tier.append(g["name"])
                    break

        tier_note = ""
        if prompt_attack_unknown_tier:
            tier_note = (
                " Tier not reported by GetGuardrail for: "
                f"{', '.join(prompt_attack_unknown_tier)} (tier unknown, not assumed CLASSIC)."
            )

        if not guardrails_with_prompt_attack:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-51",
                    finding_name="No Guardrails With Prompt Attack Filters",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have PROMPT_ATTACK filters. "
                        "Prompt injection attacks may bypass system prompts and access controls."
                    ),
                    resolution=(
                        "1. Enable PROMPT_ATTACK content filter in Bedrock Guardrails.\n"
                        "2. Set input filter strength to HIGH.\n"
                        "3. Use input tags (<amazon-bedrock-guardrails-guardContent_xyz>) to "
                        "differentiate user inputs from developer-provided prompts — required for "
                        "PROMPT_ATTACK filters to work correctly with InvokeModel/InvokeModelWithResponseStream.\n"
                        "4. Consider STANDARD tier (GA June 2025) for better jailbreak vs. injection "
                        "classification and broader language support.\n"
                        "5. Implement application-level input sanitization as defense-in-depth."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-prompt-attack.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-51"],
                )
            )
        elif guardrails_classic_tier_pa:
            # Note: guardrails_classic_tier_pa and prompt_attack_unknown_tier are
            # not mutually exclusive — a guardrail set can have some CLASSIC-tier
            # members and some with no tier reported. tier_note (computed above,
            # independent of which branch fires) discloses any unknown-tier
            # guardrails here too, so a mixed-tier result never reports Passed
            # on CLASSIC alone while silently omitting the unknown-tier ones.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-51",
                    finding_name="Prompt Attack Filters on CLASSIC Tier",
                    finding_details=(
                        f"Guardrails with PROMPT_ATTACK filters: {', '.join(guardrails_with_prompt_attack)}. "
                        f"Using CLASSIC tier: {', '.join(guardrails_classic_tier_pa)}. "
                        "STANDARD tier (GA June 2025) better distinguishes jailbreaks from "
                        f"prompt injection and provides broader language support.{tier_note}"
                    ),
                    resolution=(
                        "Consider upgrading to STANDARD tier for improved PROMPT_ATTACK detection. "
                        "Ensure input tags are used to scope user content for PROMPT_ATTACK evaluation. "
                        "STANDARD tier requires cross-region inference on the guardrail."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-prompt-attack.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-51"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-51",
                    finding_name="Guardrails With Prompt Attack Filters Found",
                    finding_details=(
                        f"Guardrails with PROMPT_ATTACK filters: "
                        f"{', '.join(guardrails_with_prompt_attack)}.{tier_note}"
                    ),
                    resolution=(
                        "Ensure input tags are used to scope user content when calling "
                        "InvokeModel/InvokeModelWithResponseStream — required for PROMPT_ATTACK "
                        "filters to evaluate user input separately from system prompts."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-prompt-attack.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-51"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_bedrock_sdk_version_currency(inventory) -> Dict[str, Any]:
    """
    FS-52 — Advisory check: verify Bedrock SDK versions in Lambda functions
    are current (outdated SDKs may lack prompt injection mitigations).
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, ISO 27001 A.12.6]
    """
    findings = _empty_findings("Bedrock SDK Version Currency Check")
    try:
        functions = require(inventory, "lambda_functions")

        bedrock_functions = [
            f
            for f in functions
            if any(
                kw in f["FunctionName"].lower()
                for kw in ["bedrock", "agent", "aiml", "genai"]
            )
        ]

        if not bedrock_functions:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-52",
                    finding_name="No Bedrock-Related Lambda Functions Found",
                    finding_details="No Lambda functions with Bedrock-related naming found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-update.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-52"],
                )
            )
            return findings

        # Check for deprecated runtimes using the definitive allowlist of currently-
        # supported Lambda managed runtimes (sourced from
        # https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html,
        # retrieved June 2026). Any runtime NOT in this set is considered deprecated
        # or end-of-support. This allowlist approach is more reliable than maintaining
        # a denylist (which silently misses newly-deprecated runtimes).
        #
        # Supported as of June 2026 (ordered newest-first per language):
        SUPPORTED_RUNTIMES = {
            # Python
            "python3.14",
            "python3.13",
            "python3.12",
            "python3.11",
            "python3.10",
            # Node.js
            "nodejs24.x",
            "nodejs22.x",
            # Java
            "java25",
            "java21",
            "java17",
            "java11",
            "java8.al2",
            # .NET
            "dotnet10",
            "dotnet9",
            "dotnet8",
            # Ruby
            "ruby4.0",
            "ruby3.4",
            "ruby3.3",
            # OS-only / custom runtimes
            "provided.al2023",
            "provided.al2",
        }
        outdated_functions = [
            f["FunctionName"]
            for f in bedrock_functions
            if f.get("Runtime", "") and f["Runtime"] not in SUPPORTED_RUNTIMES
        ]

        if outdated_functions:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-52",
                    finding_name="Bedrock Lambda Functions on Deprecated Runtimes",
                    finding_details=(
                        f"Functions on deprecated runtimes: {', '.join(outdated_functions[:10])}. "
                        "Deprecated runtimes may use outdated boto3/SDK versions lacking security patches."
                    ),
                    resolution=(
                        "1. Upgrade Lambda functions to a supported runtime — Python 3.12+, "
                        "Node.js 22.x or 24.x, Java 21+, or .NET 8+.\n"
                        "2. Update boto3 to the latest version in Lambda layers (pin the version "
                        "in requirements.txt and redeploy).\n"
                        "3. Enable Lambda runtime management controls for automatic minor-version "
                        "updates (runtimeManagementConfig.updateRuntimeOn = 'Auto').\n"
                        "4. Refer to https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html "
                        "for the authoritative list of supported and deprecated runtimes."
                    ),
                    reference="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-update.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-52"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-52",
                    finding_name="Bedrock Lambda Functions on Current Runtimes",
                    finding_details=f"All {len(bedrock_functions)} Bedrock Lambda function(s) use current runtimes.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/lambda/latest/dg/runtimes-update.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-52"],
                )
            )
    except Exception as e:
        return _error_findings("Bedrock SDK Version Currency Check", e)
    return findings


def check_waf_sql_injection_rules(inventory) -> Dict[str, Any]:
    """
    FS-53 — Verify WAF Web ACLs include SQL injection and XSS managed rules
    to protect GenAI API endpoints from injection attacks.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 6.4.1, OWASP LLM01]
    """
    findings = _empty_findings("WAF Injection Protection Rules Check")
    try:
        # require() raises if inventory is None or web_acls is _Unavailable,
        # propagating to the outer except which yields COULD_NOT_ASSESS.
        web_acl_inv = require(inventory, "web_acls")
        acls = web_acl_inv.summaries

        if not acls:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-53",
                    finding_name="No WAF Web ACLs — Injection Rules Not Applicable",
                    finding_details="No regional WAF Web ACLs found.",
                    resolution="Create WAF Web ACLs with injection protection rules (see FS-01).",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-53"],
                )
            )
            return findings

        INJECTION_RULE_GROUPS = {
            "AWSManagedRulesSQLiRuleSet",
            "AWSManagedRulesCommonRuleSet",
            "AWSManagedRulesKnownBadInputsRuleSet",
        }

        acls_without_injection_rules = []
        for acl_summary in acls:
            # detail_by_id holds get_web_acl(...)['WebACL'] or _Unavailable.
            # Accessing an _Unavailable entry re-raises its stored error, which
            # propagates to the outer except and yields COULD_NOT_ASSESS —
            # matching today's behaviour (no per-item try/except in this check).
            detail = web_acl_inv.detail_by_id[acl_summary["Id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            acl = detail
            rule_names = {
                r.get("Statement", {})
                .get("ManagedRuleGroupStatement", {})
                .get("Name", "")
                for r in acl.get("Rules", [])
            }
            if not rule_names.intersection(INJECTION_RULE_GROUPS):
                acls_without_injection_rules.append(acl_summary["Name"])

        if acls_without_injection_rules:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-53",
                    finding_name="WAF ACLs Missing Injection Protection Rules",
                    finding_details=(
                        f"WAF ACLs without SQL injection/XSS rules: "
                        f"{', '.join(acls_without_injection_rules[:10])}."
                    ),
                    resolution=(
                        "Add AWS Managed Rule Groups to WAF ACLs:\n"
                        "- AWSManagedRulesSQLiRuleSet (SQL injection)\n"
                        "- AWSManagedRulesCommonRuleSet (XSS, LFI, RFI)\n"
                        "- AWSManagedRulesKnownBadInputsRuleSet (prompt injection patterns)"
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-53"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-53",
                    finding_name="WAF Injection Protection Rules Present",
                    finding_details=f"All {len(acls)} WAF ACL(s) have injection protection rules.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-53"],
                )
            )
    except Exception as e:
        return _error_findings("WAF Injection Protection Rules Check", e)
    return findings


def check_penetration_testing_evidence() -> Dict[str, Any]:
    """
    FS-54 — Advisory check: verify penetration testing has been conducted
    on GenAI applications (prompt injection, jailbreak testing).
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 11.4, DORA Art.26]
    """
    findings = _empty_findings("Penetration Testing Evidence Check")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-54",
            finding_name="ADVISORY: Penetration Testing — Manual Review Required",
            finding_details=(
                "Penetration testing evidence cannot be verified via AWS APIs. "
                "Manual review required to confirm GenAI applications have been tested."
            ),
            resolution=(
                "1. Conduct penetration testing of GenAI applications at least annually and "
                "before major releases.\n"
                "2. Include AI-specific test cases: prompt injection, jailbreak, indirect "
                "(cross-domain) injection, system-prompt leakage, and data-extraction attempts.\n"
                "3. Consider AWS Security Agent (now part of AWS Continuum) for on-demand, AI-driven "
                "penetration testing "
                "(GA March 2026 in US East N. Virginia, US West Oregon, Europe Ireland, "
                "Europe Frankfurt, Asia Pacific Sydney, Asia Pacific Tokyo, since expanded to "
                "additional Regions, with cross-account "
                "shared-VPC testing via AWS RAM). Open-source tools such as Garak or PyRIT and "
                "manual red-teaming are complementary options. Verify current regional availability "
                "in the service-availability note on the Resilience page of the AWS Security "
                "Agent documentation before relying on it.\n"
                "4. Document findings and remediation for regulatory examination, and tag tested "
                "resources with a last-pentest-date for audit trail.\n"
                "5. For DORA compliance, include GenAI in TLPT (Threat-Led Penetration Testing) scope."
            ),
            reference="https://docs.aws.amazon.com/securityagent/latest/userguide/resilience.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-54"],
        )
    )
    return findings


# ===========================================================================
# CATEGORY 13: IMPROPER OUTPUT HANDLING (FS-55 to FS-58)
# CATEGORY 14: OFF-TOPIC & INAPPROPRIATE OUTPUT (FS-59 to FS-60)
# CATEGORY 15: OUT-OF-DATE TRAINING DATA (FS-61 to FS-63)
# COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, NYDFS 500, OWASP LLM05]
# ===========================================================================


def check_output_validation_lambda(inventory) -> Dict[str, Any]:
    """
    FS-55 — Check for Lambda functions implementing output validation/sanitization
    in GenAI application pipelines.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, OWASP LLM05]
    """
    findings = _empty_findings("Output Validation Lambda Check")
    try:
        functions = require(inventory, "lambda_functions")

        validation_functions = [
            f
            for f in functions
            if any(
                kw in f["FunctionName"].lower()
                for kw in ["validate", "sanitize", "filter", "output"]
            )
        ]

        if not validation_functions:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-55",
                    finding_name="No Output Validation Functions Found",
                    finding_details=(
                        "No Lambda functions with output validation/sanitization naming found. "
                        "GenAI outputs may be passed directly to downstream systems without validation."
                    ),
                    resolution=(
                        "1. Implement output validation Lambda functions in GenAI pipelines.\n"
                        "2. Validate output schema, length, and content before downstream use.\n"
                        "3. Sanitize outputs before rendering in web UIs (XSS prevention).\n"
                        "4. Encode outputs appropriately for the target context (HTML, SQL, JSON)."
                    ),
                    reference="https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-55"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-55",
                    finding_name="Output Validation Functions Present",
                    finding_details=f"Found {len(validation_functions)} output validation/sanitization function(s).",
                    resolution="No action required.",
                    reference="https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-55"],
                )
            )
    except Exception as e:
        return _error_findings("Output Validation Lambda Check", e)
    return findings


def check_xss_prevention_waf(inventory) -> Dict[str, Any]:
    """
    FS-56 — Verify WAF rules include XSS prevention for GenAI web application outputs.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, PCI-DSS 6.4.1, OWASP LLM05]
    """
    findings = _empty_findings("XSS Prevention WAF Check")
    try:
        # require() raises if inventory is None or web_acls is _Unavailable.
        web_acl_inv = require(inventory, "web_acls")
        acls = web_acl_inv.summaries

        if not acls:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-56",
                    finding_name="No WAF ACLs — XSS Prevention Not Applicable",
                    finding_details="No regional WAF Web ACLs found.",
                    resolution="Create WAF ACLs with XSS prevention rules.",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-56"],
                )
            )
            return findings

        # XSS protections live in the AWS managed Common Rule Set. Inspect each ACL's
        # managed-rule-group statements (mirrors FS-53) to actually verify coverage
        # rather than emitting an unconditional "review required" pass.
        acls_without_xss = []
        for acl_summary in acls:
            # detail_by_id holds get_web_acl(...)['WebACL'] or _Unavailable.
            # An _Unavailable entry re-raises its error → outer except → COULD_NOT_ASSESS.
            detail = web_acl_inv.detail_by_id[acl_summary["Id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            acl = detail
            rule_groups = {
                r.get("Statement", {})
                .get("ManagedRuleGroupStatement", {})
                .get("Name", "")
                for r in acl.get("Rules", [])
            }
            if "AWSManagedRulesCommonRuleSet" not in rule_groups:
                acls_without_xss.append(acl_summary["Name"])

        if acls_without_xss:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-56",
                    finding_name="WAF ACLs Missing Common Rule Set (XSS)",
                    finding_details=(
                        "The following WAF ACL(s) do not include AWSManagedRulesCommonRuleSet, "
                        "which provides cross-site-scripting (XSS) protections for GenAI web "
                        "application outputs:\n"
                        + "\n".join(f"- {a}" for a in acls_without_xss[:10])
                    ),
                    resolution=(
                        "1. Add AWSManagedRulesCommonRuleSet to each WAF ACL protecting GenAI "
                        "web applications (it includes the CrossSiteScripting rules).\n"
                        "2. Additionally, implement Content Security Policy (CSP) response headers."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-56"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-56",
                    finding_name="XSS Prevention Common Rule Set Present",
                    finding_details=(
                        f"All {len(acls)} WAF ACL(s) include AWSManagedRulesCommonRuleSet "
                        "(XSS protections)."
                    ),
                    resolution=(
                        "No action required. Consider also implementing Content Security Policy "
                        "(CSP) response headers as defense in depth."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/aws-managed-rule-groups-baseline.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-56"],
                )
            )
    except Exception as e:
        return _error_findings("XSS Prevention WAF Check", e)
    return findings


def check_output_encoding_advisory() -> Dict[str, Any]:
    """
    FS-57 — Advisory check: verify application encodes GenAI outputs
    appropriately for the rendering context.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, OWASP LLM05]
    """
    findings = _empty_findings("Output Encoding Advisory")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-57",
            finding_name="ADVISORY: Output Encoding — Manual Review Required",
            finding_details=(
                "Output encoding practices cannot be verified via AWS APIs. "
                "Manual code review required."
            ),
            resolution=(
                "1. HTML-encode GenAI outputs before rendering in web UIs.\n"
                "2. Use parameterized queries when GenAI output is used in database operations.\n"
                "3. JSON-encode outputs before embedding in JavaScript contexts.\n"
                "4. Validate output length and format before passing to downstream APIs."
            ),
            reference="https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-57"],
        )
    )
    return findings


def check_output_schema_validation(inventory) -> Dict[str, Any]:
    """
    FS-58 — Check for structured output validation using Bedrock response
    schemas or application-level JSON schema validation.
    COMPLIANCE_PLACEHOLDER: [NYDFS 500.06, FFIEC CAT, OWASP LLM05]
    """
    findings = _empty_findings("Output Schema Validation Check")
    try:
        # Check for EventBridge Pipes or Lambda destinations that could validate outputs
        functions = require(inventory, "lambda_functions")

        schema_functions = [
            f
            for f in functions
            if any(
                kw in f["FunctionName"].lower()
                for kw in ["schema", "validate", "parse", "format"]
            )
        ]

        findings["csv_data"].append(
            create_finding(
                check_id="FS-58",
                finding_name="ADVISORY: Output Schema Validation — Manual Review Required",
                finding_details=(
                    f"Found {len(schema_functions)} Lambda function(s) whose names suggest "
                    "schema/validation handling. Structured-output / JSON-schema validation of "
                    "GenAI responses is an application-layer control that cannot be verified "
                    "automatically — manual review required."
                ),
                resolution=(
                    "1. Use Bedrock structured output (response schemas) where supported.\n"
                    "2. Implement JSON schema validation on Lambda output processors.\n"
                    "3. Reject malformed outputs and return safe error responses.\n"
                    "4. Log schema validation failures to CloudWatch for monitoring."
                ),
                reference="https://docs.aws.amazon.com/bedrock/latest/userguide/inference-parameters.html",
                severity="Informational",
                status="N/A",
                compliance_frameworks=COMPLIANCE_MAP["FS-58"],
            )
        )
    except Exception as e:
        return _error_findings("Output Schema Validation Check", e)
    return findings


def check_guardrail_topic_allowlist(inventory) -> Dict[str, Any]:
    """
    FS-59 — Report whether Bedrock Guardrails topic policies restrict GenAI
    to on-topic responses, and which tier each uses.

    Evidence collected: presence of ``topicPolicy.topics`` and the value of
    ``topicPolicy.tier.tierName`` from GetGuardrail.

    Deliberately NOT asserted: that the configured topics cover every
    relevant off-topic category. An absent tier is reported as unknown
    rather than assumed CLASSIC — defaulting it would report an assumption
    as an observation, the same defect corrected for FS-28's topic policy
    tier (this check reads the same ``topicPolicy`` field for a different
    purpose).

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    check_name = "Guardrail Topic Allowlist Check"
    findings = _empty_findings(check_name)
    try:
        guardrail_inv = require(inventory, "guardrails")
        guardrails = guardrail_inv.summaries

        if not guardrails:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-59",
                    finding_name="No Guardrails — Topic Allowlist Not Applicable",
                    finding_details="No Bedrock Guardrails configured.",
                    resolution="Configure guardrails with topic policies to restrict off-topic responses.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-59"],
                )
            )
            return findings

        guardrails_with_topics = []
        topics_classic_tier = []
        topics_unknown_tier = []
        for g in guardrails:
            detail = guardrail_inv.detail_by_id[g["id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            topic_policy = detail.get("topicPolicy", {})
            if topic_policy.get("topics"):
                guardrails_with_topics.append(g["name"])
                # An ABSENT tier is reported as unknown rather than assumed
                # CLASSIC.
                tier = topic_policy.get("tier", {}).get("tierName")
                if tier == "CLASSIC":
                    topics_classic_tier.append(g["name"])
                elif not tier:
                    topics_unknown_tier.append(g["name"])

        tier_note = ""
        if topics_unknown_tier:
            tier_note = (
                " Tier not reported by GetGuardrail for: "
                f"{', '.join(topics_unknown_tier)} (tier unknown, not assumed CLASSIC)."
            )

        if not guardrails_with_topics:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-59",
                    finding_name="No Guardrails With Topic Restrictions",
                    finding_details=(
                        f"Found {len(guardrails)} guardrail(s) but none have topic policies. "
                        "GenAI may respond to off-topic requests (e.g., medical advice, legal advice)."
                    ),
                    resolution=(
                        "Add denied topics to guardrails for off-topic categories:\n"
                        "- Medical/health advice\n"
                        "- Legal advice\n"
                        "- Political opinions\n"
                        "- Non-financial product recommendations\n"
                        "Consider the STANDARD tier (GA June 2025) for broader language support; "
                        "it requires cross-region inference on the guardrail."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-59"],
                )
            )
        elif topics_classic_tier:
            # Note: topics_classic_tier and topics_unknown_tier are not mutually
            # exclusive — a guardrail set can have some CLASSIC-tier members and
            # some with no tier reported. tier_note (computed above, independent
            # of which branch fires) discloses any unknown-tier guardrails here
            # too, so a mixed-tier result never reports Passed on CLASSIC alone
            # while silently omitting the unknown-tier guardrails.
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-59",
                    finding_name="Topic Restrictions Configured on CLASSIC Tier",
                    finding_details=(
                        f"Guardrails with topic policies: {', '.join(guardrails_with_topics)}. "
                        f"The following use the CLASSIC tier: {', '.join(topics_classic_tier)}. "
                        "CLASSIC tier supports English, French, and Spanish only; the STANDARD tier "
                        f"(GA June 2025) adds broader language support for off-topic detection.{tier_note}"
                    ),
                    resolution=(
                        "For multilingual deployments, consider upgrading denied topics to "
                        "the STANDARD tier (topicsTierConfig.tierName=STANDARD via UpdateGuardrail; "
                        "requires a cross-region inference profile)."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-59"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-59",
                    finding_name="Guardrail Topic Restrictions Configured",
                    finding_details=(
                        f"Guardrails with topic policies: {', '.join(guardrails_with_topics)}."
                        f"{tier_note}"
                    ),
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-components.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-59"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_contextual_grounding_for_offtopic() -> Dict[str, Any]:
    """
    FS-60 — Verify contextual grounding is used to keep GenAI responses
    within the scope of the provided context/system prompt.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    # This overlaps with FS-47/FS-48 but focuses on off-topic prevention
    findings = _empty_findings("Contextual Grounding for Off-Topic Prevention")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-60",
            finding_name="ADVISORY: Contextual Grounding for Off-Topic Prevention",
            finding_details=(
                "Contextual grounding for off-topic prevention is covered by guardrail "
                "grounding checks (FS-47) and RAG configuration (FS-48). "
                "Additionally verify system prompts explicitly scope the assistant's role."
            ),
            resolution=(
                "1. Include explicit scope instructions in system prompts.\n"
                "2. Use Bedrock Guardrails relevance grounding filter.\n"
                "3. Test with off-topic prompts in QA to verify rejection behavior."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/guardrails-contextual-grounding-check.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-60"],
        )
    )
    return findings


def check_knowledge_base_sync_schedule(inventory) -> Dict[str, Any]:
    """
    FS-61 — Verify Bedrock Knowledge Base data sources have automated sync
    schedules to keep training/retrieval data current.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT]
    """
    # Reuses logic from FS-31 but focuses on scheduled automation
    findings = _empty_findings("Knowledge Base Sync Schedule Check")
    try:
        kbs = require(inventory, "knowledge_bases").summaries
        events = boto3.client("events", config=boto3_config)
        scheduler = boto3.client("scheduler", config=boto3_config)

        if not kbs:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-61",
                    finding_name="No Knowledge Bases Found",
                    finding_details="No Bedrock Knowledge Bases found.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-61"],
                )
            )
            return findings

        # Check for EventBridge rules (legacy) that trigger KB sync.
        rules = _paginate(events, "list_rules", "Rules")
        kb_sync_rules = [
            r
            for r in rules
            if "bedrock" in r.get("Name", "").lower()
            or "knowledge" in r.get("Name", "").lower()
        ]

        # Check for EventBridge Scheduler schedules (the AWS-recommended approach;
        # classic EventBridge scheduled rules are a legacy feature). The
        # ListSchedules name-prefix filter is server-side, so do a broad list and
        # match on name/target heuristics here. ListSchedules is paginated via
        # NextToken. Treat an access error as a soft signal (do not fail the whole
        # check) since Scheduler may not be in use.
        kb_sync_schedules = []
        scheduler_access_error = None
        try:
            schedules = _paginate(scheduler, "list_schedules", "Schedules")
            kb_sync_schedules = [
                s
                for s in schedules
                if "bedrock" in s.get("Name", "").lower()
                or "knowledge" in s.get("Name", "").lower()
                or "kb-sync" in s.get("Name", "").lower()
                or "ingestion" in s.get("Name", "").lower()
                or "bedrock" in s.get("Target", {}).get("Arn", "").lower()
            ]
        except ClientError as e:
            if not _is_access_error(e):
                raise
            # Remember the access error. If we ALSO find no EventBridge-rule
            # automation, we cannot conclude the control is absent (a Scheduler
            # schedule we were not allowed to read might exist) — so we surface
            # COULD_NOT_ASSESS rather than a false Failed. If a rule IS found, the
            # positive evidence stands and the access gap is immaterial.
            scheduler_access_error = e
            logger.warning(
                "Could not list EventBridge Scheduler schedules (access denied); "
                "grant scheduler:ListSchedules for full FS-61 coverage."
            )

        total_sync_automation = len(kb_sync_rules) + len(kb_sync_schedules)

        # No positive evidence AND we were blocked from reading Scheduler →
        # unknown state, not a confirmed failure. Re-raise so the handler emits a
        # COULD NOT ASSESS row (Status="N/A", Severity="Low").
        if total_sync_automation == 0 and scheduler_access_error is not None:
            raise scheduler_access_error

        if total_sync_automation == 0:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-61",
                    finding_name="No Automated KB Sync Schedules Detected",
                    finding_details=(
                        f"Found {len(kbs)} Knowledge Base(s) but no EventBridge Scheduler "
                        "schedules or EventBridge rules with 'bedrock'/'knowledge' naming were "
                        "found. Note: this check uses a name/target heuristic — sync automation "
                        "with other naming conventions, AWS Step Functions-based orchestration, "
                        "or native Bedrock API-triggered syncs (StartIngestionJob called directly) "
                        "will not be detected. Verify sync automation manually if applicable."
                    ),
                    resolution=(
                        "1. Use EventBridge Scheduler (the AWS-recommended approach) to create a "
                        "recurring schedule (e.g., rate(1 day) or a cron expression) that triggers a "
                        "Lambda function calling the Bedrock StartIngestionJob API for each data source. "
                        "Classic EventBridge scheduled rules also work but are a legacy feature.\n"
                        "2. As of December 2024, Bedrock Knowledge Bases supports custom connectors "
                        "and streaming data ingestion — use direct document ingestion "
                        "(KnowledgeBaseDocuments API) for real-time updates without a full S3 sync.\n"
                        "3. Set sync frequency based on data currency requirements "
                        "(e.g., hourly for market data, daily for regulatory guidance).\n"
                        "4. Configure CloudWatch alarms or SNS notifications on "
                        "IngestionJob FAILED status for sync failure alerting."
                    ),
                    reference="https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-61"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-61",
                    finding_name="Automated KB Sync Schedules Present",
                    finding_details=(
                        f"Found {len(kb_sync_schedules)} EventBridge Scheduler schedule(s) and "
                        f"{len(kb_sync_rules)} EventBridge rule(s) with KB-sync naming. "
                        "Verify each targets the Bedrock StartIngestionJob API for your KB data sources."
                    ),
                    resolution="Verify the schedule frequency matches your data-currency requirements.",
                    reference="https://docs.aws.amazon.com/scheduler/latest/UserGuide/what-is-scheduler.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-61"],
                )
            )
    except Exception as e:
        return _error_findings("Knowledge Base Sync Schedule Check", e)
    return findings


def check_data_currency_disclaimer_advisory() -> Dict[str, Any]:
    """
    FS-62 — Advisory check: verify application adds data currency disclaimers
    to GenAI outputs (e.g., 'Information current as of [date]').
    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, MAS TRM 9.2]
    """
    findings = _empty_findings("Data Currency Disclaimer Advisory")
    findings["csv_data"].append(
        create_finding(
            check_id="FS-62",
            finding_name="ADVISORY: Data Currency Disclaimer — Manual Review Required",
            finding_details=(
                "Data currency disclaimers cannot be verified via AWS APIs. "
                "Manual review required."
            ),
            resolution=(
                "1. Add data currency disclaimers to GenAI outputs: "
                "'Information based on data current as of [KB last sync date].'\n"
                "2. Expose KB last sync timestamp in application responses.\n"
                "3. Alert users when KB data is older than defined threshold."
            ),
            reference="https://docs.aws.amazon.com/bedrock/latest/userguide/kb-data-source-sync-ingest.html",
            severity="Informational",
            status="N/A",
            compliance_frameworks=COMPLIANCE_MAP["FS-62"],
        )
    )
    return findings


def check_foundation_model_lifecycle_policy() -> Dict[str, Any]:
    """
    FS-63 — Report whether the account has any detectable governance for
    foundation model lifecycle, and list legacy models offered in the region as
    context for that review.

    Evidence collected: ListFoundationModels for ``modelLifecycle.status`` and
    DescribeConfigRules for rules whose name mentions "lifecycle" or "model".

    Scope note, and the reason this check was restructured:
    ListFoundationModels returns the REGION CATALOGUE, not the models this
    account uses. Verified live: us-east-1 offers 119 models of which 19 are
    LEGACY, none necessarily used by the account. An earlier revision failed the
    check whenever a legacy model existed in the region and no Config rule was
    found, which fires on virtually every account in the region regardless of
    posture, and its passing branch ("No legacy models detected") was
    effectively unreachable. The account-specific signal is the absence of
    lifecycle governance, so that is what the verdict now keys off; legacy
    availability is reported as context.

    Deliberately NOT asserted:
      - that the account invokes any of the legacy models listed,
      - that a matching Config rule actually enforces model currency,
      - that a documented lifecycle process exists outside AWS Config.
    Name-matched Config rules are a heuristic for "some governance exists",
    not proof of an effective process.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, FFIEC CAT, ISO 27001 A.12.5]
    """
    check_name = "Foundation Model Lifecycle Policy Check"
    reference = (
        "https://docs.aws.amazon.com/bedrock/latest/userguide/model-lifecycle.html"
    )
    findings = _empty_findings(check_name)
    try:
        bedrock = boto3.client("bedrock", config=boto3_config)
        # Do not filter by output modality: legacy/deprecated models exist across
        # TEXT, EMBEDDING, and IMAGE modalities. Embedding models are widely used
        # in FinServ RAG pipelines; a legacy embedding model silently serves stale
        # vector representations. Fetch all modalities to surface any deprecated model.
        # ListFoundationModels has no continuation token in the Bedrock API
        # model, so there is no paginated form of this operation.
        models = bedrock.list_foundation_models().get("modelSummaries", [])
        legacy_models = [
            m["modelId"]
            for m in models
            if m.get("modelLifecycle", {}).get("status") == "LEGACY"
        ]
        legacy_context = (
            f"For context, {len(legacy_models)} of {len(models)} model(s) offered in this region "
            f"are marked LEGACY (for example {', '.join(sorted(legacy_models)[:5])}); this "
            "reflects the regional catalogue, not this account's usage."
            if legacy_models
            else f"No LEGACY models are offered in this region ({len(models)} model(s) reviewed)."
        )

        try:
            config_client = boto3.client("config", config=boto3_config)
            rules = _paginate(config_client, "describe_config_rules", "ConfigRules")
        except ClientError as e:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-63",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        "Unable to enumerate AWS Config rules "
                        f"({e.response['Error']['Code']}), so account-side lifecycle governance "
                        f"could not be assessed. {legacy_context}"
                    ),
                    resolution="Ensure the assessment role has config:DescribeConfigRules permission.",
                    reference=reference,
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-63"],
                )
            )
            return findings

        lifecycle_rules = [
            r
            for r in rules
            if "lifecycle" in r.get("ConfigRuleName", "").lower()
            or "model" in r.get("ConfigRuleName", "").lower()
        ]

        if lifecycle_rules:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-63",
                    finding_name="Foundation Model Lifecycle Governance Detected",
                    finding_details=(
                        f"{len(lifecycle_rules)} AWS Config rule(s) with lifecycle- or "
                        "model-related names were found, indicating some account-side model "
                        "lifecycle governance: "
                        f"{', '.join(sorted(r['ConfigRuleName'] for r in lifecycle_rules)[:5])}. "
                        "Rule names are a heuristic; whether these rules enforce model currency "
                        f"is not assessed. {legacy_context}"
                    ),
                    resolution=(
                        "Confirm the matched rules genuinely track model currency, and that "
                        "deprecation notifications are monitored."
                    ),
                    reference=reference,
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-63"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-63",
                    finding_name="No Foundation Model Lifecycle Governance Detected",
                    finding_details=(
                        "No AWS Config rule with a lifecycle- or model-related name was found, so "
                        "no account-side control was detected for migrating off deprecated "
                        "foundation models. A documented process may exist outside AWS Config and "
                        f"would not be visible here. {legacy_context}"
                    ),
                    resolution=(
                        "1. Document a model lifecycle process covering evaluation and migration.\n"
                        "2. Subscribe to AWS Bedrock model deprecation notifications.\n"
                        "3. Test and migrate off legacy models you actually invoke, before their "
                        "end-of-life dates.\n"
                        "4. Record training-data cutoff dates in the model inventory (see FS-13)."
                    ),
                    reference=reference,
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-63"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_kb_datasource_s3_event_notifications(inventory) -> Dict[str, Any]:
    """
    FS-65 — Check that S3 event notifications (EventBridge or SNS/SQS) are
    configured on Knowledge Base data-source buckets to detect unauthorized
    document changes in real time.
    COMPLIANCE_PLACEHOLDER: [SR 11-7, ISO 27001 A.12, FFIEC CAT]
    """
    findings = _empty_findings("KB Data Source S3 Event Notifications Check")
    try:
        kb_inv = require(inventory, "knowledge_bases")
        kbs = kb_inv.summaries
        s3_client = boto3.client("s3", config=boto3_config)

        if not kbs:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-65",
                    finding_name="No Knowledge Bases Found",
                    finding_details="No Bedrock Knowledge Bases found; S3 event notification check not applicable.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventNotifications.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-65"],
                )
            )
            return findings

        buckets_without_notifications = []
        missing_buckets = []
        for kb in kbs:
            kb_id = kb["knowledgeBaseId"]
            data_sources = kb_inv.data_sources_by_kb.get(kb_id, [])
            if isinstance(data_sources, _Unavailable):
                raise data_sources.error
            for ds in data_sources:
                ds_id = ds["dataSourceId"]
                ds_detail = kb_inv.data_source_detail.get((kb_id, ds_id))
                if isinstance(ds_detail, _Unavailable):
                    raise ds_detail.error
                if ds_detail is None:
                    continue
                s3_config = (
                    ds_detail.get("dataSource", {})
                    .get("dataSourceConfiguration", {})
                    .get("s3Configuration", {})
                )
                bucket = _bucket_name_from_arn(s3_config.get("bucketArn", ""))
                if not bucket:
                    continue
                try:
                    notif = s3_client.get_bucket_notification_configuration(
                        Bucket=bucket
                    )
                    has_notif = any(
                        [
                            notif.get("TopicConfigurations"),
                            notif.get("QueueConfigurations"),
                            notif.get("LambdaFunctionConfigurations"),
                            notif.get("EventBridgeConfiguration"),
                        ]
                    )
                    if not has_notif:
                        buckets_without_notifications.append(bucket)
                except ClientError as e:
                    # An access error means we could not read the notification
                    # config; re-raise so it surfaces as could-not-assess rather
                    # than a false "missing notifications" finding.
                    if _is_access_error(e):
                        raise
                    # The data source points to a deleted bucket — a distinct
                    # integrity problem, not "notifications missing."
                    if _is_missing_bucket_error(e):
                        logger.warning(
                            f"KB '{kb.get('name', kb_id)}' data source "
                            f"'{ds.get('name', ds['dataSourceId'])}' references a "
                            f"deleted bucket: {bucket}"
                        )
                        missing_buckets.append(
                            f"{bucket} (KB '{kb.get('name', kb_id)}', "
                            f"source '{ds.get('name', ds['dataSourceId'])}')"
                        )
                        continue
                    buckets_without_notifications.append(f"{bucket} (error)")

        # A dangling data-source reference to a deleted bucket is a real integrity
        # finding — emit it separately so it is not conflated with "no notifications."
        if missing_buckets:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-65",
                    finding_name="KB Data Source References a Deleted S3 Bucket",
                    finding_details=(
                        "One or more Knowledge Base data sources point to S3 buckets that no "
                        "longer exist (NoSuchBucket). Document-change monitoring cannot be "
                        "assessed and KB grounding data is missing for these sources:\n"
                        + "\n".join(f"- {b}" for b in missing_buckets[:10])
                    ),
                    resolution=(
                        "1. Investigate why the data-source bucket was deleted (accidental "
                        "deletion, environment teardown, or stale KB configuration).\n"
                        "2. Recreate/restore the bucket (with event notifications and versioning "
                        "enabled), or remove the orphaned data source from the Knowledge Base.\n"
                        "3. Re-run a KB ingestion job after restoring the data source."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventBridge.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-65"],
                )
            )

        if buckets_without_notifications:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-65",
                    finding_name="KB Data Source Buckets Missing S3 Event Notifications",
                    finding_details=(
                        "The following KB data-source S3 buckets have no event notifications configured. "
                        "Unauthorized document modifications will not be detected in real time:\n"
                        + "\n".join(
                            f"- {b}" for b in buckets_without_notifications[:10]
                        )
                    ),
                    resolution=(
                        "1. Enable Amazon EventBridge notifications on each KB data-source S3 bucket.\n"
                        "2. Create an EventBridge rule to route s3:ObjectCreated, s3:ObjectRemoved, "
                        "and s3:ObjectModified events to an SNS topic or Lambda for alerting.\n"
                        "3. Integrate alerts into your security incident response workflow."
                    ),
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventBridge.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-65"],
                )
            )
        elif not missing_buckets:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-65",
                    finding_name="KB Data Source S3 Event Notifications Configured",
                    finding_details="All KB data-source S3 buckets have event notifications configured.",
                    resolution="No action required.",
                    reference="https://docs.aws.amazon.com/AmazonS3/latest/userguide/EventBridge.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-65"],
                )
            )
    except Exception as e:
        return _error_findings("KB Data Source S3 Event Notifications Check", e)
    return findings


def check_agentcore_end_user_identity_propagation() -> Dict[str, Any]:
    """
    FS-66 — Report whether each AgentCore runtime has a custom JWT authorizer,
    the configuration prerequisite for carrying an end-user identity into the
    runtime.

    Evidence collected: ListAgentRuntimes (paginated), then GetAgentRuntime per
    runtime to read ``authorizerConfiguration.customJWTAuthorizer``. As with
    FS-08, the list operation does not return authorizerConfiguration.

    Deliberately NOT asserted:
      - that the end-user identity is actually forwarded to downstream tool
        services (an application behavior, not a runtime property),
      - that tool services validate a propagated identity,
      - that tokens are not over-shared.
    Note also that ``authorizerConfiguration`` exposes only
    ``customJWTAuthorizer``; there is no ``iamAuthorizer`` member, so no
    IAM-authorizer claim is made.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, NYDFS 500.06, MAS TRM 9.1]
    """
    check_name = "AgentCore End-User Identity Propagation Check"
    manual_review = (
        "A JWT authorizer is a prerequisite, not proof of propagation; verify "
        "downstream token forwarding and validation manually."
    )
    findings = _empty_findings(check_name)
    try:
        agentcore = boto3.client("bedrock-agentcore-control", config=boto3_config)
        try:
            runtimes = _paginate(agentcore, "list_agent_runtimes", "agentRuntimes")
        except ClientError as e:
            if "AccessDenied" in str(e) or "UnrecognizedClientException" in str(e):
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-66",
                        finding_name="AgentCore Identity Propagation — Access Check",
                        finding_details="Unable to enumerate AgentCore runtimes (access denied or service unavailable in region).",
                        resolution="Ensure assessment role has bedrock-agentcore:ListAgentRuntimes permission.",
                        reference="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html",
                        severity="Low",
                        status="N/A",
                        compliance_frameworks=COMPLIANCE_MAP["FS-66"],
                    )
                )
                return findings
            raise

        if not runtimes:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-66",
                    finding_name="No AgentCore Runtimes Found",
                    finding_details="No AgentCore runtimes found; identity propagation check not applicable.",
                    resolution=(
                        "If using AgentCore, configure token propagation so end-user identities "
                        "are forwarded to tool services."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-66"],
                )
            )
            return findings

        # authorizerConfiguration comes from GetAgentRuntime only.
        with_jwt: List[str] = []
        without_jwt: List[str] = []
        undetermined: List[str] = []

        for runtime in runtimes:
            name = runtime.get("agentRuntimeName") or runtime.get("agentRuntimeId", "")
            runtime_id = runtime.get("agentRuntimeId")
            if not runtime_id:
                undetermined.append(f"{name} (no agentRuntimeId in list response)")
                continue
            try:
                detail = agentcore.get_agent_runtime(agentRuntimeId=runtime_id)
            except ClientError as e:
                undetermined.append(f"{name} ({e.response['Error']['Code']})")
                continue
            except Exception as e:  # noqa: BLE001 - per-runtime isolation
                undetermined.append(f"{name} ({type(e).__name__})")
                continue
            authorizer = detail.get("authorizerConfiguration") or {}
            if authorizer.get("customJWTAuthorizer"):
                with_jwt.append(name)
            else:
                without_jwt.append(name)

        if without_jwt:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-66",
                    finding_name="AgentCore Runtimes Without JWT Authorizer",
                    finding_details=(
                        "The following runtimes have no customJWTAuthorizer, so no end-user "
                        "identity can reach the runtime and tool calls are authorized only by "
                        "the agent execution role:\n"
                        + "\n".join(f"- {r}" for r in without_jwt[:10])
                        + f"\n{manual_review}"
                    ),
                    resolution=(
                        "1. Configure a custom JWT authorizer on each AgentCore runtime.\n"
                        "2. Propagate the end-user's identity token to downstream tool services.\n"
                        "3. Ensure tool services validate the propagated identity before executing actions.\n"
                        "4. Do not expose propagated identity tokens to unauthorized third parties."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html",
                    severity="High",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-66"],
                )
            )

        if with_jwt:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-66",
                    finding_name="AgentCore Runtimes With JWT Authorizer Configured",
                    finding_details=(
                        f"{len(with_jwt)} of {len(runtimes)} runtime(s) have a "
                        f"customJWTAuthorizer: {', '.join(with_jwt)}. " + manual_review
                    ),
                    resolution="No action required for JWT authorizer presence.",
                    reference="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html",
                    severity="High",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-66"],
                )
            )

        if undetermined:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-66",
                    finding_name=f"{COULD_NOT_ASSESS_PREFIX}{check_name}",
                    finding_details=(
                        "Could not read authorizerConfiguration for: "
                        f"{', '.join(undetermined)}."
                    ),
                    resolution="Ensure the assessment role has bedrock-agentcore:GetAgentRuntime permission.",
                    reference="https://docs.aws.amazon.com/bedrock-agentcore/latest/devguide/runtime-oauth.html",
                    severity="Low",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-66"],
                )
            )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


def check_agent_financial_transaction_thresholds(inventory) -> Dict[str, Any]:
    """
    FS-67 — Report whether Lambda functions that look like agent action groups
    carry environment variables suggesting a transaction-value threshold.

    Evidence collected: Lambda function names matched against the keyword list
    below, and the NAMES of their environment variables. Variable values are
    never read.

    This is a configuration HINT, not enforcement. Deliberately NOT asserted:
      - that a matched function performs financial transactions,
      - that any threshold is enforced anywhere in code,
      - that a configured value is safe or appropriate,
      - that an AgentCore policy rule caps transaction amounts.
    A threshold implemented in code or in a policy rule is invisible here, and
    conversely an unrelated variable such as MAX_RETRIES or LIMIT=0 satisfies
    the heuristic. Both directions are false signals.

    Behavioral dependency: this check's scope is determined by resource NAMING.
    Changing the keyword list, or renaming customer functions, changes which
    resources are assessed. The assessment excludes its own Lambda functions,
    which would otherwise self-report via the "finserv" and "agent" keywords.

    COMPLIANCE_PLACEHOLDER: [SR 11-7, MAS TRM 9.1, FFIEC CAT, PCI-DSS]
    """
    check_name = "Agent Financial Transaction Value Thresholds Check"
    heuristic_note = (
        "Name-and-variable-name matching is a heuristic prompt for manual "
        "verification, not evidence that a limit is enforced."
    )
    findings = _empty_findings(check_name)
    try:
        functions = require(inventory, "lambda_functions")

        # Scope is name-driven; see the docstring's behavioral-dependency note.
        action_group_lambdas = [
            f
            for f in functions
            if any(
                kw in f["FunctionName"].lower()
                for kw in [
                    "agent",
                    "action",
                    "tool",
                    "bedrock",
                    "finserv",
                    "transaction",
                ]
            )
            and not _is_assessment_own_lambda(f["FunctionName"])
        ]

        if not action_group_lambdas:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-67",
                    finding_name="No Agent Action-Group Lambda Functions Found",
                    finding_details=(
                        "No Lambda functions matching agent action-group naming patterns found. "
                        "If agents perform financial transactions, verify transaction-value limits "
                        "are enforced in the action-group implementation."
                    ),
                    resolution=(
                        "1. Implement transaction-value threshold checks in all agent action-group "
                        "Lambda functions that initiate financial operations.\n"
                        "2. Use AgentCore Policy Engine to enforce maximum transaction amounts as "
                        "a policy constraint on tool calls.\n"
                        "3. Reject or escalate to human review any transaction exceeding defined limits."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_GatewayPolicyEngineConfiguration.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-67"],
                )
            )
        else:
            # Advisory: check for environment variables indicating threshold configuration
            lambdas_without_threshold_config = [
                f["FunctionName"]
                for f in action_group_lambdas
                if not any(
                    "threshold" in k.lower()
                    or "limit" in k.lower()
                    or "max" in k.lower()
                    for k in f.get("Environment", {}).get("Variables", {}).keys()
                )
            ]

            if lambdas_without_threshold_config:
                findings["status"] = "WARN"
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-67",
                        finding_name="Agent Action-Group Lambdas May Lack Transaction Thresholds",
                        finding_details=(
                            "The following agent action-group Lambda functions have no environment "
                            "variables whose names suggest transaction-value threshold configuration "
                            "(this is a best-effort heuristic — a threshold enforced in code or in an "
                            "AgentCore Policy Engine rule would not be detected here, so treat this as "
                            "a prompt for manual verification rather than a definitive gap). "
                            "Without explicit limits, agents could initiate unbounded financial transactions:\n"
                            + "\n".join(
                                f"- {n}" for n in lambdas_without_threshold_config[:10]
                            )
                        ),
                        resolution=(
                            "1. Add transaction-value threshold environment variables (e.g., MAX_TRANSACTION_AMOUNT) "
                            "to each agent action-group Lambda.\n"
                            "2. Implement threshold enforcement logic in the Lambda handler.\n"
                            "3. Configure AgentCore Policy Engine rules to cap financial transaction amounts.\n"
                            "4. Route transactions exceeding thresholds to a human-in-the-loop approval step."
                        ),
                        reference="https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_GatewayPolicyEngineConfiguration.html",
                        severity="High",
                        status="Failed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-67"],
                    )
                )
            else:
                findings["csv_data"].append(
                    create_finding(
                        check_id="FS-67",
                        finding_name="Agent Action-Group Lambdas Have Threshold-Named Variables",
                        finding_details=(
                            f"Found {len(action_group_lambdas)} agent action-group Lambda(s) each "
                            "carrying at least one environment variable whose NAME contains "
                            "threshold, limit, or max. Variable values were not read, so this does "
                            "not show that a transaction limit exists or is enforced — an "
                            "unrelated variable such as MAX_RETRIES, or a LIMIT of 0, satisfies "
                            f"this heuristic. {heuristic_note}"
                        ),
                        resolution=(
                            "Confirm each variable actually caps transaction value, that the "
                            "handler enforces it, and that the value suits your risk tolerance."
                        ),
                        reference="https://docs.aws.amazon.com/bedrock-agentcore-control/latest/APIReference/API_GatewayPolicyEngineConfiguration.html",
                        severity="High",
                        status="Passed",
                        compliance_frameworks=COMPLIANCE_MAP["FS-67"],
                    )
                )
    except Exception as e:
        return _error_findings(check_name, e)
    return findings


# Default body-inspection window AWS WAF applies before oversize handling kicks
# in. For CloudFront/API Gateway/Cognito/App Runner/Verified Access the default
# is 16 KB (raisable to 64 KB via the web ACL AssociationConfig); for ALB/AppSync
# it is a fixed 8 KB. A GT/GE SizeConstraint above this window can only ever fire
# if the rule's OversizeHandling is MATCH. See:
# https://docs.aws.amazon.com/waf/latest/developerguide/waf-oversize-request-components.html
_WAF_DEFAULT_BODY_INSPECTION_LIMIT = 16384

# JSON-Schema keywords that actually bound request-body SIZE. A request validator
# only enforces a size cap when its model schema carries one of these — merely
# enabling validateRequestBody does NOT cap payload size (it validates the schema
# / required params only; the REST hard limit is a fixed, non-configurable 10 MB).
_SCHEMA_SIZE_KEYWORDS = ('"maxLength"', '"maxItems"', '"maxProperties"')


def _waf_statement_has_firing_body_size_constraint(
    stmt: Any, inspection_limit: int = _WAF_DEFAULT_BODY_INSPECTION_LIMIT
) -> bool:
    """True if a WAF rule Statement contains a SizeConstraintStatement on the
    request Body/JsonBody that can actually fire.

    Recurses into And/Or/Not combinators. A GT/GE size threshold above the body
    inspection window cannot fire unless OversizeHandling is MATCH, so such a rule
    is NOT credited as a working body-size control (the documented WAF limitation).
    """
    if not isinstance(stmt, dict):
        return False
    sc = stmt.get("SizeConstraintStatement")
    if isinstance(sc, dict):
        ftm = sc.get("FieldToMatch", {}) or {}
        body = ftm.get("Body")
        json_body = ftm.get("JsonBody")
        target = body if isinstance(body, dict) else json_body
        if isinstance(target, dict):
            comparison = sc.get("ComparisonOperator", "")
            size = sc.get("Size", 0) or 0
            oversize = target.get("OversizeHandling")
            # A "block if body > N" rule with N beyond the inspection window only
            # fires when oversize content is treated as a match.
            if (
                comparison in ("GT", "GE")
                and size > inspection_limit
                and oversize != "MATCH"
            ):
                return False
            return True
    for combinator in ("AndStatement", "OrStatement"):
        sub = stmt.get(combinator)
        if isinstance(sub, dict):
            for inner in sub.get("Statements", []) or []:
                if _waf_statement_has_firing_body_size_constraint(
                    inner, inspection_limit
                ):
                    return True
    not_stmt = stmt.get("NotStatement")
    if isinstance(not_stmt, dict):
        if _waf_statement_has_firing_body_size_constraint(
            not_stmt.get("Statement"), inspection_limit
        ):
            return True
    return False


def _api_has_body_size_validator(apigw, api_id: str) -> bool:
    """True only if a REST API has a request validator that validates the body
    AND at least one model whose schema bounds body size (maxLength/maxItems/
    maxProperties). Validator presence alone is NOT sufficient — it does not cap
    payload size (the bug FS-68 previously had)."""
    validators = apigw.get_request_validators(restApiId=api_id).get("items", [])
    if not any(v.get("validateRequestBody") for v in validators):
        return False
    for model in _paginate(apigw, "get_models", "items", restApiId=api_id):
        schema = model.get("schema", "") or ""
        if any(tok in schema for tok in _SCHEMA_SIZE_KEYWORDS):
            return True
    return False


def check_api_gateway_request_body_size_limits(inventory) -> Dict[str, Any]:
    """
    FS-68 — Verify API Gateway REST APIs fronting GenAI endpoints actually enforce
    a maximum input-payload size (to blunt token-exhaustion via oversized prompts).

    Important correctness note: an API Gateway request validator does NOT cap body
    size — it validates required params + a JSON-Schema model, and the REST payload
    limit is a fixed, non-configurable 10 MB. A real size cap requires either (a) a
    validator model with a maxLength/maxItems/maxProperties bound, or (b) a WAF
    SizeConstraintStatement on the request Body that can actually fire within WAF's
    body-inspection window (default 16 KB for API Gateway). This check credits only
    those evidenced controls — validator presence alone is not a pass.
    COMPLIANCE_PLACEHOLDER: [FFIEC CAT, DORA Art.6, PCI-DSS, OWASP LLM10]
    """
    findings = _empty_findings("API Gateway Request Body Size Limits Check")
    try:
        apigw = boto3.client("apigateway", config=boto3_config)

        rest_apis = _paginate(apigw, "get_rest_apis", "items")
        # require() raises if inventory is None or web_acls is _Unavailable.
        web_acl_inv = require(inventory, "web_acls")
        acls = web_acl_inv.summaries

        # Nothing-to-assess branch: no REST APIs AND no WAF ACLs means there is no
        # input-payload surface to evaluate in this region.
        if not rest_apis and not acls:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-68",
                    finding_name="API Gateway Request Body Size Limits — Not Applicable",
                    finding_details=(
                        "No API Gateway REST APIs and no regional WAF Web ACLs were found in this "
                        "region. There is no input-payload surface to assess for body-size limits."
                    ),
                    resolution=(
                        "If GenAI endpoints are fronted by API Gateway or WAF in another region, "
                        "run the assessment there. Otherwise no action is required."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-type-size-constraint-match.html",
                    severity="Informational",
                    status="N/A",
                    compliance_frameworks=COMPLIANCE_MAP["FS-68"],
                )
            )
            return findings

        # Evidence 1: REST APIs whose validator model actually bounds body size.
        apis_with_size_control = []
        for api in rest_apis:
            if _api_has_body_size_validator(apigw, api["id"]):
                apis_with_size_control.append(api.get("name", api["id"]))

        # Evidence 2: regional WAF ACLs with a body SizeConstraint that can fire.
        # detail_by_id holds get_web_acl(...)['WebACL'] or _Unavailable.
        # An _Unavailable entry re-raises its error → outer except → COULD_NOT_ASSESS.
        acls_with_size_rules = 0
        for acl in acls:
            detail = web_acl_inv.detail_by_id[acl["Id"]]
            if isinstance(detail, _Unavailable):
                raise detail.error
            rules = detail.get("Rules", [])
            if any(
                _waf_statement_has_firing_body_size_constraint(r.get("Statement", {}))
                for r in rules
            ):
                acls_with_size_rules += 1

        has_size_control = bool(apis_with_size_control) or acls_with_size_rules > 0

        if has_size_control:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-68",
                    finding_name="API Gateway Request Body Size Limits Configured",
                    finding_details=(
                        f"Found {len(rest_apis)} REST API(s) "
                        f"({len(apis_with_size_control)} with a body-size-bounding validator model) "
                        f"and {acls_with_size_rules} WAF ACL(s) with a firing body-size constraint. "
                        "Verify the WAF ACL(s) are associated with the GenAI-facing API stages, "
                        "since this check does not confirm resource association."
                    ),
                    resolution="No action required (verify WAF/API association as noted).",
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/waf-rule-statement-type-size-constraint-match.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-68"],
                )
            )
        else:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-68",
                    finding_name="API Gateway Request Body Size Limits Not Enforced",
                    finding_details=(
                        f"Found {len(rest_apis)} REST API(s) and {len(acls)} regional WAF Web "
                        "ACL(s), but none enforce a maximum request-body size. Note: an API "
                        "Gateway request validator does NOT cap body size (it validates the schema "
                        "and required params; the REST limit is a fixed 10 MB), and a WAF body "
                        "SizeConstraint only inspects the first ~16 KB of the body by default. "
                        "Oversized prompts can exhaust Bedrock token quotas and inflate costs."
                    ),
                    resolution=(
                        "1. Add a maxLength (or maxItems/maxProperties) bound to the request-body "
                        "JSON-Schema model used by your request validator, so oversized prompts are "
                        "rejected with a 400.\n"
                        "2. Add a WAF SizeConstraintStatement on the request Body sized within WAF's "
                        "body-inspection window (default 16 KB; raise via the web ACL "
                        "AssociationConfig, or set OversizeHandling=MATCH to block bodies beyond the "
                        "window), and associate the ACL with the API stage.\n"
                        "3. Set the max_tokens parameter in Bedrock API calls to cap output length.\n"
                        "4. Implement client-side token counting before submitting requests."
                    ),
                    reference="https://docs.aws.amazon.com/waf/latest/developerguide/waf-oversize-request-components.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-68"],
                )
            )
    except Exception as e:
        return _error_findings("API Gateway Request Body Size Limits Check", e)
    return findings


def check_prompt_input_validation_function(inventory) -> Dict[str, Any]:
    """
    FS-69 — Check for a Lambda function or API Gateway request validator that
    sanitizes user prompt input (strips special characters, enforces expected
    format, rejects oversized inputs) before forwarding to Bedrock.
    COMPLIANCE_PLACEHOLDER: [OWASP LLM01, FFIEC CAT, NYDFS 500.06]
    """
    findings = _empty_findings("Prompt Input Validation Function Check")
    try:
        functions = require(inventory, "lambda_functions")

        # Look for Lambda functions with input validation / sanitization naming patterns
        VALIDATION_KEYWORDS = [
            "sanitiz",
            "validat",
            "input",
            "preprocess",
            "pre-process",
            "filter",
            "clean",
            "prompt-guard",
            "promptguard",
        ]
        validation_lambdas = [
            f["FunctionName"]
            for f in functions
            if any(kw in f["FunctionName"].lower() for kw in VALIDATION_KEYWORDS)
        ]

        if not validation_lambdas:
            findings["status"] = "WARN"
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-69",
                    finding_name="No Prompt Input Validation Function Found",
                    finding_details=(
                        "No Lambda functions matching input validation or sanitization naming "
                        "patterns were found. Without explicit prompt input validation, malicious "
                        "inputs (special characters, oversized payloads, injection sequences) may "
                        "reach Bedrock unfiltered, bypassing WAF-level controls."
                    ),
                    resolution=(
                        "1. Implement a Lambda authorizer or pre-processing function that:\n"
                        "   - Strips or escapes special characters from user input.\n"
                        "   - Validates input against an expected format (e.g., regex allowlist).\n"
                        "   - Rejects inputs exceeding maximum token/character limits.\n"
                        "   - Logs rejected inputs for security monitoring.\n"
                        "2. Use parameterized prompt templates instead of string concatenation.\n"
                        "3. Apply Bedrock Guardrails PROMPT_ATTACK filter as a complementary control.\n"
                        "4. Reference: AWS Prompt Injection Security guidance."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-injection.html",
                    severity="Medium",
                    status="Failed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-69"],
                )
            )
        else:
            findings["csv_data"].append(
                create_finding(
                    check_id="FS-69",
                    finding_name="Prompt Input Validation Functions Present",
                    finding_details=(
                        f"Found {len(validation_lambdas)} Lambda function(s) with input "
                        f"validation/sanitization naming patterns: "
                        f"{', '.join(validation_lambdas[:5])}."
                    ),
                    resolution=(
                        "Review these functions to confirm they cover: special-character stripping, "
                        "format validation, size limits, and injection-sequence detection."
                    ),
                    reference="https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-injection.html",
                    severity="Medium",
                    status="Passed",
                    compliance_frameworks=COMPLIANCE_MAP["FS-69"],
                )
            )
    except Exception as e:
        return _error_findings("Prompt Input Validation Function Check", e)
    return findings


# ===========================================================================
# REPORT GENERATION & LAMBDA HANDLER
# ===========================================================================


def generate_csv_report(findings: List[Dict[str, Any]]) -> str:
    """Generate CSV report from all security check findings."""
    csv_buffer = StringIO()
    fieldnames = [
        "Check_ID",
        "Finding",
        "Finding_Details",
        "Resolution",
        "Reference",
        "Severity",
        "Status",
        "Region",
        "Compliance_Frameworks",
    ]
    writer = csv.DictWriter(csv_buffer, fieldnames=fieldnames)
    writer.writeheader()
    for finding in findings:
        for row in finding.get("csv_data", []):
            writer.writerow(row)
    return csv_buffer.getvalue()


def _normalized_target_regions(value: str) -> List[str]:
    """Parse the CloudFormation TargetRegions parameter value."""
    value = (value or "").strip()
    if not value:
        return []
    if value.lower() == "all":
        raise ValueError(
            "TARGET_REGIONS no longer accepts 'all'; leave it empty to scan the "
            "deployment region or provide an explicit region list"
        )
    return [region.strip() for region in re.split(r"[,\s]+", value) if region.strip()]


def _get_region_scopes(event: Dict[str, Any]) -> List[str]:
    """Return resolved target regions without assuming a fixed deployment region."""
    target_regions = event.get("TargetRegions")
    if isinstance(target_regions, list):
        regions = [
            str(region).strip() for region in target_regions if str(region).strip()
        ]
        if regions:
            return regions

    regions = _normalized_target_regions(os.environ.get("TARGET_REGIONS", ""))
    if regions:
        return regions

    fallback_region = event.get("Region") or ""
    return [fallback_region] if fallback_region else []


def _probe_regional_resource_list(probe_label: str, probe_func) -> Optional[bool]:
    """Return True for resources, False for a successful empty list, None if unknown."""
    try:
        result = probe_func()
        return bool(result) if isinstance(result, list) else None
    except (EndpointConnectionError, ParamValidationError):
        logger.info("%s API is not available in this region", probe_label)
        return False
    except ClientError as e:
        error_code = e.response.get("Error", {}).get("Code", "")
        if _is_access_error(e):
            logger.warning(
                "Unable to determine Responsible AI GRC regional footprint from %s: %s",
                probe_label,
                error_code,
            )
            return None
        if error_code in {
            "UnknownOperationException",
            "ValidationException",
            "ResourceNotFoundException",
            "OptInRequired",
            "UnauthorizedOperation",
        }:
            logger.info(
                "%s API is not available in this region: %s", probe_label, error_code
            )
            return False
        logger.warning(
            "Unexpected error probing %s for Responsible AI GRC regional footprint: %s",
            probe_label,
            error_code or str(e),
        )
        return None
    except Exception as e:
        error_text = str(e)
        if "Unknown operation" in error_text or "UnknownOperation" in error_text:
            logger.info("%s API is not available in this region", probe_label)
            return False
        logger.warning(
            "Unexpected error probing %s for Responsible AI GRC regional footprint: %s",
            probe_label,
            error_text,
        )
        return None


def detect_finserv_regional_footprint(region: str) -> Optional[bool]:
    """
    Detect whether a target region has GenAI resources that justify regional
    FinServ findings.

    Returns:
        True when Bedrock, AgentCore, or SageMaker resources exist
        False when EVERY probe either succeeds with an empty result or is not
            available in this region (i.e. no probe is indeterminate)
        None when at least one probe's result is indeterminate (permissions or
            unexpected errors), even if other probes succeeded empty

    A region is only ever reported as empty (False) when the full picture is
    known. An earlier revision returned False as soon as ANY probe succeeded
    empty, even when another probe in the same loop was indeterminate — so an
    AccessDenied on, say, SageMaker while Bedrock Guardrails happened to be
    empty produced a confident "no resources" verdict from a partially unknown
    picture. Downstream, that would emit an FS-00 "no regional resources
    found" row — a false claim. `None` therefore takes priority over any
    confirmed-empty probe result whenever at least one probe could not be
    resolved, matching the contract stated above.
    """
    bedrock = boto3.client("bedrock", config=boto3_config, region_name=region)
    bedrock_agent = boto3.client(
        "bedrock-agent", config=boto3_config, region_name=region
    )
    agentcore = boto3.client(
        "bedrock-agentcore-control", config=boto3_config, region_name=region
    )
    sagemaker = boto3.client("sagemaker", config=boto3_config, region_name=region)

    probes = [
        (
            "Bedrock Guardrails",
            lambda: bedrock.list_guardrails(maxResults=1).get("guardrails", []),
        ),
        (
            "Bedrock Agents",
            lambda: bedrock_agent.list_agents(maxResults=1).get("agentSummaries", []),
        ),
        (
            "Bedrock Knowledge Bases",
            lambda: bedrock_agent.list_knowledge_bases(maxResults=1).get(
                "knowledgeBaseSummaries", []
            ),
        ),
        (
            "AgentCore Runtimes",
            lambda: agentcore.list_agent_runtimes(maxResults=1).get(
                "agentRuntimes", []
            ),
        ),
        (
            "SageMaker Endpoints",
            lambda: sagemaker.list_endpoints(MaxResults=1).get("Endpoints", []),
        ),
        (
            "SageMaker Models",
            lambda: sagemaker.list_models(MaxResults=1).get("Models", []),
        ),
        (
            "SageMaker Feature Groups",
            lambda: sagemaker.list_feature_groups(MaxResults=1).get(
                "FeatureGroupSummaries", []
            ),
        ),
    ]

    indeterminate = False
    for probe_label, probe_func in probes:
        probe_result = _probe_regional_resource_list(probe_label, probe_func)
        if probe_result is True:
            return True
        if probe_result is None:
            indeterminate = True

    # False is only correct when every probe was resolved (empty or N/A in
    # this region) — a mix of "confirmed empty" and "indeterminate" must not
    # collapse to False, since that would hide a real footprint that an
    # unresolved probe could not rule out.
    return None if indeterminate else False


def _partition_regions_by_finserv_footprint(
    regions: List[str],
) -> "tuple[List[str], List[str]]":
    """Split target regions into regions to assess and regions that are N/A."""
    assessable_regions = []
    empty_regions = []
    for region in regions:
        footprint_found = detect_finserv_regional_footprint(region)
        if footprint_found is False:
            empty_regions.append(region)
        else:
            # Unknown footprint keeps the region in scope so access/API problems do
            # not hide potentially real risks.
            assessable_regions.append(region)
    return assessable_regions, empty_regions


def _stamp_unscoped_findings_global(findings: List[Dict[str, Any]]) -> None:
    """Label unscoped evidence as global instead of claiming regional provenance."""
    for finding in findings:
        for row in finding.get("csv_data", []):
            if not row.get("Region"):
                row["Region"] = GLOBAL_REGION_LABEL


def _stamp_regions(findings: List[Dict[str, Any]], regions: List[str]) -> None:
    """Compatibility wrapper that no longer clones evidence across regions.

    The assessment executes its checks once using one inventory snapshot. A
    missing Region therefore means the evidence has no target-region
    provenance. Copying that row into every target region would misattribute
    the evidence, so it is emitted once as Global instead.
    """
    _stamp_unscoped_findings_global(findings)


def _append_no_resource_region_findings(
    findings: List[Dict[str, Any]], regions: List[str]
) -> None:
    """Append one informational N/A finding for each region without GenAI resources."""
    if not regions:
        return
    findings.append(
        {
            "check_name": "Responsible AI GRC Regional Resource Scope",
            "status": "PASS",
            "details": "No regional GenAI resources found",
            "csv_data": [
                _no_regional_genai_resources_row(region) for region in regions if region
            ],
        }
    )


def _apply_region_scope(findings: List[Dict[str, Any]], regions: List[str]) -> None:
    """Preserve unscoped rows globally and emit N/A rows for empty regions."""
    _stamp_unscoped_findings_global(findings)
    if not regions:
        return

    _, empty_regions = _partition_regions_by_finserv_footprint(regions)
    _append_no_resource_region_findings(findings, empty_regions)


def write_to_s3(execution_id: str, csv_content: str, bucket_name: str) -> str:
    """Write CSV report to S3 bucket.

    Writes a single object under the responsible_ai_grc_security_report
    prefix. This is the only prefix the assessment writes: the legacy
    finserv_security_report prefix and the additive
    responsible_ai_gov_security_report alias (Phase 2 Stage 2b) have both been
    retired in favor of this one name. Archived reports written before this
    change keep their original filenames; they are not rewritten.
    """
    s3_client = boto3.client("s3", config=boto3_config)
    file_name = f"responsible_ai_grc_security_report_{execution_id}.csv"
    s3_client.put_object(
        Bucket=bucket_name, Key=file_name, Body=csv_content, ContentType="text/csv"
    )

    return f"https://{bucket_name}.s3.amazonaws.com/{file_name}"


# ---------------------------------------------------------------------------
# Inventory collector (REQ-1, REQ-2, REQ-3, REQ-4, REQ-7)
# ---------------------------------------------------------------------------


def _safe_collect_lambda_functions():
    """Collect all Lambda functions via list_functions (fully paginated).
    Returns a list on success, or _Unavailable(exc) on any failure."""
    try:
        client = boto3.client("lambda", config=boto3_config)
        return _paginate(client, "list_functions", "Functions")
    except Exception as e:
        logger.warning(
            "inventory:lambda_functions collection failed: %s", type(e).__name__
        )
        return _Unavailable(e)


def _safe_collect_guardrails():
    """Collect Bedrock guardrail summaries and per-guardrail DRAFT detail.
    A single-guardrail detail failure is recorded as _Unavailable for that id
    only — it does NOT abort the whole guardrail inventory."""
    try:
        client = boto3.client("bedrock", config=boto3_config)
        summaries = _paginate(client, "list_guardrails", "guardrails")
        detail_by_id: dict = {}
        for g in summaries:
            gid = g["id"]
            try:
                detail_by_id[gid] = client.get_guardrail(
                    guardrailIdentifier=gid, guardrailVersion="DRAFT"
                )
            except Exception as e:
                logger.warning(
                    "inventory:guardrails detail for %s failed: %s",
                    gid,
                    type(e).__name__,
                )
                detail_by_id[gid] = _Unavailable(e)
        return GuardrailInventory(summaries=summaries, detail_by_id=detail_by_id)
    except Exception as e:
        logger.warning("inventory:guardrails collection failed: %s", type(e).__name__)
        return _Unavailable(e)


def _safe_collect_knowledge_bases():
    """Collect Bedrock Knowledge Base summaries, per-KB data-source summaries,
    and per-data-source detail.  Per-KB and per-data-source failures are
    recorded as _Unavailable without aborting the rest of the collection."""
    try:
        client = boto3.client("bedrock-agent", config=boto3_config)
        summaries = _paginate(client, "list_knowledge_bases", "knowledgeBaseSummaries")
        data_sources_by_kb: dict = {}
        data_source_detail: dict = {}
        for kb in summaries:
            kb_id = kb["knowledgeBaseId"]
            try:
                ds_summaries = _paginate(
                    client,
                    "list_data_sources",
                    "dataSourceSummaries",
                    knowledgeBaseId=kb_id,
                )
                data_sources_by_kb[kb_id] = ds_summaries
                for ds in ds_summaries:
                    ds_id = ds["dataSourceId"]
                    try:
                        data_source_detail[(kb_id, ds_id)] = client.get_data_source(
                            knowledgeBaseId=kb_id, dataSourceId=ds_id
                        )
                    except Exception as e:
                        logger.warning(
                            "inventory:knowledge_bases data_source detail (%s, %s) failed: %s",
                            kb_id,
                            ds_id,
                            type(e).__name__,
                        )
                        data_source_detail[(kb_id, ds_id)] = _Unavailable(e)
            except Exception as e:
                logger.warning(
                    "inventory:knowledge_bases data_sources for KB %s failed: %s",
                    kb_id,
                    type(e).__name__,
                )
                data_sources_by_kb[kb_id] = _Unavailable(e)
        return KbInventory(
            summaries=summaries,
            data_sources_by_kb=data_sources_by_kb,
            data_source_detail=data_source_detail,
        )
    except Exception as e:
        logger.warning(
            "inventory:knowledge_bases collection failed: %s", type(e).__name__
        )
        return _Unavailable(e)


def _safe_collect_buckets():
    """Collect the full account S3 bucket list with explicit ContinuationToken
    pagination.  MaxBuckets=1000 ensures pagination is always engaged so accounts
    above the 10,000-bucket quota (where unpaginated requests are rejected) succeed."""
    try:
        client = boto3.client("s3", config=boto3_config)
        return _paginate(
            client,
            "list_buckets",
            "Buckets",
            token=("ContinuationToken", "ContinuationToken"),
            MaxBuckets=1000,
        )
    except Exception as e:
        logger.warning("inventory:buckets collection failed: %s", type(e).__name__)
        return _Unavailable(e)


def _safe_collect_web_acls():
    """Collect WAFv2 REGIONAL Web ACL summaries and per-ACL detail.  Uses
    explicit NextMarker/NextMarker pagination (WAFv2 input ≠ Lambda Marker).
    Per-ACL detail failures are recorded as _Unavailable for that id only."""
    try:
        client = boto3.client("wafv2", config=boto3_config)
        summaries = _paginate(
            client,
            "list_web_acls",
            "WebACLs",
            token=("NextMarker", "NextMarker"),
            Scope="REGIONAL",
        )
        detail_by_id: dict = {}
        for acl in summaries:
            acl_id = acl["Id"]
            try:
                # Store the WebACL dict directly (response["WebACL"]), not the
                # full envelope, so consuming checks can do detail.get("Rules")
                # without an extra ["WebACL"] indirection (matches design §3).
                resp = client.get_web_acl(Name=acl["Name"], Scope="REGIONAL", Id=acl_id)
                detail_by_id[acl_id] = resp["WebACL"]
            except Exception as e:
                logger.warning(
                    "inventory:web_acls detail for %s failed: %s",
                    acl_id,
                    type(e).__name__,
                )
                detail_by_id[acl_id] = _Unavailable(e)
        return WebAclInventory(summaries=summaries, detail_by_id=detail_by_id)
    except Exception as e:
        logger.warning("inventory:web_acls collection failed: %s", type(e).__name__)
        return _Unavailable(e)


def collect_resource_inventory() -> ResourceInventory:
    """Collect each shared inventory at most once per invocation.

    Each inventory is isolated: a failure yields an ``_Unavailable`` sentinel
    for that field without aborting the others (REQ-4, INV-5).  All five
    inventories are always collected because the current registry always
    consumes all five (design DD-7).

    All clients use ``boto3.client(service, config=boto3_config)`` — no
    ``region_name`` or ``endpoint_url`` — so this inventory has no reliable
    target-region provenance. Rows derived from it are therefore labeled
    ``Global`` rather than copied into each target region."""
    return ResourceInventory(
        lambda_functions=_safe_collect_lambda_functions(),
        guardrails=_safe_collect_guardrails(),
        knowledge_bases=_safe_collect_knowledge_bases(),
        buckets=_safe_collect_buckets(),
        web_acls=_safe_collect_web_acls(),
    )


def build_finserv_checks(permission_cache, inventory=None):
    """
    Single source of truth: ordered (check_id, zero-arg callable) registry of
    all FinServ checks, in execution order (FS-01 → FS-69, skipping the ids
    merged into upstream: FS-17/18/19/23/64). The two permission-cache checks
    are bound with functools.partial so every entry is uniformly zero-arg.

    Driving the handler from this registry lets us attach the correct Check_ID
    to a synthesized "could not assess" row when a check errors out, instead of
    silently dropping the check from the report.

    ``inventory`` is optional (defaults to ``None``) so that existing one-arg
    call sites — e.g. tests/test_severity_register.py — continue to work
    without modification (DD-2b).  ``lambda_handler`` always passes a real
    ``ResourceInventory``; consuming checks will be bound to it in Wave 3.
    FS-21 and FS-46 (S3-inventory consumers) are bound to ``inventory`` here.
    Guardrail consumers (FS-27a, 28, 36, 38, 45, 47, 50, 51, 59) are now
    bound to ``inventory`` as well (Task 7).
    """
    return [
        # --- Category 1: Unbounded Consumption ---
        ("FS-01", functools.partial(check_waf_shield_on_bedrock_endpoints, inventory)),
        ("FS-02", check_api_gateway_rate_limiting),
        ("FS-03", check_bedrock_token_quotas),
        ("FS-04", check_cost_anomaly_detection),
        ("FS-05", check_cloudwatch_token_alarms),
        ("FS-06", check_aws_budgets_for_aiml),
        # --- Category 2: Excessive Agency ---
        (
            "FS-07",
            functools.partial(check_bedrock_agent_action_boundaries, permission_cache),
        ),
        ("FS-08", check_agentcore_runtime_inbound_authorizer),
        ("FS-09", functools.partial(check_agent_transaction_limits, inventory)),
        ("FS-10", check_human_in_the_loop_for_high_risk_actions),
        ("FS-11", check_agent_rate_alarms),
        # --- Category 3: Supply Chain Vulnerabilities ---
        ("FS-12", check_scp_model_access_restrictions),
        ("FS-13", check_model_inventory_tagging),
        ("FS-14", check_model_onboarding_governance),
        ("FS-15", check_bedrock_model_evaluation_adversarial),
        ("FS-16", check_ecr_image_scanning),
        # --- Category 4: Training Data & Model Poisoning ---
        ("FS-20", check_feature_store_rollback_capability),
        ("FS-21", functools.partial(check_training_data_s3_versioning, inventory)),
        # --- Category 5: Vector & Embedding Weaknesses ---
        (
            "FS-22",
            functools.partial(
                check_knowledge_base_iam_least_privilege, permission_cache
            ),
        ),
        (
            "FS-24",
            functools.partial(check_knowledge_base_metadata_filtering, inventory),
        ),
        ("FS-25", check_opensearch_serverless_encryption),
        ("FS-26", check_knowledge_base_vpc_access),
        # --- Category 6: Non-Compliant Output ---
        # FS-27 is split into two checks: contextual grounding (threshold-based) and
        # Automated Reasoning policies (formal-verification, GA August 2025). Both
        # use the FS-27 check_id so they appear together in the CSV report.
        ("FS-27", functools.partial(check_guardrail_contextual_grounding, inventory)),
        ("FS-27", check_automated_reasoning_policies),
        (
            "FS-28",
            functools.partial(check_guardrail_denied_topics_financial, inventory),
        ),
        ("FS-29", check_compliance_disclaimer_in_outputs),
        ("FS-30", check_bedrock_evaluation_compliance_datasets),
        # --- Category 7: Misinformation ---
        ("FS-31", functools.partial(check_knowledge_base_data_source_sync, inventory)),
        ("FS-32", check_source_attribution_in_guardrails),
        (
            "FS-33",
            functools.partial(check_knowledge_base_integrity_monitoring, inventory),
        ),
        ("FS-34", check_fm_version_currency),
        # --- Category 8: Abusive or Harmful Output ---
        ("FS-35", check_fmeval_harmful_content),
        ("FS-36", functools.partial(check_guardrail_content_filters, inventory)),
        ("FS-37", check_user_feedback_mechanism),
        ("FS-38", functools.partial(check_guardrail_word_filters, inventory)),
        # --- Category 9: Biased Output ---
        ("FS-39", check_sagemaker_clarify_bias),
        ("FS-40", check_bedrock_evaluation_bias_datasets),
        ("FS-41", check_sagemaker_clarify_explainability),
        ("FS-42", check_ai_service_cards_documentation),
        # --- Category 10: Sensitive Information Disclosure ---
        ("FS-43", check_cloudwatch_log_pii_masking),
        ("FS-44", check_macie_on_training_data_buckets),
        ("FS-45", functools.partial(check_guardrail_pii_filters, inventory)),
        ("FS-46", functools.partial(check_data_classification_tagging, inventory)),
        # --- Category 11: Hallucination ---
        ("FS-47", functools.partial(check_guardrail_grounding_threshold, inventory)),
        ("FS-48", functools.partial(check_rag_knowledge_base_configured, inventory)),
        ("FS-49", check_hallucination_disclaimer_advisory),
        ("FS-50", functools.partial(check_guardrail_relevance_grounding, inventory)),
        # --- Category 12: Prompt Injection ---
        (
            "FS-51",
            functools.partial(check_prompt_injection_input_validation, inventory),
        ),
        ("FS-52", functools.partial(check_bedrock_sdk_version_currency, inventory)),
        ("FS-53", functools.partial(check_waf_sql_injection_rules, inventory)),
        ("FS-54", check_penetration_testing_evidence),
        # --- Category 13: Improper Output Handling ---
        ("FS-55", functools.partial(check_output_validation_lambda, inventory)),
        ("FS-56", functools.partial(check_xss_prevention_waf, inventory)),
        ("FS-57", check_output_encoding_advisory),
        ("FS-58", functools.partial(check_output_schema_validation, inventory)),
        # --- Category 14: Off-Topic & Inappropriate Output ---
        ("FS-59", functools.partial(check_guardrail_topic_allowlist, inventory)),
        ("FS-60", check_contextual_grounding_for_offtopic),
        # --- Category 15: Out-of-Date Training Data ---
        ("FS-61", functools.partial(check_knowledge_base_sync_schedule, inventory)),
        ("FS-62", check_data_currency_disclaimer_advisory),
        ("FS-63", check_foundation_model_lifecycle_policy),
        # --- Material Gap Checks (FS-65 to FS-69) ---
        (
            "FS-65",
            functools.partial(check_kb_datasource_s3_event_notifications, inventory),
        ),
        ("FS-66", check_agentcore_end_user_identity_propagation),
        (
            "FS-67",
            functools.partial(check_agent_financial_transaction_thresholds, inventory),
        ),
        (
            "FS-68",
            functools.partial(check_api_gateway_request_body_size_limits, inventory),
        ),
        ("FS-69", functools.partial(check_prompt_input_validation_function, inventory)),
    ]


def lambda_handler(event, context):
    """Main Lambda handler — runs all FinServ security checks.

    The registry in build_finserv_checks() contains 65 entries (64 standalone
    FS checks plus the new FS-27 Automated Reasoning Policies check). Two
    entries share the FS-27 check_id (contextual grounding + ARC policies),
    both contributing rows to the report under the same check namespace.
    """
    logger.info("Starting Responsible AI GRC security assessment")
    all_findings = []
    region_scopes = _get_region_scopes(event)

    execution_id = event.get("Execution", {}).get("Name", "local-test")
    permission_cache = get_permissions_cache(execution_id)
    inventory = collect_resource_inventory()  # NEW: once per invocation

    # Run every check from the registry. If a check produces no rows for ANY
    # reason (an ERROR envelope, or an unexpected empty non-error result),
    # synthesize a visible "could not assess" row (keyed by its Check_ID) so the
    # gap surfaces in the report instead of the check silently vanishing. The
    # guard intentionally keys off empty csv_data (not just status=="ERROR") so
    # the no-silent-drop invariant holds structurally, not by data coincidence.
    for check_id, check_fn in build_finserv_checks(permission_cache, inventory):
        result = check_fn()
        if not result.get("csv_data"):
            details = result.get("details", "") or (
                f"check returned status={result.get('status', 'UNKNOWN')!r} "
                "with no findings"
            )
            result.setdefault("csv_data", []).append(
                _could_not_assess_row(
                    check_id,
                    result.get("check_name", check_id),
                    details,
                )
            )
        all_findings.append(result)

    # Generate and upload report. Checks execute once against one inventory
    # snapshot, so unscoped evidence is labeled Global rather than cloned into
    # target regions. Confirmed-empty regions still receive a visible N/A row.
    _apply_region_scope(all_findings, region_scopes)
    csv_content = generate_csv_report(all_findings)
    bucket_name = os.environ.get("AIML_ASSESSMENT_BUCKET_NAME")
    if not bucket_name:
        raise ValueError("AIML_ASSESSMENT_BUCKET_NAME environment variable is not set")

    s3_url = write_to_s3(execution_id, csv_content, bucket_name)

    return {
        "statusCode": 200,
        "body": {
            "message": "Responsible AI GRC security assessment completed",
            "findings": all_findings,
            "report_url": s3_url,
        },
    }
