Metadata-Version: 2.4
Name: aws-network-preflight
Version: 0.1.0
Summary: Declare allowed and denied AWS connectivity in YAML and verify it with AWS Reachability Analyzer.
Project-URL: Homepage, https://github.com/gcasanova/aws-network-preflight
Project-URL: Repository, https://github.com/gcasanova/aws-network-preflight
Author: Guillermo Casanova
License: Apache License
        Version 2.0, January 2004
        http://www.apache.org/licenses/
        
        TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
        1. Definitions.
        
           "License" shall mean the terms and conditions for use, reproduction,
           and distribution as defined by Sections 1 through 9 of this document.
        
           "Licensor" shall mean the copyright owner or entity authorized by
           the copyright owner that is granting the License.
        
           "Legal Entity" shall mean the union of the acting entity and all
           other entities that control, are controlled by, or are under common
           control with that entity. For the purposes of this definition,
           "control" means (i) the power, direct or indirect, to cause the
           direction or management of such entity, whether by contract or
           otherwise, or (ii) ownership of fifty percent (50%) or more of the
           outstanding shares, or (iii) beneficial ownership of such entity.
        
           "You" (or "Your") shall mean an individual or Legal Entity
           exercising permissions granted by this License.
        
           "Source" form shall mean the preferred form for making modifications,
           including but not limited to software source code, documentation
           source, and configuration files.
        
           "Object" form shall mean any form resulting from mechanical
           transformation or translation of a Source form, including but
           not limited to compiled object code, generated documentation,
           and conversions to other media types.
        
           "Work" shall mean the work of authorship, whether in Source or
           Object form, made available under the License, as indicated by a
           copyright notice that is included in or attached to the work
           (an example is provided in the Appendix below).
        
           "Derivative Works" shall mean any work, whether in Source or Object
           form, that is based on (or derived from) the Work and for which the
           editorial revisions, annotations, elaborations, or other modifications
           represent, as a whole, an original work of authorship. For the purposes
           of this License, Derivative Works shall not include works that remain
           separable from, or merely link (or bind by name) to the interfaces of,
           the Work and Derivative Works thereof.
        
           "Contribution" shall mean any work of authorship, including
           the original version of the Work and any modifications or additions
           to that Work or Derivative Works thereof, that is intentionally
           submitted to Licensor for inclusion in the Work by the copyright owner
           or by an individual or Legal Entity authorized to submit on behalf of
           the copyright owner. For the purposes of this definition, "submitted"
           means any form of electronic, verbal, or written communication sent
           to the Licensor or its representatives, including but not limited to
           communication on electronic mailing lists, source code control systems,
           and issue tracking systems that are managed by, or on behalf of, the
           Licensor for the purpose of discussing and improving the Work, but
           excluding communication that is conspicuously marked or otherwise
           designated in writing by the copyright owner as "Not a Contribution."
        
           "Contributor" shall mean Licensor and any individual or Legal Entity
           on behalf of whom a Contribution has been received by Licensor and
           subsequently incorporated within the Work.
        
        2. Grant of Copyright License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           copyright license to reproduce, prepare Derivative Works of,
           publicly display, publicly perform, sublicense, and distribute the
           Work and such Derivative Works in Source or Object form.
        
        3. Grant of Patent License. Subject to the terms and conditions of
           this License, each Contributor hereby grants to You a perpetual,
           worldwide, non-exclusive, no-charge, royalty-free, irrevocable
           (except as stated in this section) patent license to make, have made,
           use, offer to sell, sell, import, and otherwise transfer the Work,
           where such license applies only to those patent claims licensable
           by such Contributor that are necessarily infringed by their
           Contribution(s) alone or by combination of their Contribution(s)
           with the Work to which such Contribution(s) was submitted. If You
           institute patent litigation against any entity (including a
           cross-claim or counterclaim in a lawsuit) alleging that the Work
           or a Contribution incorporated within the Work constitutes direct
           or contributory patent infringement, then any patent licenses
           granted to You under this License for that Work shall terminate
           as of the date such litigation is filed.
        
        4. Redistribution. You may reproduce and distribute copies of the
           Work or Derivative Works thereof in any medium, with or without
           modifications, and in Source or Object form, provided that You
           meet the following conditions:
        
           (a) You must give any other recipients of the Work or
               Derivative Works a copy of this License; and
        
           (b) You must cause any modified files to carry prominent notices
               stating that You changed the files; and
        
           (c) You must retain, in the Source form of any Derivative Works
               that You distribute, all copyright, patent, trademark, and
               attribution notices from the Source form of the Work,
               excluding those notices that do not pertain to any part of
               the Derivative Works; and
        
           (d) If the Work includes a "NOTICE" text file as part of its
               distribution, then any Derivative Works that You distribute must
               include a readable copy of the attribution notices contained
               within such NOTICE file, excluding those notices that do not
               pertain to any part of the Derivative Works, in at least one
               of the following places: within a NOTICE text file distributed
               as part of the Derivative Works; within the Source form or
               documentation, if provided along with the Derivative Works; or,
               within a display generated by the Derivative Works, if and
               wherever such third-party notices normally appear. The contents
               of the NOTICE file are for informational purposes only and
               do not modify the License. You may add Your own attribution
               notices within Derivative Works that You distribute, alongside
               or as an addendum to the NOTICE text from the Work, provided
               that such additional attribution notices cannot be construed
               as modifying the License.
        
           You may add Your own copyright statement to Your modifications and
           may provide additional or different license terms and conditions
           for use, reproduction, or distribution of Your modifications, or
           for any such Derivative Works as a whole, provided Your use,
           reproduction, and distribution of the Work otherwise complies with
           the conditions stated in this License.
        
        5. Submission of Contributions. Unless You explicitly state otherwise,
           any Contribution intentionally submitted for inclusion in the Work
           by You to the Licensor shall be under the terms and conditions of
           this License, without any additional terms or conditions.
           Notwithstanding the above, nothing herein shall supersede or modify
           the terms of any separate license agreement you may have executed
           with Licensor regarding such Contributions.
        
        6. Trademarks. This License does not grant permission to use the trade
           names, trademarks, service marks, or product names of the Licensor,
           except as required for reasonable and customary use in describing the
           origin of the Work and reproducing the content of the NOTICE file.
        
        7. Disclaimer of Warranty. Unless required by applicable law or
           agreed to in writing, Licensor provides the Work (and each
           Contributor provides its Contributions) on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied, including, without limitation, any warranties or conditions
           of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
           PARTICULAR PURPOSE. You are solely responsible for determining the
           appropriateness of using or redistributing the Work and assume any
           risks associated with Your exercise of permissions under this License.
        
        8. Limitation of Liability. In no event and under no legal theory,
           whether in tort (including negligence), contract, or otherwise,
           unless required by applicable law (such as deliberate and grossly
           negligent acts) or agreed to in writing, shall any Contributor be
           liable to You for damages, including any direct, indirect, special,
           incidental, or consequential damages of any character arising as a
           result of this License or out of the use or inability to use the
           Work (including but not limited to damages for loss of goodwill,
           work stoppage, computer failure or malfunction, or any and all
           other commercial damages or losses), even if such Contributor
           has been advised of the possibility of such damages.
        
        9. Accepting Warranty or Additional Liability. While redistributing
           the Work or Derivative Works thereof, You may choose to offer,
           and charge a fee for, acceptance of support, warranty, indemnity,
           or other liability obligations and/or rights consistent with this
           License. However, in accepting such obligations, You may act only
           on Your own behalf and on Your sole responsibility, not on behalf
           of any other Contributor, and only if You agree to indemnify,
           defend, and hold each Contributor harmless for any liability
           incurred by, or claims asserted against, such Contributor by reason
           of your accepting any such warranty or additional liability.
        
        END OF TERMS AND CONDITIONS
        
        APPENDIX: How to apply the Apache License to your work.
        
           To apply the Apache License to your work, attach the following
           boilerplate notice, with the fields enclosed by brackets "[]"
           replaced with your own identifying information. (Don't include
           the brackets!)  The text should be enclosed in the appropriate
           comment syntax for the file format. We also recommend that a
           file or class name and description of purpose be included on the
           same "printed page" as the copyright notice for easier
           identification within third-party archives.
        
        Copyright [yyyy] [name of copyright owner]
        
        Licensed under the Apache License, Version 2.0 (the "License");
        you may not use this file except in compliance with the License.
        You may obtain a copy of the License at
        
            http://www.apache.org/licenses/LICENSE-2.0
        
        Unless required by applicable law or agreed to in writing, software
        distributed under the License is distributed on an "AS IS" BASIS,
        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
        See the License for the specific language governing permissions and
        limitations under the License.
License-File: LICENSE
Keywords: aws,cli,networking,reachability-analyzer,sre
Classifier: License :: OSI Approved :: Apache Software License
Requires-Python: >=3.11
Requires-Dist: boto3>=1.34.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: pyyaml>=6.0.1
Requires-Dist: rich>=13.7.0
Requires-Dist: typer>=0.12.3
Provides-Extra: dev
Requires-Dist: mypy>=1.10.0; extra == 'dev'
Requires-Dist: pytest>=8.2.0; extra == 'dev'
Requires-Dist: ruff>=0.4.0; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0.12; extra == 'dev'
Description-Content-Type: text/markdown

# aws-network-preflight

[![CI](https://github.com/gcasanova/aws-network-preflight/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/gcasanova/aws-network-preflight/actions/workflows/ci.yml) [![License: Apache 2.0](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](LICENSE) [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](#installation)

Declare allowed and denied AWS connectivity in YAML and verify it with AWS Reachability Analyzer.

`aws-network-preflight` is a Python CLI for platform, SRE, and networking teams that want to describe expected AWS connectivity in version-controlled YAML and verify it with AWS Reachability Analyzer. It helps catch drift in security groups, routes, and attachments before that drift turns into a broken deployment or an incident.

The scope is intentionally narrow. v1 focuses on single-region AWS connectivity validation for EC2 instances and ENIs.

## Why this exists

AWS connectivity changes over time. Security groups get edited, routes move, NACLs tighten, new attachments appear, and paths that used to work quietly stop working.

This project exists to make expected connectivity explicit and testable:

- declare intent in YAML
- verify it locally or in CI
- use AWS-native analysis instead of hand-built network heuristics

## Installation

Python 3.11+ is required.

### Recommended install

Install from PyPI:

```bash
pipx install aws-network-preflight
```

That gives you a globally available CLI in an isolated environment.

### Install from source

Install from source for local development:

```bash
git clone https://github.com/gcasanova/aws-network-preflight.git
python3 -m venv ~/venvs/anp
source ~/venvs/anp/bin/activate
pip install -e ./aws-network-preflight
```

This keeps the virtual environment outside the repository instead of creating a local `.venv` inside the source tree.

`anp` is the short alias for `aws-network-preflight`.

The CLI uses the AWS credential chain and supports profile-based authentication. For multi-account setups, logical accounts can also define per-account `role_arn` values to assume.

You will need AWS credentials and permissions that can read the referenced resources and run Reachability Analyzer in the configured accounts.

## Quick start

Create a starter config:

```bash
anp init
```

Edit `preflight.yaml` with your real AWS profile, region, accounts, and selectors.

Validate the config:

```bash
anp validate -f preflight.yaml
```

Resolve the configured targets without running analysis:

```bash
anp list-targets -f preflight.yaml
```

Run the assertions:

```bash
anp run -f preflight.yaml
```

Inspect one assertion in detail:

```bash
anp explain -f preflight.yaml --id client-to-server-443-allow
```

For CI-friendly output, `run` and `explain` also support `--format json`.

## Minimal example config

This is the simplest same-account profile-based shape:

```yaml
version: 1

defaults:
  region: us-east-1
  auth:
    mode: profile
    profile: default

accounts:
  lab:
    regions: [us-east-1]

assertions:
  - id: client-to-server-443-allow
    type: allow
    source:
      account: lab
      selector:
        tags:
          Name: client
    destination:
      account: lab
      selector:
        tags:
          Name: server
    protocol: tcp
    port: 443

  - id: client-to-server-80-deny
    type: deny
    source:
      account: lab
      selector:
        tags:
          Name: client
    destination:
      account: lab
      selector:
        tags:
          Name: server
    protocol: tcp
    port: 80
```

`role_arn` is optional for simple same-account profile-based usage. For multi-account configurations, each logical account can also define a `role_arn` to assume.

## Cross-account example

For multi-account setups, logical accounts can carry their own role assumptions:

```yaml
version: 1

defaults:
  region: us-east-1
  auth:
    mode: profile
    profile: default

accounts:
  shared:
    role_arn: arn:aws:iam::111111111111:role/PreflightReadRole
    regions: [us-east-1]

  app:
    role_arn: arn:aws:iam::222222222222:role/PreflightReadRole
    regions: [us-east-1]

assertions:
  - id: dev-to-shared-dns-allow
    type: allow
    source:
      account: app
      selector:
        tags:
          Name: app-dev-ec2
    destination:
      account: shared
      selector:
        tags:
          Name: shared-dns-endpoint
    protocol: tcp
    port: 53

  - id: dev-to-prod-db-deny
    type: deny
    source:
      account: app
      selector:
        tags:
          Name: app-dev-ec2
    destination:
      account: app
      selector:
        tags:
          Name: app-prod-db
    protocol: tcp
    port: 5432
```

## Recommended IAM permissions

At a minimum, the CLI usually needs enough access to discover the selected resources, run Reachability Analyzer, and identify the effective AWS account for each configured session.

- Discovery: `ec2:DescribeInstances`, `ec2:DescribeNetworkInterfaces`
- Reachability Analyzer execution: `ec2:CreateNetworkInsightsPath`, `ec2:DeleteNetworkInsightsPath`, `ec2:StartNetworkInsightsAnalysis`, `ec2:DescribeNetworkInsightsAnalyses`, `ec2:DeleteNetworkInsightsAnalysis`
- Identity and account resolution: `sts:GetCallerIdentity`
- Cross-account usage with `role_arn`: `sts:AssumeRole`

The exact policy can vary by account structure and whether you use same-account credentials or cross-account role assumption.

## Example commands and output

Common tasks:

```bash
# run all configured assertions
anp run -f preflight.yaml

# inspect one assertion in detail
anp explain -f preflight.yaml --id client-to-server-443-allow

# emit machine-readable output for CI
anp run -f preflight.yaml --format json
```

Text output from `run`:

```text
                                                                     Assertion Results
┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃ Assertion ID                ┃ Expected      ┃ Actual        ┃ Status ┃ Analysis ID          ┃ Detail                                                     ┃
┡━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ client-to-server-443-allow  │ reachable     │ reachable     │ passed │ nia-0abc123def456789 │ Expected reachable and Reachability Analyzer reported      │
│                             │               │               │        │                      │ reachable.                                                 │
│ client-to-server-80-deny    │ not reachable │ reachable     │ failed │ nia-0123abc456def789 │ Expected not reachable but Reachability Analyzer reported  │
│                             │               │               │        │                      │ reachable.                                                 │
└─────────────────────────────┴───────────────┴───────────────┴────────┴──────────────────────┴────────────────────────────────────────────────────────────┘
Passed: 1  Failed: 1  Errors: 0
```

JSON output from `run --format json`:

```json
{
  "error_count": 0,
  "failed_count": 1,
  "passed_count": 1,
  "results": [
    {
      "actual_outcome": "reachable",
      "assertion_id": "client-to-server-443-allow",
      "expected_outcome": "reachable",
      "status": "passed"
    },
    {
      "actual_outcome": "reachable",
      "assertion_id": "client-to-server-80-deny",
      "expected_outcome": "not_reachable",
      "status": "failed"
    }
  ]
}
```

## Troubleshooting

- `Unable to locate credentials`: the AWS credential chain did not find usable credentials. Check your environment, local AWS config, or the profile referenced in `defaults.auth.profile`.
- `AccessDenied` or `UnauthorizedOperation`: the active credentials can reach AWS but do not have one or more required EC2 or STS permissions. Check discovery permissions, Reachability Analyzer permissions, and `sts:AssumeRole` when `role_arn` is configured.
- Tag selector matches no resources: the selected account, region, or tag values do not resolve to a supported v1 target. Check `defaults.region`, the endpoint `account`, and the exact tag key and value on the EC2 instance or ENI.
- Tag selector matches multiple resources: the selector is not unique within the configured account and region. Tighten the tag set until it resolves to exactly one EC2 instance or ENI.
- Reachability Analyzer finished with `failed` or another unexpected status: AWS did not produce a normal successful analysis result. Check the detailed error output first, then confirm the source and destination resolved to the intended ENIs and that the execution account has the required Reachability Analyzer permissions.

## Exit codes

- `0`: all assertions passed
- `1`: one or more assertions failed
- `2`: config or validation error
- `3`: runtime, AWS API, or authentication error

## Demo

A short terminal demo showing config validation, target resolution, real Reachability Analyzer execution, and assertion inspection will be added here.

<!-- Example:
[Demo video](...)
![aws-network-preflight demo](docs/demo/anp-demo.gif)
-->

## Design choices

The scope is intentionally narrow because the goal is a reliable v1, not a vague networking framework.

- AWS-first because the tool is built around AWS-native analysis and AWS account boundaries, not generic abstractions.
- Single-region-only in v1 because discovery and execution are easier to reason about when every assertion runs in one explicit effective region from `defaults.region`.
- Reachability Analyzer only in v1 because one trustworthy engine is more useful than several partially supported analysis modes.
- ENI as the canonical execution target because it is the most precise AWS networking anchor for path analysis.
- EC2 instance as a convenience input because it keeps the CLI practical while still normalizing execution to one concrete ENI.
- Narrow target-family support because public v1 credibility comes from being explicit about what the tool does support, not by implying it solves all of AWS networking.

## Limitations

- v1 is single-region-only
- v1 uses AWS Reachability Analyzer only
- supported target families are limited to EC2 instances and ENIs
- selectors must resolve to exactly one supported resource
- tag ambiguity is a hard failure
- only the standard commercial AWS partition (`aws`) is supported
- no Network Access Analyzer, active probes, internet exposure checks, or service-specific logic for TGW, Cloud WAN, PrivateLink, or VPC Lattice

## Development

Install development dependencies and run the local checks:

```bash
git clone https://github.com/gcasanova/aws-network-preflight.git
python3 -m venv ~/venvs/anp-dev
source ~/venvs/anp-dev/bin/activate
pip install -e "./aws-network-preflight[dev]"
cd aws-network-preflight
ruff check .
ruff format --check .
mypy preflight
pytest
```

## Contributing

Issues, feedback, and contributions are welcome.

A good first contribution is usually one of these:

- improve documentation and examples
- tighten validation and error messages
- add focused test coverage for supported v1 behavior
- improve local UX without broadening the scope carelessly

## License

This project is licensed under the Apache License 2.0. See [LICENSE](LICENSE).
