Audit Context Building

Automate and integrate Audit Context Building into your audit workflows

Audit Context Building is a community skill for assembling comprehensive audit context from codebases, covering code flow tracing, dependency mapping, configuration extraction, access control analysis, and structured evidence collection for security and compliance audits.

What Is This?

Overview

Audit Context Building provides patterns for gathering and organizing information needed for code audits. It covers code flow tracing that maps request handling from entry points through middleware to data stores, dependency mapping that catalogs third-party libraries with version and vulnerability status, configuration extraction that collects environment variables, feature flags, and security settings, access control analysis that documents authentication and authorization patterns across endpoints, and structured evidence collection that organizes findings into audit-ready reports. The skill enables audit teams to build comprehensive context before detailed review, reducing the time spent on initial discovery and allowing reviewers to focus on substantive security analysis.

Who Should Use This

This skill serves security auditors reviewing codebases for vulnerabilities and compliance gaps, compliance teams building evidence for SOC 2 or ISO 27001 audits, and engineering leads preparing codebases for external security assessments. It is also valuable for internal red teams conducting periodic security reviews.

Why Use It?

Problems It Solves

Auditors spend significant time understanding codebase architecture before identifying issues. Dependency vulnerability status is scattered across package managers and advisory databases. Access control patterns are implemented inconsistently and documented poorly. Configuration settings affecting security are spread across multiple files and environments, making manual discovery error-prone and time-consuming.

Core Highlights

Flow tracer maps request paths from endpoints through business logic to data access. Dependency scanner catalogs packages with known vulnerability cross-references. Config collector extracts security-relevant settings from environment and configuration files. Evidence organizer structures findings into audit-ready documentation.

How to Use It?

Basic Usage

import os
import json
from pathlib import Path
from dataclasses\
  import dataclass, field

@dataclass
class AuditContext:
  endpoints: list[dict] =\
    field(default_factory=list)
  dependencies: list[dict] =\
    field(default_factory=list)
  configs: list[dict] =\
    field(default_factory=list)
  findings: list[dict] =\
    field(default_factory=list)

class ContextBuilder:
  def __init__(
    self, project_dir: str
  ):
    self.root = Path(
      project_dir)
    self.context =\
      AuditContext()

  def scan_dependencies(
    self
  ) -> None:
    pkg_file = self.root\
      / 'package.json'
    if pkg_file.exists():
      pkg = json.loads(
        pkg_file.read_text())
      deps = {
        **pkg.get(
          'dependencies', {}),
        **pkg.get(
          'devDependencies',
          {})}
      for name, version\
          in deps.items():
        self.context\
          .dependencies.append(
          {'name': name,
           'version': version,
           'type': 'npm'})

  def scan_configs(
    self
  ) -> None:
    env_file = self.root\
      / '.env.example'
    if env_file.exists():
      for line in env_file\
          .read_text()\
          .splitlines():
        if '=' in line\
            and not line\
              .startswith('#'):
          key = line.split(
            '=')[0].strip()
          self.context\
            .configs.append(
            {'key': key,
             'source':
               '.env.example'})

Real-World Examples

import ast
from pathlib import Path

def find_auth_patterns(
  project_dir: str
) -> list[dict]:
  patterns = []
  root = Path(project_dir)

  for py_file in root.rglob(
      '*.py'):
    try:
      tree = ast.parse(
        py_file.read_text())
    except SyntaxError:
      continue

    for node\
        in ast.walk(tree):
      if isinstance(node,
          ast.FunctionDef):
        decorators = [
          d.attr
          if isinstance(
            d, ast.Attribute)
          else getattr(
            d, 'id', '')
          for d in
            node.decorator_list]
        auth_decs = [
          d for d
          in decorators
          if 'auth' in
            d.lower()
          or 'login' in
            d.lower()
          or 'permission' in
            d.lower()]
        if auth_decs:
          patterns.append({
            'file': str(
              py_file),
            'function':
              node.name,
            'decorators':
              auth_decs,
            'line':
              node.lineno})
  return patterns

Advanced Tips

Cross-reference dependency versions against the National Vulnerability Database for known CVEs. Map authentication decorator usage to route definitions to identify unprotected endpoints. Generate a dependency tree showing transitive dependencies that may introduce vulnerabilities. When auditing microservice architectures, apply the same context-building process to each service independently, then consolidate findings to identify cross-service authorization gaps.

When to Use It?

Use Cases

Build audit context for a SOC 2 compliance review by cataloging access controls and configurations. Prepare a codebase for external security assessment by mapping all endpoints and their authorization requirements. Scan dependencies for known vulnerabilities before an audit.

Related Topics

Security auditing, compliance evidence, code analysis, dependency scanning, and access control review.

Important Notes

Requirements

Access to the project source code and configuration files. Package manager files for dependency analysis. Static analysis tools for code flow tracing.

Usage Recommendations

Do: scan all dependency files including lock files for precise version identification. Document environment variables that affect security behavior. Map all authentication and authorization patterns across the codebase.

Don't: rely solely on automated scanning without manual code review for logic vulnerabilities. Include actual secret values in audit context documents. Assume decorator presence means correct authorization implementation.

Limitations

Static analysis cannot detect runtime authorization bypass vulnerabilities. Dependency scanning finds known CVEs but not zero-day vulnerabilities. Configuration analysis requires access to all deployment environments which may be restricted, particularly in regulated industries where production environment access is tightly controlled.