Secure Coding Practices for AI-Assisted Federal Development

June 29, 2026 · View on GitHub

Version: 0.1.0 | Impact Level: FIPS Moderate | Scope: Single-agent, internal enterprise

Quick Reference

DomainKey Rules
InputValidate ALL external input server-side, parameterized queries only, allowlist over denylist
OutputContext-appropriate encoding, no internal details in error messages
SecretsNever in source code, use approved KMS (Vault, AWS SM, Azure KV), rotate regularly
AuthAuthenticate all endpoints, server-side authorization, framework-native session management
DependenciesPin exact versions, commit lock files, no critical/high CVEs, verify package names
ErrorsExplicit handling, structured logging, no sensitive data in logs
CryptoFIPS-validated algorithms only, no custom implementations, TLS 1.2+
ArchitectureADRs for design decisions, Design by Contract, interfaces before implementations
Change SafetyTDD (red-green-refactor), regression tests for bug fixes, idempotent operations
Size LimitsFunctions ≤50 lines, files ≤400 lines, cyclomatic complexity ≤10, params ≤5
AI BiasTest decision-making outputs for bias across protected classes; document known limitations
Model EvalEvaluate accuracy, limitations, provenance before use; document selection in ADR
AI MonitoringTrack error rates, detect model drift, monitor for prompt injection, monthly evaluation
Version ControlSemVer 2.0.0, Conventional Commits 1.0.0, automated releases, CHANGELOG maintenance

Full details in sections below. See CONTEXT-GUIDE.md for loading instructions.


Disclaimer: This playbook is informational only and is not authoritative federal policy. Each agency must tailor these practices to their specific requirements.

This document defines secure coding standards that AI agents and developers MUST follow when building software in federal environments. These practices apply to all code — whether written by a human, generated by an AI agent, or a combination of both.

Key words: "MUST", "MUST NOT", "SHOULD", "SHOULD NOT", and "MAY" are used per RFC 2119.


1. AI-Generated Code: Additional Responsibilities

AI-generated code requires the same security scrutiny as human-written code — plus additional verification steps.

1.1 Code Provenance

  • AI-generated code SHOULD be attributed at the PR level (e.g., disclosure in PR description)
  • Per-commit attribution (e.g., Co-authored-by) is OPTIONAL — federal guidance emphasizes traceability, not granular commit-level attribution
  • Developers MUST review all AI-generated code before committing — the developer assumes responsibility for all committed code regardless of who or what generated it
  • The AI agent SHOULD explain its reasoning for non-obvious implementation choices
  • AI-generated code MUST NOT be deployed to production without human review and approval
  • Projects using AI agents SHOULD document this in AGENTS.md or equivalent project documentation

1.2 Known Limitations

Developers SHOULD be aware that AI-generated code may:

  • Contain plausible-looking but incorrect logic
  • Reference APIs, libraries, or language features that do not exist or are deprecated
  • Reproduce insecure patterns from its training data
  • Lack awareness of agency-specific requirements not included in the prompt

Mitigation: Always verify AI suggestions against official documentation. Test edge cases. Run security scanners.

SSDF Mapping: PO.1.1 (Security Requirements), PW.1.1 (Design to Requirements)


2. Input Validation and Output Encoding

2.1 Input Validation Rules

All external input MUST be validated before use. External input includes: HTTP request parameters, form data, file uploads, API responses, environment variables, configuration files, command-line arguments, and database query results.

Validation approach:

1. Define expected format (type, length, range, pattern)
2. Reject anything that does not match — fail closed
3. Use allowlists, not denylists
4. Validate on the server/backend side — never trust client validation alone

Specific requirements:

Input TypeValidation Required
String inputMax length, character allowlist, encoding
Numeric inputRange check, type coercion safety
File uploadsExtension allowlist, MIME type check, size limit, content scanning
Email addressesRFC 5322 format validation
URLsProtocol allowlist (https only), domain allowlist
File pathsPath traversal prevention (resolve, then verify prefix)
SQL parametersParameterized queries only — never string concatenation
Shell commandsAvoid when possible; if necessary, use library APIs not shell strings

2.2 Output Encoding

Output MUST be encoded based on context:

ContextEncoding
HTML bodyHTML entity encoding
HTML attributesAttribute encoding (quote-safe)
JavaScriptJavaScript string escaping
URLsURL/percent encoding
SQLParameterized queries (not encoding)
ShellAvoid; use APIs. If unavoidable, shell-escape all arguments
JSONProper serialization — never string concatenation
Log filesSanitize newlines and control characters

Control Mapping: SI-10 (Input Validation), SI-15 (Information Output Filtering)


3. Authentication and Authorization in Code

3.1 Authentication

  • MUST use agency-approved identity providers (e.g., Login.gov, agency SSO, PIV/CAC)
  • MUST NOT implement custom password storage unless specifically authorized — use established libraries
  • MUST enforce multi-factor authentication (MFA) for all privileged operations
  • MUST NOT store credentials in source code, configuration files, or environment variables committed to version control
  • SHOULD use short-lived tokens over long-lived credentials

3.2 Authorization

  • MUST enforce authorization checks on every protected resource access — server-side
  • MUST use role-based access control (RBAC) or attribute-based access control (ABAC)
  • MUST deny by default — explicitly grant access, do not explicitly deny
  • MUST NOT rely on client-side authorization checks
  • SHOULD implement authorization as middleware or decorators, not inline checks

3.3 Session Management

  • MUST generate cryptographically random session identifiers
  • MUST set appropriate session timeouts (per agency policy, typically 15-30 minutes idle)
  • MUST invalidate sessions on logout
  • MUST transmit session tokens only over TLS
  • MUST set Secure, HttpOnly, and SameSite flags on session cookies

Control Mapping: IA-2 (Identification), IA-5 (Authenticator Management), AC-3 (Access Enforcement), SC-23 (Session Authenticity)


4. Secrets Management

4.1 Rules

  • MUST NOT hardcode secrets (API keys, tokens, passwords, private keys) in source code
  • MUST NOT commit secrets to version control — even in private repositories
  • MUST use approved secrets management solutions (HashiCorp Vault, AWS Secrets Manager, Azure Key Vault, SOPS, or agency-provided equivalent)
  • MUST rotate secrets on a defined schedule (per agency policy)
  • MUST revoke compromised secrets immediately and rotate all dependent credentials

4.2 Prevention

  • MUST configure pre-commit hooks to scan for secrets before commits (e.g., gitleaks, detect-secrets, trufflehog)
  • MUST include common secret patterns in .gitignore:
    .env
    .env.*
    *.key
    *.pem
    *.p12
    credentials.*
    *secret*
    
  • SHOULD use environment variables for runtime secrets
  • SHOULD encrypt secrets at rest using FIPS-validated encryption

4.3 If a Secret Is Committed

If a secret is accidentally committed to version control:

  1. Revoke the secret immediately — assume it is compromised
  2. Rotate the secret and all dependent credentials
  3. Remove the secret from git history (using git filter-branch or BFG Repo-Cleaner)
  4. Report the incident per your agency's incident response procedures
  5. Audit access logs for the compromised credential

Control Mapping: IA-5 (Authenticator Management), SC-28 (Protection of Information at Rest), IR-6 (Incident Reporting)


5. Dependency and Supply Chain Security

5.1 Dependency Selection

Before adding any dependency, verify:

CheckRequirement
Maintenance statusActive commits within last 6 months
Known vulnerabilitiesNo unpatched critical/high CVEs
License compatibilityCompatible with federal use (avoid AGPL, check GPL carefully)
Download count / communityReasonable adoption — avoid single-maintainer packages for critical functions
Dependency depthMinimize transitive dependencies
Package nameVerify exact spelling — check for typosquatting

5.2 Dependency Management

  • MUST pin exact versions in production (e.g., 1.2.3 not ^1.2.3)
  • MUST commit lock files (package-lock.json, poetry.lock, Cargo.lock, go.sum)
  • MUST run dependency vulnerability scanning in CI/CD (e.g., npm audit, pip-audit, cargo audit)
  • MUST update dependencies on a regular schedule (at minimum monthly for security patches)
  • SHOULD generate SBOM (Software Bill of Materials) in SPDX or CycloneDX format
  • SHOULD verify package signatures and checksums when available

5.3 Container Image Security

If using containers:

  • MUST use minimal base images (Alpine, distroless, or agency-approved)
  • MUST pin image digests (SHA256), not just tags
  • MUST scan images for vulnerabilities before deployment
  • MUST NOT run containers as root unless absolutely necessary
  • SHOULD use multi-stage builds to minimize attack surface

Control Mapping: SR-3 (Supply Chain Controls; supersedes withdrawn SA-12), SR-11 (Component Authenticity), SA-4 (Acquisition Process)


6. Error Handling and Logging

6.1 Error Handling

  • MUST handle all errors explicitly — no empty catch blocks
  • MUST NOT expose internal details in user-facing error messages (stack traces, file paths, SQL queries, internal hostnames)
  • MUST use structured error types with error codes
  • MUST log errors with sufficient context for debugging
  • SHOULD distinguish between expected errors (validation failures) and unexpected errors (system failures)

6.2 Logging

What to log:

  • Authentication events (success and failure)
  • Authorization decisions (grants and denials)
  • Data access events (reads and writes to sensitive data)
  • Administrative actions (configuration changes, user management)
  • Error conditions and exceptions

What MUST NOT be logged:

  • Passwords, tokens, or secrets
  • Full credit card or Social Security numbers
  • Session tokens in their entirety
  • Personally Identifiable Information (PII) unless required and approved

Logging format:

  • MUST use structured logging (JSON format preferred)
  • MUST include: timestamp (ISO 8601 UTC), event type, severity level, user/agent identity, source IP, and action result
  • SHOULD include correlation IDs for request tracing

Control Mapping: AU-2 (Audit Events), AU-3 (Content of Audit Records), SI-11 (Error Handling)


7. Database Security

  • MUST use parameterized queries or prepared statements — never string concatenation for SQL
  • MUST use separate database accounts for different application functions (read-only vs read-write)
  • MUST encrypt sensitive data at rest using FIPS-validated encryption
  • MUST enable TLS for all database connections
  • MUST NOT store plaintext passwords — use bcrypt, scrypt, or Argon2id with appropriate work factors
  • SHOULD use database migrations for all schema changes (version-controlled, reversible)
  • SHOULD implement row-level security where applicable

Control Mapping: SC-28 (Protection of Information at Rest), AC-3 (Access Enforcement), IA-5 (Authenticator Management)


8. API Design and Security

8.1 API Security Requirements

  • MUST authenticate all API endpoints (except public health checks)
  • MUST implement rate limiting on all public and semi-public endpoints
  • MUST validate all request bodies against a schema (JSON Schema, OpenAPI, Zod, etc.)
  • MUST use HTTPS (TLS 1.2+) for all API traffic
  • MUST return appropriate HTTP status codes (not 200 for errors)
  • MUST NOT include sensitive data in URL query parameters (use request body or headers)
  • SHOULD implement request/response logging for audit purposes
  • SHOULD use API versioning to manage breaking changes

8.2 CORS and Headers

  • MUST configure CORS with explicit origin allowlists — never use wildcard (*) for authenticated APIs
  • MUST set security headers: Content-Security-Policy, X-Content-Type-Options, X-Frame-Options, Strict-Transport-Security
  • SHOULD use Content-Type validation on all endpoints

Control Mapping: SC-7 (Boundary Protection), AC-4 (Information Flow), SC-8 (Transmission Confidentiality)


9. Frontend Security

  • MUST implement Content Security Policy (CSP) headers
  • MUST use framework-provided output encoding (React's JSX, Angular's template binding, etc.)
  • MUST NOT use innerHTML, eval(), document.write(), or equivalent unsafe APIs with untrusted data
  • MUST implement CSRF protection for all state-changing operations
  • MUST validate all redirects against an allowlist — prevent open redirect vulnerabilities
  • SHOULD use Subresource Integrity (SRI) for externally hosted scripts and stylesheets
  • SHOULD minimize use of third-party scripts and tracking code in federal applications

Control Mapping: SI-10 (Input Validation), SC-18 (Mobile Code)


10. Infrastructure and Deployment Code

10.1 Infrastructure as Code (IaC)

  • MUST version all infrastructure definitions in source control
  • MUST use least-privilege IAM roles for all services
  • MUST encrypt data at rest and in transit by default
  • MUST NOT use default credentials or passwords for any service
  • MUST enable logging and monitoring for all deployed services
  • SHOULD use infrastructure scanning tools (tfsec, checkov, cfn-nag) in CI/CD

10.2 CI/CD Pipeline Security

  • MUST require code review approval before merging to protected branches
  • MUST run automated security scanning (SAST, SCA, secrets detection) in CI
  • MUST NOT store secrets in CI/CD configuration files — use the CI system's secrets management
  • MUST use ephemeral build environments where possible
  • MUST sign release artifacts when deploying to production
  • SHOULD implement pipeline-as-code with version-controlled CI configurations

Control Mapping: CM-2 (Baseline Configuration), SA-10 (Developer Configuration Management), SA-11 (Developer Testing)

10.3 Version Control and Release Management

This section defines version control and release management requirements for federal software projects.

Version Control Requirements

  • MUST follow Semantic Versioning (SemVer 2.0.0) for all releases:

    • MAJOR: Breaking changes (incompatible API changes)
    • MINOR: New features (backward-compatible)
    • PATCH: Bug fixes (backward-compatible)
    • Pre-release versions MAY use dot-separated identifiers (e.g., 1.0.0-alpha.1, 1.0.0-rc.1)
  • MUST use Conventional Commits 1.0.0 format for all commit messages:

    • Format: <type>[optional scope][!]: <description>
    • The ! suffix indicates a breaking change
    • See AGENTS.md for complete commit message standards
  • SHOULD sign commits using GPG or SSH keys for non-repudiation

  • MUST sign release tags for production releases (git tag -s)

  • MUST maintain CHANGELOG.md following Keep a Changelog format:

    • Sections: Added, Changed, Deprecated, Removed, Fixed, Security
    • Version links to GitHub compare views
    • SHOULD be auto-generated from conventional commits via release-please

Branch Protection

  • MUST enable branch protection on default and release branches
  • MUST require pull request reviews before merging to protected branches
  • MUST require status checks to pass before merging
  • SHOULD require linear history for cleaner release automation

Release Automation

  • MUST use automated release workflows (release-please + GitHub Actions)

  • Version bumps determined automatically from commit types:

    • feat: → Minor version bump
    • fix: → Patch version bump
    • BREAKING CHANGE: footer or ! suffix → Major version bump
    • docs:, chore:, test:, ci:, build:, style:, refactor:, perf: → No version bump (configurable)
  • MUST validate conventional-commit format in CI. The recommended mechanism is a pinned PR-title-linting GitHub Action (e.g. amannn/action-semantic-pull-request, referenced by full commit SHA) rather than a local commitlint install:

    • It requires no local npm/commitlint dependency (smaller supply-chain and maintenance surface).
    • Squash-merge is the preferred merge strategy — the validated PR title becomes the squashed commit subject that release-please consumes for version bumps. This also satisfies the "SHOULD require linear history" guidance below.
    • commitlint-cli MAY be adopted as optional local convenience tooling, but MUST NOT be required.
  • MUST create git tags for all releases (v<version>)

  • MUST generate GitHub releases with release notes from CHANGELOG

  • Release artifacts MUST be signed per §10.2

Traceability Requirements

  • Every release MUST be traceable to specific commits via git tags
  • Every commit MUST follow conventional commit format for automated classification
  • CHANGELOG.md MUST document all user-facing changes with version and date
  • Breaking changes MUST be clearly documented in CHANGELOG and commit messages

Control Mapping: CM-2 (Baseline Configuration), CM-3 (Configuration Change Control), SA-10 (Developer Configuration Management), AU-10 (Non-repudiation), SI-7 (Software, Firmware, and Information Integrity)


11. Architecture Discipline

Sound architecture requires explicit decision-making, contract-driven design, and clear boundaries. These practices ensure that AI-assisted code fits coherently into the larger system.

11.1 Architecture Decision Records (ADRs)

  • MUST write an ADR before making any architectural change — including adding external services, changing authentication flows, introducing new data stores, or altering module boundaries
  • MUST use the MADR format with federal compliance extensions (see the federal-decision-records skill for the template and workflow)
  • MUST include rejected alternatives with quantified trade-offs in every ADR
  • MUST require peer review of ADRs before the corresponding code change merges
  • SHOULD store ADRs in docs/decisions/ following the NNNN-title.md naming convention

11.2 Design by Contract

  • MUST define interface contracts (preconditions, postconditions, invariants) before writing implementations
  • MUST validate preconditions at system boundaries (API endpoints, public functions, module interfaces)
  • SHOULD document contracts using the language's type system, assertions, or schema validation (e.g., Zod, JSON Schema, Pydantic)
  • SHOULD NOT rely solely on runtime validation — encode contracts in types and interfaces where the language supports it

11.3 Separation of Concerns

  • MUST enforce one-way dependency flow — outer layers (UI, API handlers) depend on inner layers (domain logic, data access), never the reverse
  • MUST NOT mix infrastructure concerns (database, HTTP, file I/O) with business logic in the same function or class
  • SHOULD isolate side effects (network calls, file writes, database queries) behind interfaces that can be substituted in tests

11.4 Conway's Law Awareness

  • MUST align service and module boundaries with team ownership — if two modules must always deploy together, they are effectively one module
  • SHOULD consider organizational structure when designing system architecture — communication bottlenecks between teams become coupling points in code
  • SHOULD document ownership boundaries in the project's AGENTS.md or repository documentation

Control Mapping: SA-8 (Security and Privacy Engineering Principles), SA-17 (Developer Security Architecture), CM-2 (Baseline Configuration), SC-3 (Security Function Isolation)


12. Change Safety and Verification

Every code change must be verifiable, reversible, and safe. These practices ensure that changes — whether human or AI-generated — do not introduce regressions or undetected failures.

12.1 Test-Driven Development (Red-Green-Refactor)

  • MUST write a failing test before writing production code (red → green → refactor)
  • MUST NOT merge code that lacks corresponding tests
  • MUST run the full existing test suite before committing changes and verify all tests pass
  • SHOULD keep each test focused on a single behavior — one assertion per test where practical

12.2 Property-Based Testing

  • SHOULD use property-based testing (e.g., Hypothesis for Python, fast-check for JS/TS) for functions with combinatorial input spaces — parsers, validators, encoders, serializers
  • SHOULD define properties as invariants: "for all valid inputs, the output satisfies P"
  • MAY use property-based tests to supplement, not replace, example-based tests

12.3 Regression Test Rule

  • MUST add a regression test for every resolved defect — the test MUST fail against the broken state and pass against the fix
  • MUST NOT close a defect without a corresponding regression test
  • SHOULD label regression tests for traceability (e.g., test_issue_42_regression)

12.4 Snapshot and Golden Tests

  • SHOULD use snapshot or golden-file tests for deterministic outputs — configuration generation, serialization formats, report templates, API response schemas
  • MUST update snapshots explicitly and review diffs in pull requests — never auto-accept snapshot changes
  • SHOULD store golden files alongside tests in version control

12.5 Idempotent and Deterministic Operations

  • MUST design state-changing operations to be idempotent — repeated execution produces identical outcomes
  • MUST produce deterministic output given the same inputs — avoid reliance on random values, timestamps, or environment state in business logic
  • SHOULD use seed values or fixed timestamps in tests to ensure reproducibility

12.6 Explicit Error Signaling

  • MUST surface all errors — no swallowed exceptions, empty catch blocks, or silent fallbacks
  • MUST use structured error types with error codes, not bare strings
  • MUST distinguish between recoverable errors (retry, fallback) and fatal errors (halt, escalate)
  • MUST NOT use error codes or return values that callers can silently ignore — prefer exceptions or Result types

Control Mapping: SA-11 (Developer Testing), SI-2 (Flaw Remediation), SI-7 (Software Integrity), CP-10 (System Recovery and Reconstitution)


13. Scope, Simplicity, and Maintainability

Complexity is the enemy of security. Every unnecessary abstraction, speculative feature, or duplicated pattern increases attack surface and maintenance burden.

13.1 KISS and YAGNI

  • MUST NOT implement speculative features — code only what current requirements demand
  • MUST prefer the simplest solution that satisfies requirements — clever code is maintenance debt
  • MUST NOT add configurability, feature flags, or extension points unless the current task requires them
  • SHOULD ask "what is the simplest thing that could possibly work?" before designing a solution

13.1.1 The Laziness Ladder

Before writing code, the agent SHOULD stop at the first rung that holds — prefer the option that requires the least new code:

  1. Does this need to exist at all? If not, skip it (YAGNI).
  2. Does the standard library already do this? Use it.
  3. Does a native platform feature cover it? Use it.
  4. Does an already-installed dependency solve it? Use it (no new dependency).
  5. Can it be one line? Make it one line.
  6. Only then: write the minimum code that works.

The goal is less code because it is necessary, not code golf. Pick the edge-case-correct option when two approaches are the same size — "lazy" means less code, never the flimsier algorithm.

Lazy is not negligent. The following are NEVER simplified away, regardless of the ladder: input validation at trust boundaries (§3), error handling that prevents data loss (§4), security controls, accessibility (Section 508 / WCAG), and anything explicitly requested. Non-trivial logic MUST leave at least one runnable check behind (a test or assert-based self-check, per §12); trivial one-liners need none.

Mark an intentional simplification with a comment naming the shortcut and, if it has a known ceiling (a global lock, an O(n²) scan, a naive heuristic), the ceiling and the upgrade path — so "later" does not silently become "never".

Inspired by the open-source ponytail ruleset (MIT). Adapted for federal use: the non-negotiable carve-outs above are mandatory, not optional.

13.2 DRY and the Rule of Three

  • MUST extract shared logic only at three or more occurrences — two is coincidence, three is a pattern worth extracting
  • MUST NOT DRY prematurely — premature abstraction is worse than duplication
  • MUST ensure extracted abstractions have clear, single-purpose interfaces
  • SHOULD prefer composition over inheritance for code reuse

13.3 Size and Complexity Guidelines

  • MUST enforce these limits (exceptions require written justification in the PR description):
    • Functions: ≤50 lines of logic (excluding blank lines, comments, and closing brackets)
    • Files/modules: ≤400 lines (cohesive 400-600 line files are acceptable with justification)
    • Cyclomatic complexity: ≤10 per function
    • Function parameters: ≤5 (use an options/config object for more)
  • MUST justify any exception to these limits in the pull request — "it's complex because..." is required, not optional
  • SHOULD use automated linting to enforce these limits in CI

13.4 SOLID Principles

Apply these principles proportionally to the project's complexity:

  • Single Responsibility Principle (SRP): Each module, class, or function SHOULD have one reason to change
  • Open/Closed Principle (OCP): Code SHOULD be open for extension but closed for modification — add new behavior by adding new code, not modifying existing code
  • Liskov Substitution Principle (LSP): Subtypes MUST be substitutable for their base types without altering correctness
  • Interface Segregation Principle (ISP): Interfaces SHOULD be narrow and client-specific — no client should depend on methods it does not use
  • Dependency Inversion Principle (DIP): High-level modules SHOULD NOT depend on low-level modules — both should depend on abstractions

13.5 Module Boundaries

  • MUST define explicit public APIs for each module — only exported interfaces are part of the contract
  • MUST NOT import internal implementation details across module boundaries
  • SHOULD document module boundaries and their contracts in the project's architecture documentation
  • SHOULD enforce module boundary violations in CI (e.g., import restrictions, dependency rules)

Control Mapping: SA-8 (Security Engineering Principles), SA-15 (Development Process), SC-3 (Security Function Isolation), CM-3 (Configuration Change Control)


14. Accessibility (Section 508 / WCAG 2.1)

Federal systems MUST comply with Section 508 of the Rehabilitation Act (29 U.S.C. section 794d) and meet WCAG 2.1 Level AA success criteria. AI-generated UI code is not exempt from these requirements.

14.1 General Requirements

  • ALL AI-generated UI code MUST meet WCAG 2.1 Level AA conformance before deployment
  • Developers MUST verify that AI-generated components do not introduce accessibility regressions — AI models frequently produce inaccessible markup (missing labels, incorrect ARIA usage, insufficient contrast)
  • Accessibility MUST be validated both by automated tools and manual testing (keyboard navigation, screen reader verification)

14.2 Semantic HTML

  • MUST use semantic HTML elements (<nav>, <main>, <header>, <footer>, <section>, <article>) instead of generic <div> containers
  • MUST use heading elements (<h1> through <h6>) in logical, hierarchical order — do not skip levels
  • MUST use <button> for interactive controls (not styled <div> or <span> elements with click handlers)
  • MUST use landmark regions so assistive technology can navigate the page structure

14.3 Color and Visual Design

  • MUST maintain a minimum contrast ratio of 4.5:1 for normal text (under 18pt / 14pt bold)
  • MUST maintain a minimum contrast ratio of 3:1 for large text (18pt+ / 14pt+ bold) and UI components
  • MUST NOT use color as the sole means of conveying information — provide text labels, patterns, or icons as secondary indicators

14.4 Keyboard Navigation

  • ALL interactive elements MUST be operable via keyboard alone (Tab, Shift+Tab, Enter, Space, Arrow keys)
  • MUST provide a visible focus indicator on all focusable elements — do not suppress the browser's default focus outline without providing an equivalent
  • MUST implement logical tab order that follows the visual reading order
  • MUST provide skip navigation links for repetitive content blocks

14.5 Screen Reader Compatibility

  • ALL images MUST have alt text — decorative images use alt="" (empty string, not omitted)
  • ALL form inputs MUST have a programmatically associated <label> element (use for/id pairing or wrap the input in the label)
  • MUST use aria-label or aria-labelledby only when a visible text label is not feasible
  • MUST NOT use ARIA roles that conflict with the element's native semantics
  • Dynamic content changes MUST use aria-live regions to announce updates to screen readers

14.6 Forms

  • Every form input MUST have a visible, descriptive label — placeholder text alone is not sufficient
  • Required fields MUST be indicated both visually and programmatically (aria-required="true" or the required attribute)
  • Error messages MUST be associated with the relevant input (aria-describedby) and announced to screen readers
  • Form validation errors MUST NOT rely solely on color to indicate the error state

14.7 Testing Tools and Process

  • MUST run automated accessibility scanning in CI using at least one of: axe-core, Lighthouse accessibility audit, or pa11y
  • SHOULD use browser-based tools during development: WAVE evaluation tool, axe DevTools, or Lighthouse
  • SHOULD perform manual screen reader testing with NVDA (Windows), VoiceOver (macOS/iOS), or Orca (Linux) before release
  • SHOULD include users of assistive technology in usability testing when feasible

Legal Reference: Section 508 of the Rehabilitation Act (29 U.S.C. section 794d), as amended by the ICT Standards and Guidelines (36 CFR Part 1194)

Standards: WCAG 2.1 Level AA (W3C Recommendation), referenced by the U.S. Access Board's ICT Standards

Control Mapping: SA-8 (Security and Privacy Engineering Principles — encompasses quality attributes including accessibility)


15. AI Bias and Fairness

AI-generated code that influences decisions about people carries additional risk. Bias in training data, model architecture, or prompt design can produce discriminatory outcomes that violate federal equal opportunity requirements.

15.1 Code Review for Discriminatory Patterns

  • AI-generated code SHOULD be reviewed for discriminatory patterns — scoring, ranking, filtering, or eligibility logic that may produce disparate outcomes across protected classes (race, gender, age, disability, national origin, religion)
  • Developers MUST NOT deploy AI-generated decision logic without verifying that it does not encode proxies for protected characteristics (e.g., zip code as proxy for race, name patterns as proxy for national origin)
  • AI-generated sorting, ranking, or prioritization algorithms SHOULD be reviewed for implicit bias in default orderings or weighting

15.2 Bias Testing Requirements

  • Outputs that make decisions about people — eligibility determinations, scoring, ranking, resource allocation, or risk assessments — MUST be tested for bias before deployment
  • MUST test with diverse input data representing protected classes to verify equitable outcomes across demographic groups
  • SHOULD use fairness metrics appropriate to the use case (demographic parity, equalized odds, predictive parity) and document which metrics were applied and why
  • SHOULD perform adversarial testing with edge-case inputs designed to surface discriminatory behavior

15.3 Documentation and Transparency

  • MUST document any known limitations or biases in AI model outputs used by the system — include these in the system's risk assessment and user-facing documentation
  • MUST document the demographic composition of test data used for bias evaluation
  • SHOULD maintain a bias incident log for issues discovered post-deployment

15.4 Federal Policy Alignment

  • M-26-04 (Unbiased AI Principles): AI systems MUST adhere to Truth-Seeking and Ideological Neutrality principles — outputs should reflect objective analysis, not encode cultural or political bias from training data
  • NIST AI 600-1 (GenAI Risk Profile), Risk #5 (Bias/Homogenization): Generative AI systems risk amplifying biases present in training data and producing homogenized outputs that erase minority perspectives. Systems SHOULD implement bias detection and mitigation strategies as described in the NIST AI RMF MEASURE function

Control Mapping: NIST AI RMF MEASURE 2.6 (Bias Testing), NIST AI 600-1 Risk #5, M-26-04 Section 3


16. AI Model Evaluation

Before integrating an AI model into a federal system, teams MUST evaluate the model's fitness for the intended use case. Model selection is an architectural decision with security, accuracy, and compliance implications.

16.1 Pre-Use Evaluation Criteria

Before using an AI model (whether for code generation, analysis, or decision support), evaluate:

  • Accuracy on your domain: Test the model against representative tasks from your problem space — do not rely solely on vendor-reported benchmarks
  • Known limitations: Review the model's documentation (model card, technical report) for disclosed weaknesses, failure modes, and out-of-distribution behavior
  • Training data provenance: Understand what data the model was trained on, whether it includes your domain, and whether the training data is appropriately licensed
  • Security posture: Assess whether the model has undergone adversarial testing, red-teaming, or security evaluation relevant to your threat model

16.2 Code Generation Validation

  • For code generation use cases, MUST test model output against known-good reference implementations before trusting the model for production tasks
  • SHOULD maintain a benchmark suite of representative coding tasks with verified solutions to evaluate model accuracy over time
  • SHOULD re-evaluate model performance when upgrading to new model versions — regressions are common

16.3 Model Selection Documentation

  • MUST document model selection rationale in an Architecture Decision Record (ADR) — use the federal-decision-records skill for the MADR template with federal compliance extensions
  • The ADR MUST include: model name and version, evaluation criteria applied, benchmark results, rejected alternatives with reasoning, and any compliance considerations
  • SHOULD include cost, latency, and data residency analysis in the ADR

16.4 Federal Policy Requirements

  • M-25-21 (Pre-Deployment Testing): AI systems MUST undergo pre-deployment testing that evaluates accuracy, reliability, and safety before being deployed in federal environments
  • M-26-04 (Model Cards): For LLM procurements, agencies SHOULD require model cards from vendors that document training data, evaluation results, intended use cases, and known limitations

Control Mapping: SA-11 (Developer Testing), SA-4 (Acquisition Process), M-25-21 Section 3, M-26-04 Section 4


17. Continuous Monitoring for AI Systems

Deploying an AI system is not the finish line. AI models degrade over time in ways traditional software does not — accuracy declines as real-world data drifts from training data, adversaries adapt their attacks, and user behavior shifts. Continuous monitoring (ConMon) catches these failures before they reach end users.

17.1 Post-Deployment Monitoring Requirements

  • MUST monitor AI system outputs for quality degradation over time — track error rates, response latency, and user-reported issues
  • MUST set up automated alerts for anomalous behavior: sudden accuracy drops, unexpected output patterns, or significant changes in confidence score distributions
  • SHOULD log a representative sample of inputs and outputs (with PII redacted) to enable retrospective analysis when issues are reported

17.2 Model Drift Detection

  • AI models degrade as real-world data diverges from training data — this is expected, not exceptional
  • MUST establish baseline performance metrics at deployment time and document them in the system's ADR
  • MUST schedule periodic evaluation against baseline at minimum monthly intervals
  • SHOULD automate drift detection where feasible (e.g., statistical tests on output distributions)
  • When drift exceeds acceptable thresholds, document findings and remediation plan in an ADR — use the federal-decision-records skill for the MADR template

17.3 Security Monitoring

  • MUST monitor for prompt injection attempts — log sanitized inputs that trigger defense mechanisms (see docs/PROMPT-INJECTION-DEFENSE.md for defense patterns)
  • MUST track the rate of blocked and filtered requests to detect attack campaigns
  • SHOULD review AI access patterns for unauthorized usage, unusual request volumes, or access from unexpected sources
  • SHOULD correlate AI security events with broader system security monitoring (SIEM integration)

17.4 Federal Policy Requirements

  • M-25-21 (Continuous Monitoring): Requires "continuous monitoring" for high-impact AI systems — agencies MUST demonstrate ongoing oversight, not just pre-deployment testing
  • NIST AI 800-4 (March 2026): Identifies key challenges in monitoring deployed AI systems, including evasion attacks that degrade model performance gradually and data poisoning that manifests only after deployment
  • ConMon findings feed directly into ATO continuous authorization — AI-specific metrics MUST be included in the system's ongoing authorization package

17.5 Minimum ConMon Checklist

Before an AI system receives production traffic, verify:

  • Error rate tracking enabled with alerting thresholds defined
  • Performance baseline documented in ADR with quantitative metrics
  • Monthly evaluation scheduled and assigned to a responsible party
  • Security monitoring active for prompt injection and access anomalies
  • Incident response plan updated to cover AI-specific failure modes (drift, adversarial inputs, hallucination spikes)

Control Mapping: CA-7 (Continuous Monitoring), SI-4 (System Monitoring), M-25-21 Section 5, NIST AI 800-4


OWASP Top 10 for LLM Applications — Cross-Reference

This section maps the OWASP Top 10 for LLM Applications (2025) to relevant sections of this document and AGENTS.md.

OWASP RiskCovered InKey Mitigation
LLM01: Prompt InjectionAGENTS.md §11Treat external data as untrusted; never execute embedded instructions
LLM02: Sensitive Information Disclosure§4 (Secrets), §6.2 (Logging)Never log secrets or PII; use secrets management
LLM03: Supply Chain§5 (Dependencies)Pin versions, scan for vulns, verify packages
LLM04: Data and Model PoisoningAGENTS.md §11Validate training data sources; monitor for drift
LLM05: Improper Output Handling§2.2 (Output Encoding)Encode output based on context; validate AI output
LLM06: Excessive AgencyAGENTS.md §3, §10Least privilege; human-in-the-loop for destructive actions
LLM07: System Prompt LeakageAGENTS.md §4Treat system prompts as sensitive; don't expose in logs
LLM08: Vector and Embedding WeaknessesNot in MVP scopeAddress in future multi-agent guidance
LLM09: Misinformation§1.2 (Known Limitations)Verify AI output against official docs; human review
LLM10: Unbounded Consumption§8.1 (Rate Limiting)Rate limiting, timeout handling, resource bounds

OWASP Top 10 for Agentic Applications — Cross-Reference

OWASP Agentic RiskCovered InKey Mitigation
Agent Goal HijackAGENTS.md §11Prompt injection defense; untrusted input handling
Identity and Privilege AbuseAGENTS.md §2, §3Agent identity; least privilege; human-in-the-loop
Unexpected Code ExecutionAGENTS.md §10Prohibited actions; no execution of external code
Insecure Inter-Agent CommunicationNot in MVP scopeAddress in future multi-agent guidance
Human Agent Trust ExploitationAGENTS.md §3.2Explicit approval requirements; transparency
Tool Misuse and ExploitationAGENTS.md §3, §10Capability restrictions; least privilege
Agentic Supply Chain Vulnerabilities§5 (Dependencies)Pin versions, scan, verify provenance
Memory and Context PoisoningAGENTS.md §11Validate external content; session boundaries
Cascading FailuresAGENTS.md §9Error handling; incident escalation
Rogue AgentsAGENTS.md §10Prohibited actions; behavioral rules; audit logging

SSDF (SP 800-218A) Practice Mapping

SSDF PracticePractice NameCovered In
PO.1Define Security RequirementsAGENTS.md §1 (Core Principles)
PS.1Protect All Forms of Code§4 (Secrets), §5 (Supply Chain)
PS.2Provide a Mechanism for Verifying Software Integrity§5.2 (Dependency Management), §10.2 (CI/CD)
PW.1Design Software to Meet Security Requirements§2-§9 (all coding sections), §11 (Architecture Discipline)
PW.2Review Software Design§1.1 (Code Provenance), §11.1 (ADRs), AGENTS.md §8 (AI Code Review)
PW.4Reuse Existing, Well-Secured Software§5 (Dependency Selection), §13.2 (DRY / Rule of Three)
PW.5Create Source Code by Adhering to Secure Coding Practices§2-§9, §11-§13 (all coding and discipline sections)
PW.6Configure the Build Process§10.2 (CI/CD Pipeline Security)
PW.7Review and Test Code§12 (Change Safety), AGENTS.md §8 (Testing), §1 (AI-Generated Code Review)
PW.8Configure Software to Have Secure Settings by Default§12 (Configuration) in AGENTS.md
PW.9Test Executable Code§12.1 (TDD), §12.2 (Property Tests), §12.3 (Regression), AGENTS.md §8
RV.1Identify and Confirm VulnerabilitiesAGENTS.md §9 (Vulnerability Discovery)
RV.2Assess, Prioritize, and RemediateAGENTS.md §9 (Incident Response)
RV.3Analyze Vulnerabilities to Identify Root CausesAGENTS.md §9

Version History

DateVersionChange
2026-02-250.1.0Initial release

Framework References

  • NIST SP 800-53 Rev 5.2.0 (September 2024)
  • NIST SP 800-218A Secure Software Development Practices for Generative AI (June 2024)
  • NIST SP 800-218 Rev 1 SSDF v1.2 (Draft, 2025)
  • OWASP Top 10 for LLM Applications 2025
  • OWASP Top 10 for Agentic Applications 2026
  • CISA Secure by Design Principles (2025)
  • CISA Memory Safety Guidance (2025)