Rapid IT Health Audit

Data Pipeline Entity Relationship Diagram

SaaS Architecture

Entity Relationship Diagram

Visual representation of the core data model

erDiagram ASSET ||--o{ CONTROL : "has" CONTROL ||--o{ EVIDENCE : "requires" CONTROL ||--o{ COST_ITEM : "incurs" CONTROL ||--o{ RISK : "mitigates" ASSET { string asset_id PK string name string type string location string owner date purchase_date boolean is_critical } CONTROL { string control_id PK string name string description string standard string implementation_status date last_review_date } EVIDENCE { string evidence_id PK string control_id FK string type string file_path date collection_date string collected_by boolean is_valid } COST_ITEM { string cost_id PK string control_id FK decimal amount string currency string category date incurred_date string justification } RISK { string risk_id PK string control_id FK string description string impact string likelihood string mitigation_strategy date identified_date }

Asset

Represents IT infrastructure components (hardware, software, network devices) that need to be audited.

Fields:

  • asset_id (PK): string
  • name: string
  • type: string
  • location: string
  • owner: string
  • purchase_date: date
  • is_critical: boolean

Control

Security controls or compliance measures applied to assets to mitigate risks and meet standards.

Fields:

  • control_id (PK): string
  • name: string
  • description: string
  • standard: string
  • implementation_status: string
  • last_review_date: date

Evidence

Documentation proving that controls are properly implemented (screenshots, logs, config files).

Fields:

  • evidence_id (PK): string
  • control_id (FK): string
  • type: string
  • file_path: string
  • collection_date: date
  • collected_by: string
  • is_valid: boolean

CostItem

Financial aspects associated with implementing and maintaining controls.

Fields:

  • cost_id (PK): string
  • control_id (FK): string
  • amount: decimal
  • currency: string
  • category: string
  • incurred_date: date
  • justification: string

Risk

Potential threats or vulnerabilities that controls aim to mitigate.

Fields:

  • risk_id (PK): string
  • control_id (FK): string
  • description: string
  • impact: string
  • likelihood: string
  • mitigation_strategy: string
  • identified_date: date

Relationship Summary

1

Asset to Control

One-to-many relationship where each asset can have multiple controls applied to it (e.g., a server might have access controls, patch management, and monitoring controls).

2

Control to Evidence

One-to-many relationship where each control requires multiple pieces of evidence to demonstrate its proper implementation (e.g., firewall rules, access logs).

3

Control to CostItem

One-to-many relationship tracking the financial investment in each control (e.g., license costs, implementation hours, maintenance expenses).

4

Control to Risk

One-to-many relationship showing which risks each control mitigates, allowing for risk-based prioritization of control implementation.

Automated Workflow

Containerized data pipeline execution flow

  1. Container Initialization: Docker container starts with temporary read-only credentials passed as environment variables
  2. Credential Validation: Verify all supplied credentials can establish basic API connections
  3. Parallel API Harvesting: Simultaneously collect data from all connected systems using their respective APIs
  4. JSON Normalization: Transform all collected data into standardized JSON format matching our data model
  5. Database Population: Upsert normalized data into Postgres tables (Asset, Control, Evidence, CostItem, Risk)
  6. Evidence Manifest Generation: Create CSV mapping each JSON evidence file to its associated Control record
  7. Log Finalization: Write execution summary and any errors to timestamped log file
sequenceDiagram participant Docker as Docker Container participant Cloud as Cloud/SaaS APIs participant Postgres as Postgres DB Docker->>Docker: Initialize with ENV credentials Docker->>Cloud: Validate credentials par Parallel Execution Docker->>Cloud: Harvest API Data (Asset) Docker->>Cloud: Harvest API Data (Control) Docker->>Cloud: Harvest API Data (Evidence) end Docker->>Docker: Normalize JSON data Docker->>Postgres: Upsert Asset records Docker->>Postgres: Upsert Control records Docker->>Postgres: Upsert related entities Docker->>Docker: Generate evidence manifest (CSV) Docker->>Docker: Write execution logs

Compliance Data Serializers

Transformations for standards and tool integrations

OSCAL SSP JSON

Mappings from core tables to NIST SP 800-53 controls:

{
  "mappings": {
    "Control": {
      "control_id → implemented-requirements/uuid",
      "name → implemented-requirements/description",
      "standard → implemented-requirements/control-id"
    },
    "Evidence": {
      "file_path → implemented-requirements/links/href",
      "collection_date → implemented-requirements/props/value"
    }
  },
  "required_namespaces": [
    "http://csrc.nist.gov/ns/oscal/1.0",
    "http://csrc.nist.gov/ns/oscal/metaschema/1.0"
  ],
  "example": {
    "system-security-plan": {
      "uuid": "a0e48328-...",
      "implemented-requirements": [{
        "uuid": "CTL-2024-001",
        "control-id": "AC-2",
        "description": "Server Access Control"
      }]
    }
  }
}

OpenControl YAML

mappings:
  Control:
    control_id: id
    name: name
    description: narrative
  Evidence:
    file_path: documentation
    collected_by: referenced_by
    collection_date: date

namespaces:
  - opencontrol/schemas/1.0.0

example: |
  standards:
    - name: NIST-800-53
      controls:
        - id: CTL-2024-001
          name: Patch Management
          narrative: "Ensures timely..."

CSV Bundles

Vanta/Drata CSV Mappings:
Asset:
  asset_id → Device ID
  name → Asset Name
  is_critical → Critical (true/false)

Control:
  control_id → Control ID
  implementation_status → Status
  last_review_date → Last Tested

Example:
Device ID,Asset Name,Critical
ASSET-001,Web Server,true

XBRL Cost Data

Mappings:
CostItem:
  amount → xbrli:monetaryItemType
  currency → iso4217:currency
  category → audit:costCategory

Namespaces:
  - http://www.xbrl.org/2003/instance
  - http://www.xbrl.org/dtr/type/numeric

Example:
<xbrl>
  <cost:cybersecurityCost 
    contextRef="current" 
    unitRef="USD" 
    decimals="2">45000</cost:cybersecurityCost>
</xbrl>

Evidence Storage Automation

Secure S3 bucket configuration with presigned URLs for auditor access

Terraform S3 Configuration

resource "aws_s3_bucket" "evidence_store" {
  bucket = "audit-evidence-${var.account_id}"
  
  object_lock_configuration {
    object_lock_enabled = "Enabled"
  }

  lifecycle_rule {
    id      = "auto-expire"
    enabled = true
    expiration {
      days = 90
    }
  }
}

resource "aws_s3_bucket_policy" "read_only" {
  bucket = aws_s3_bucket.evidence_store.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = {"AWS": "arn:aws:iam::${var.auditor_account_id}:root"}
      Action    = ["s3:GetObject"]
      Resource  = "${aws_s3_bucket.evidence_store.arn}/*"
    }]
  })
}

Python Upload Script

import boto3
from datetime import datetime, timedelta

def upload_evidence(file_path, control_id):
    s3 = boto3.client('s3')
    bucket = 'audit-evidence-123456789012'
    key = f"{control_id}/{datetime.now().isoformat()}_{file_path.split('/')[-1]}"
    
    # Upload file with object lock retention
    s3.upload_file(file_path, bucket, key, ExtraArgs={
        'ObjectLockMode': 'GOVERNANCE',
        'ObjectLockRetainUntilDate': datetime.now() + timedelta(days=90)
    })
    
    # Generate presigned URL
    url = s3.generate_presigned_url(
        'get_object',
        Params={'Bucket': bucket, 'Key': key},
        ExpiresIn=432000  # 5 days in seconds
    )
    return url

Auditor Access Process

Auditors receive time-limited presigned URLs that:

  1. Provide read-only access to specific evidence files
  2. Automatically expire after 5 days to limit exposure
  3. Don't require AWS credentials (works through URL signature)
  4. Track which evidence was accessed via CloudTrail logs

Workflow:

  1. System generates URL during evidence collection
  2. URL gets embedded in compliance reports
  3. Auditor clicks link to verify evidence directly
  4. Access automatically revoked after expiration

Serverless Data Collection Scheduler

Automated 90-day refresh cycle with observability

Terraform Configuration

resource "aws_cloudwatch_event_rule" "quarterly_audit" {
  name                = "quarterly-audit-data-collection"
  description         = "Triggers audit data collection every 90 days"
  schedule_expression = "rate(90 days)"
}

resource "aws_iam_role" "lambda_exec" {
  name = "audit-data-collector-lambda"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action = "sts:AssumeRole"
      Effect = "Allow"
      Principal = {
        Service = "lambda.amazonaws.com"
      }
    }]
  })
}

resource "aws_iam_role_policy" "lambda_policy" {
  name = "least-privilege-audit-collector"
  role = aws_iam_role.lambda_exec.id

  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Action = [
          "logs:CreateLogGroup",
          "logs:CreateLogStream",
          "logs:PutLogEvents"
        ]
        Resource = "arn:aws:logs:*:*:*"
      },
      {
        Effect = "Allow"
        Action = [
          "cloudwatch:PutMetricData"
        ]
        Resource = "*"
      }
    ]
  })
}

resource "aws_lambda_function" "data_collector" {
  filename      = "data-collector.zip"
  function_name = "audit-data-collector"
  role          = aws_iam_role.lambda_exec.arn
  handler       = "lambda_function.lambda_handler"
  runtime       = "python3.9"
  timeout       = 900  # 15 minutes

  environment {
    variables = {
      DB_HOST     = var.database_host
      DB_PASSWORD = var.database_password
      OPENAI_KEY  = var.openai_key
    }
  }
}

resource "aws_cloudwatch_event_target" "trigger_lambda" {
  rule      = aws_cloudwatch_event_rule.quarterly_audit.name
  target_id = "TriggerLambda"
  arn       = aws_lambda_function.data_collector.arn
}

resource "aws_lambda_permission" "allow_cloudwatch" {
  statement_id  = "AllowExecutionFromCloudWatch"
  action        = "lambda:InvokeFunction"
  function_name = aws_lambda_function.data_collector.function_name
  principal     = "events.amazonaws.com"
  source_arn    = aws_cloudwatch_event_rule.quarterly_audit.arn
}

Python Lambda Function

import os
import boto3
from datetime import datetime
import psycopg2
import openai

cloudwatch = boto3.client('cloudwatch')

def lambda_handler(event, context):
    # Connect to database using env vars
    conn = psycopg2.connect(
        host=os.environ['DB_HOST'],
        database="audit",
        user="collector",
        password=os.environ['DB_PASSWORD']
    )
    
    try:
        start_time = datetime.now()
        
        # 1. Collect data from APIs
        collect_assets()
        collect_controls()
        
        # 2. Process with OpenAI for risk analysis
        analyze_risks()
        
        # 3. Publish metrics
        publish_metrics(
            duration=(datetime.now() - start_time).total_seconds(),
            assets_collected=100,  # example value
            controls_processed=50  # example value
        )
        
        return {"status": "success"}
    except Exception as e:
        publish_error_metric()
        raise e

def publish_metrics(duration, assets_collected, controls_processed):
    cloudwatch.put_metric_data(
        Namespace='AuditDataCollection',
        MetricData=[
            {
                'MetricName': 'ExecutionTime',
                'Value': duration,
                'Unit': 'Seconds'
            },
            {
                'MetricName': 'AssetsCollected',
                'Value': assets_collected,
                'Unit': 'Count'
            },
            {
                'MetricName': 'ControlsProcessed',
                'Value': controls_processed,
                'Unit': 'Count'
            }
        ]
    )

def publish_error_metric():
    cloudwatch.put_metric_data(
        Namespace='AuditDataCollection',
        MetricData=[{
            'MetricName': 'CollectionErrors',
            'Value': 1,
            'Unit': 'Count'
        }]
    )

Key CloudWatch Metrics

  1. ExecutionTime: Duration of data collection in seconds
  2. AssetsCollected: Count of IT assets inventoried
  3. ControlsProcessed: Number of security controls evaluated
  4. CollectionErrors: Count of failed executions (alarm when >0)
  5. APICallLatency: Response times from external APIs
  6. RecordsProcessed: Total database records created/updated

Control Failure Narrative Generator

Template for converting failed controls into actionable insights

Prompt Template:

Transform this failed control data into a concise risk narrative in JSON format:

1. Business Risk Summary: One sentence describing the business impact
2. Control Reference: Include the control_id
3. Actionable Fix: One practical recommendation (≤40 words)
4. Format: Strict JSON with keys summary, control_id, recommendation

Example Input:
{
  "control_name": "Server Patch Management",
  "control_id": "CTL-2024-001",
  "failure_details": "30% of servers missing critical security patches"
}

Required Output Format:
{
  "summary": "[business risk statement]",
  "control_id": "[control identifier]",
  "recommendation": "[concrete action item]"
}

Example Output:

{
  "summary": "Unpatched servers create vulnerabilities for ransomware attacks and data breaches",
  "control_id": "CTL-2024-001",
  "recommendation": "Deploy automated patching system with 72-hour SLA for critical updates"
}

Made with DeepSite LogoDeepSite - 🧬 Remix