{"id":15050375,"url":"https://github.com/mozilla/frost","last_synced_at":"2025-04-09T18:19:24.500Z","repository":{"id":54878615,"uuid":"105812506","full_name":"mozilla/frost","owner":"mozilla","description":"Unit testing framework for test driven security of AWS, GCP, Heroku and more.","archived":false,"fork":false,"pushed_at":"2024-01-13T10:31:35.000Z","size":934,"stargazers_count":106,"open_issues_count":43,"forks_count":18,"subscribers_count":9,"default_branch":"main","last_synced_at":"2025-03-29T16:28:57.603Z","etag":null,"topics":["pytest","security-audit","third-party"],"latest_commit_sha":null,"homepage":"https://mozilla.github.io/frost/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mpl-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mozilla.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/ContributingDocumentation.rst","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2017-10-04T20:00:35.000Z","updated_at":"2025-03-23T23:09:59.000Z","dependencies_parsed_at":"2024-04-23T18:25:11.005Z","dependency_job_id":"3b7c88ec-32d2-4e53-8580-019cca1b288d","html_url":"https://github.com/mozilla/frost","commit_stats":{"total_commits":315,"total_committers":19,"mean_commits":16.57894736842105,"dds":0.6984126984126984,"last_synced_commit":"5e4bce438a4c2b27cf97989d4fd3462b3db2610b"},"previous_names":["g-k/pytest-aws"],"tags_count":12,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mozilla%2Ffrost","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mozilla%2Ffrost/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mozilla%2Ffrost/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mozilla%2Ffrost/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mozilla","download_url":"https://codeload.github.com/mozilla/frost/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247624119,"owners_count":20968824,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["pytest","security-audit","third-party"],"created_at":"2024-09-24T21:26:06.141Z","updated_at":"2025-04-09T18:19:24.465Z","avatar_url":"https://github.com/mozilla.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Frost\n\n[![PyPI version](https://badge.fury.io/py/frost.svg)](https://badge.fury.io/py/frost)\n[![Documentation](https://img.shields.io/badge/Docs-gh--pages-yellowgreen.svg)](https://mozilla.github.com/frost/)\n\n![frost snowman logo](docs/frost-snowman-logo.png)\n\nHTTP clients and a wrapper around\n[pytest](https://docs.pytest.org/en/latest/index.html) tests to verify\nthat third party services are configured correctly. For example:\n\n* Are our AWS DB snapshots publicly accessible?\n* Are there dangling DNS entries in Route53?\n\n## Usage\n\n### Installing\n\n1. Install [Python 3.8](https://www.python.org/downloads/)\n1. Run `git clone git@github.com:mozilla/frost.git; cd frost; make install`\n\n### Usage\n\n```console\n$ frost --help\nUsage: frost [OPTIONS] COMMAND [ARGS]...\n\n  FiRefox Operations Security Testing API clients and tests\n\nOptions:\n  --version  Show the version and exit.\n  --help     Show this message and exit.\n\n  Commands:\n    list  Lists available test filenames packaged with frost.\n    test  Run pytest tests passing all trailing args to pytest.\n\n$ frost test --help\nUsage: frost test [OPTIONS] [PYTEST_ARGS]...\n\n  Run pytest tests passing all trailing args to pytest.\n\n  Adds the pytest args:\n\n  -s to disable capturing stdout\n  https://docs.pytest.org/en/latest/capture.html\n\n  and frost specific arg:\n\n  --debug-calls to print AWS API calls\n\nOptions:\n  --help  Show this message and exit.\n```\n\n### Running\n\nTo fetch RDS resources from the cache or AWS API and check that\nbackups are enabled for DB instances for [the configured aws\nprofile](https://docs.aws.amazon.com/cli/latest/userguide/cli-config-files.html)\nnamed `default` in the `us-west-2` region\n\n\n1. find the test file path:\n\n```console\n$ frost list | grep rds\n./aws/rds/test_rds_db_instance_backup_enabled.py\n./aws/rds/test_rds_db_snapshot_encrypted.py\n./aws/rds/test_rds_db_instance_is_postgres_with_invalid_certificate.py\n./aws/rds/test_rds_db_instance_encrypted.py\n./aws/rds/test_rds_db_security_group_does_not_grant_public_access.py\n./aws/rds/test_rds_db_instance_not_publicly_accessible_by_vpc_sg.py\n./aws/rds/test_rds_db_instance_minor_version_updates_enabled.py\n./aws/rds/test_rds_db_instance_is_multiaz.py\n./aws/rds/test_rds_db_snapshot_not_publicly_accessible.py\n```\n\nNote: **packaged frost tests are relative to the frost install**\n\n1. run the test:\n\n```console\nfrost test aws/rds/test_rds_db_instance_backup_enabled.py --aws-profiles default\n```\n\nFrost adds the options:\n\n* `--aws-profiles` for selecting one or more AWS profiles to fetch resources for or the AWS default profile / `AWS_PROFILE` environment variable\n* `--aws-regions` for selecting one or more AWS regions to test as a CSV e.g. `us-east-1,us-west-2`. **defaults to all regions**\n* `--gcp-project-id` for selecting the GCP project to test. **Required for GCP tests**\n* `--offline` a flag to tell HTTP clients to not make requests and return empty params\n* [`--config`](#custom-test-config) path to test custom config file\n\nand produces output showing calls to the AWS API and failing for a DB\ninstance with backups disabled:\n\n```console\n============================================================ test session starts ============================================================\nplatform linux -- Python 3.8.2, pytest-6.0.2, py-1.9.0, pluggy-0.13.1\nrootdir: /home/gguthe/frost\nplugins: json-0.4.0, cov-2.10.0, html-1.20.0, metadata-1.10.0\ncollecting ... calling AWSAPICall(profile='default, region='ap-northeast-1', service='rds', method='describe_db_instances', args=[], kwargs={})\ncalling AWSAPICall(profile='default, region='ap-northeast-2', service='rds', method='describe_db_instances', args=[], kwargs={})\ncalling AWSAPICall(profile='default, region='ap-south-1', service='rds', method='describe_db_instances', args=[], kwargs={})\ncalling AWSAPICall(profile='default, region='ap-southeast-1', service='rds', method='describe_db_instances', args=[], kwargs={})\ncalling AWSAPICall(profile='default, region='ap-southeast-2', service='rds', method='describe_db_instances', args=[], kwargs={})\n...\ncalling AWSAPICall(profile='default, region='us-west-2', service='rds', method='list_tags_for_resource', args=[], kwargs={'ResourceName': 'arn:aws:rds:us-west-2:redacted:db:test-db-ro-dev1'})\ncollected 21 items\n\naws/rds/test_rds_db_instance_backup_enabled.py F....................\n\n================================================================= FAILURES ==================================================================\n____________________________________ test_rds_db_instance_backup_enabled[test-db-ro-dev1] ___________________________________________________\n\nrds_db_instance = {'AllocatedStorage': 250, 'AutoMinorVersionUpgrade': True, 'AvailabilityZone': 'us-east-1a', 'BackupRetentionPeriod': 0, ..\n.}\n\n    @pytest.mark.rds\n    @pytest.mark.parametrize(\n        \"rds_db_instance\", rds_db_instances_with_tags(), ids=get_db_instance_id,\n    )\n    def test_rds_db_instance_backup_enabled(rds_db_instance):\n\u003e       assert (\n            rds_db_instance[\"BackupRetentionPeriod\"] \u003e 0\n        ), \"Backups disabled for {}\".format(rds_db_instance[\"DBInstanceIdentifier\"])\nE       AssertionError: Backups disabled for test-db-ro-dev1\nE       assert 0 \u003e 0\n\naws/rds/test_rds_db_instance_backup_enabled.py:12: AssertionError\n========================================================== short test summary info ==========================================================\nFAILED aws/rds/test_rds_db_instance_backup_enabled.py::test_rds_db_instance_backup_enabled[test-db-ro-dev1] - AssertionError...\n======================================================= 2 failed, 21 passed in 14.32s =======================================================\n```\n\n#### IAM Policy for frost\n\nThe below policy will allow you to run all AWS tests in frost against all resources in your account.\n\n```json\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Sid\": \"PytestServicesReadOnly\",\n      \"Action\": [\n        \"autoscaling:DescribeLaunchConfigurations\",\n        \"cloudtrail:DescribeTrails\",\n        \"ec2:DescribeFlowLogs\",\n        \"ec2:DescribeInstances\",\n        \"ec2:DescribeSecurityGroups\",\n        \"ec2:DescribeSnapshotAttribute\",\n        \"ec2:DescribeSnapshots\",\n        \"ec2:DescribeVolumes\",\n        \"ec2:DescribeVpcs\",\n        \"elasticache:DescribeCacheClusters\",\n        \"elasticloadbalancing:DescribeLoadBalancers\",\n        \"es:DescribeElasticsearchDomains\",\n        \"es:ListDomainNames\",\n        \"iam:GenerateCredentialReport\",\n        \"iam:GetCredentialReport\",\n        \"iam:GetLoginProfile\",\n        \"iam:ListAccessKeys\",\n        \"iam:ListAttachedGroupPolicies\",\n        \"iam:ListAttachedRolePolicies\",\n        \"iam:ListAttachedUserPolicies\",\n        \"iam:ListGroupPolicies\",\n        \"iam:ListGroupsForUser\",\n        \"iam:ListMFADevices\",\n        \"iam:ListRolePolicies\",\n        \"iam:ListRoles\",\n        \"iam:ListUserPolicies\",\n        \"iam:ListUsers\",\n        \"rds:DescribeDbInstances\",\n        \"rds:DescribeDbSecurityGroups\",\n        \"rds:DescribeDbSnapshotAttributes\",\n        \"rds:DescribeDbSnapshots\",\n        \"rds:ListTagsForResource\",\n        \"redshift:DescribeClusterSecurityGroups\",\n        \"redshift:DescribeClusters\",\n        \"s3:GetBucketAcl\",\n        \"s3:GetBucketCORS\",\n        \"s3:GetBucketLogging\",\n        \"s3:GetBucketPolicy\",\n        \"s3:GetBucketVersioning\",\n        \"s3:GetBucketWebsite\",\n        \"s3:ListAllMyBuckets\",\n        \"s3:ListBucket\"\n      ],\n      \"Effect\": \"Allow\",\n      \"Resource\": \"*\"\n    }\n  ]\n}\n```\n\n#### Setting up GCP tests\n\n##### Enabling required API's for your project\n\n```\ngcloud [--project \u003cproject name\u003e] services enable bigquery-json.googleapis.com\ngcloud [--project \u003cproject name\u003e] services enable cloudresourcemanager.googleapis.com\ngcloud [--project \u003cproject name\u003e] services enable compute.googleapis.com\ngcloud [--project \u003cproject name\u003e] services enable sqladmin.googleapis.com\n```\n\n#### Setting up GSuite tests\n\nMake sure to have an OAuth2 app created and have the `client_secret.json` file in `~/.credentials` and then run:\n\n```\nmake setup_gsuite\n```\n\n### Caching\n\nThe AWS client will use AWS API JSON responses when available and save them using AWS profile, region, service name, service method, [botocore](http://botocore.readthedocs.io/) args and kwargs in the cache key to filenames with the format `.cache/v/pytest_aws:\u003caws profile\u003e:\u003caws region\u003e:\u003caws service\u003e:\u003cservice method\u003e:\u003cargs\u003e:\u003ckwargs\u003e.json` e.g.\n\n```\nhead .cache/v/pytest_aws:cloudservices-aws-stage:us-west-2:rds:describe_db_instances::.json\n{\n    \"DBInstances\": [\n        {\n            \"AllocatedStorage\": 5,\n            \"AutoMinorVersionUpgrade\": true,\n            \"AvailabilityZone\": \"us-west-2c\",\n            \"BackupRetentionPeriod\": 1,\n            \"CACertificateIdentifier\": \"rds-ca-2015\",\n            \"CopyTagsToSnapshot\": false,\n            \"DBInstanceArn\": \"arn:aws:rds:us-west-2:123456678901:db:test-db\",\n```\n\nThese files can be removed individually or all at once with [the pytest --cache-clear](https://docs.pytest.org/en/latest/cache.html#usage) option.\nThe cache can be disabled entirely with [the pytest -p no:cacheprovider](https://stackoverflow.com/questions/47744076/preventing-pytest-from-creating-cache-directories-in-pycharm).\n\n## Custom Test Config\n\nfrost adds a `--config` cli option for passing in a custom config file specific to tests within frost.\n\nThe example config in repo (`config.yaml.example`):\n```\nexemptions:\n  - test_name: test_ec2_instance_has_required_tags\n    test_param_id: i-0123456789f014c162\n    expiration_day: 2019-01-01\n    reason: ec2 instance has no owner\n  - test_name: test_ec2_security_group_opens_specific_ports_to_all\n    test_param_id: '*HoneyPot'\n    expiration_day: 2020-01-01\n    reason: purposefully insecure security group\nseverities:\n  - test_name: test_ec2_instance_has_required_tags\n    severity: INFO\n  - test_name: '*'\n    severity: ERROR\nregressions:\n  - test_name: test_ec2_security_group_opens_all_ports_to_all\n    test_param_id: '*mycustomgroup'\n    comment: this was remediated by ops team\naws:\n  admin_groups:\n    - \"Administrators\"\n  admin_policies:\n    - \"AWSAdminRequireMFA\"\n  user_is_inactive:\n    no_activity_since:\n      years: 1\n      months: 0\n    created_after:\n      weeks: 1\n  access_key_expires_after:\n    years: 1\n    months: 0\n  required_tags:\n    - Name\n    - Type\n    - App\n    - Env\n  required_amis:\n    - ami-00000000000000000\n    - ami-55555555555555555\n  # Allowed ports for the test_ec2_security_group_opens_specific_ports_to_all\n  # test for all instances\n  allowed_ports_global:\n    - 25\n  # Allowed ports for the test_ec2_security_group_opens_specific_ports_to_all\n  # test for specific instances. In this example, we are allowing ports 22\n  # and 2222 for all security groups that include the word 'bastion' in them.\n  allowed_ports:\n    - test_param_id: '*bastion'\n      ports:\n        - 22\n        - 2222\ngcp:\n  allowed_org_domains:\n    - mygsuiteorg.com\n  allowed_gke_versions:\n    - 1.15.12-gke.20\n    - 1.16.13-gke.401\n    - 1.17.9-gke.1504\n    - 1.18.6-gke.3504\n  # Allowed ports for the test_firewall_opens_any_ports_to_all\n  # test for all firewalls\n  allowed_ports_global:\n    - 25\n  # Allowed ports for the test_firewall_opens_any_ports_to_all\n  # test for specific firewalls. In this example, we are allowing ports 22\n  # and 2222 for all firewalls that include the word 'bastion' in them.\n  allowed_ports:\n    - test_param_id: '*bastion'\n      ports:\n        - 22\n        - 2222\ngsuite:\n  domain: 'example.com'\n  user_is_inactive:\n    no_activity_since:\n      years: 1\n      months: 0\n```\n\n### Test Exemptions\n\nfrost custom config format adds support for\nmarking test and test resource IDs as expected failures.\n\nThe keys for each exemption rule is:\n* test_name - Name of the test\n* test_param_id - test ID (usually an AWS resource ID) (prefix with `*` to turn into a regex matcher)\n* expiration_day - exception expiration day (as YYYY-MM-DD)\n* reason - exception reason\n\nThe config looks like:\n```\n...\nexemptions:\n  - test_name: test_ec2_instance_has_required_tags\n    test_param_id: i-0123456789f014c162\n    expiration_day: 2019-01-01\n    reason: ec2 instance has no owner\n  - test_name: test_ec2_security_group_opens_specific_ports_to_all\n    test_param_id: '*HoneyPot'\n    expiration_day: 2020-01-01\n    reason: purposefully insecure security group\n...\n```\n\n#### Enabling regex for test ID\n\nYou can prefix the test ID with a `*` to enable regex matching for the test ID. The `*` prefix will be stripped\noff, and the rest will be used as a regex.\n\nFor example:\n - `*foobar` becomes `foobar`\n - `*foo\\w+` becomes `foo\\w+`\n\nFor more information on Python's regex syntax see: [Regular Expression HOWTO](https://docs.python.org/3.4/howto/regex.html#regex-howto).\n\n**Note:** All regex rules are applied first. As well, the ordering of both regex and non-regex rules is top to bottom and the first one wins.\n\n\nWhen a json report is generated, the exemptions will show up in the\njson metadata as serialized markers:\n\n```json\npython -m json.tool report.json | grep -C 20 xfail\n...\n                        \"markers\": {\n                            \"ec2\": {\n                                \"name\": \"ec2\",\n                                \"args\": [],\n                                \"kwargs\": {}\n                            },\n                            \"parametrize\": {\n                                \"name\": \"parametrize\",\n                                \"args\": [\n                                    \"...skipped...\"\n                                ],\n                                \"kwargs\": [\n                                    \"...skipped...\"\n                                ]\n                            },\n                            \"xfail\": {\n                                \"name\": \"xfail\",\n                                \"args\": [],\n                                \"kwargs\": {\n                                    \"reason\": \"ec2 instance has no owner\",\n                                    \"strict\": true,\n                                    \"expiration\": \"2019-01-01\"\n                                }\n                            }\n                        },\n...\n```\n\n\n#### Test Severity\n\nfrost custom config format adds support for marking the severity of a certain test. A severity can be `INFO`, `WARN`, or `ERROR`.\n\nThese do not modify pytest results (pass, fail, xfail, skip, etc.).\n\nThe config looks like:\n\n```\n...\nseverities:\n  - test_name: test_ec2_instance_has_required_tags\n    severity: INFO\n  - test_name: '*'\n    severity: ERROR\n...\n```\n\nAnd results in a severity and severity marker being included in the\njson metadata:\n\n```console\nfrost test -s --aws-profiles stage --aws-require-tags Name Type App Stack -k test_ec2_instance_has_required_tags --config config.yaml.example --json=report.json\n...\n```\n\n```json\npython -m json.tool report.json\n{\n    \"report\": {\n        \"environment\": {\n            \"Python\": \"3.6.2\",\n            \"Platform\": \"Darwin-15.6.0-x86_64-i386-64bit\"\n        },\n        \"tests\": [\n            {\n...\n                \"metadata\": [\n                    {\n...\n                    \"markers\": {\n...\n                            \"severity\": {\n                                \"name\": \"severity\",\n                                \"args\": [\n                                    \"INFO\"\n                                ],\n                                \"kwargs\": {}\n                            }\n                        },\n...\n                        \"severity\": \"INFO\",\n                        \"unparametrized_name\": \"test_ec2_instance_has_required_tags\"\n                    }\n...\n```\n\n### AWS Config\n\nfrost has a suite of AWS tests. This section of the custom config includes configuration options specific\nto these tests.\n\nThe config looks like:\n```\n...\naws:\n  # Relative time delta for test_iam_user_is_inactive. no_activity_since will be used as the failure marker,\n  # so in this example any user that hasn't had any activity for a year will be marked as a \"failure\". created_after\n  # is used as a grace period, so in this case any user that was created within the last week will be automatically\n  # pass this test.\n  user_is_inactive:\n    no_activity_since:\n      years: 1\n      months: 0\n    created_after:\n      weeks: 1\n  # Required tags used within the test_ec2_instance_has_required_tags test\n  required_tags:\n    - Name\n    - Type\n    - App\n    - Env\n  # Allowed ports for the test_ec2_security_group_opens_specific_ports_to_all\n  # test for all instances\n  allowed_ports_global:\n    - 25\n  # Allowed ports for the test_ec2_security_group_opens_specific_ports_to_all\n  # test for specific instances. In this example, we are allowing ports 22\n  # and 2222 for all security groups that include the word 'bastion' in them.\n  allowed_ports:\n    - test_param_id: '*bastion'\n      ports:\n        - 22\n        - 2222\n...\n```\n\n### GSuite Config\n\nfrost has a suite of GSuite tests. This section of the\ncustom config includes configuration options specific to these tests.\n\n**Make sure to [setup GSuite](#setting-up-gsuite-tests) before running GSuite tests**\n\nThe config looks like:\n```\ngsuite:\n  # The specific GSuite domain to test.\n  domain: 'example.com'\n  # Relative time delta for test_admin_user_is_inactive. no_activity_since will be used as the failure marker,\n  # so in this example any user that hasn't had any activity for a year will be marked as a \"failure\".\n  user_is_inactive:\n    no_activity_since:\n      years: 1\n      months: 0\n```\n\n### Test Accuracy\n\nThere are two important things to note about `frost` tests that may be different from your expectations.\n\nFirst, the focus is on \"actionable results\". This plays out as an attempt to reduce false\npositives by trying to filter out unused resources. An example of this can be seen by looking at\nany of the security group tests, where we are skipping any security groups that are not attached to a resource.\n\nSecond, there are some tests that make naive assumptions instead of trying to capture the complexities\nof the system. The current best example of this is all IAM tests that relate to \"admin\" users. How we\nare determining what an user or role is an admin is based simply off substring matching on the policies\nattached. This obviously has a high chance of false negatives.\n\n## Development\n\n### Goals\n\n1. replace one-off scripts for each check\n1. share checks with other organizations\n1. consolidate bugs in one place (i.e. one thing to update)\n1. in pytest use a known existing framework for writing checks\n1. be vendor agnostic e.g. support checks across cloud providers or in hybrid environments or competing services\n1. cache and share responses to reduce third party API usage (i.e. lots of tests check AWS security groups so fetch them once)\n1. provide a way to run a single test or subset of tests\n1. focus on actionable results (see [test accuracy](#test-accuracy) for more information)\n\n### Non-Goals\n\n1. Invent a new DSL for writing expectations (use pytest conventions)\n1. Verify how third party services or their client libraries work\n   (e.g. don't answer \"Does GET / on the CRUD1 API return 400 when\n   query param `q` is `$bad_value`?\")\n\n### Design\n\nCurrently this is a monolithic pytest package, but should eventually\n[be extracted into a pytest plugin](https://github.com/mozilla/frost/issues/3) and with [separate dependent\npytest plugins for each service](https://github.com/mozilla/frost/issues/4).\n\nAPI responses should fit on disk and in memory (i.e. don't use this\nfor log processing or checking binaries for malware), and be safe to\ncache for minutes, hours, or days (i.e. probably don't use this for\nmonitoring a streaming API) (NB: [bug for specifying data\nfreshness](https://github.com/mozilla/frost/issues/5)).\n\nAdditionally we want:\n\n* data fetching functions in a `resources.py`\n* data checking and test helpers in a `helpers.py`\n* prefix test files with `test_`\n* doctests for non test files (e.g. `helpers.py`, `resources.py`, `client.py`)\n  * tests that depend on external IO or the runtime environment (env vars, file system, HTTP) to use the prefix `meta_test_` (and probably `mock` or `pytest.monkeypatch`)\n    * JSON fixtures for anonymized cached http call in `example_cache/v/`\n* tests to have pytest markers for any services they depend on for data\n* HTTP clients should be read only and use read only credentials\n* running a test should not modify services\n\n#### File Layout\n\n```console\nfrost\n...\n├── example_cache\n│   └── v\n│       ├── cache\n│       │   └── lastfailed\n│       ├── pytest_aws:example-account:us-east-1:ec2:describe_instances::.json\n│       ├── pytest_aws:example-account:us-east-1:ec2:describe_security_groups::.json\n...\n├── \u003cthird party service A\u003e\n│   ├── client.py\n│   ├── conftest.py\n│   ├── meta_test_client.py\n│   ├── \u003csubservice A (optional)\u003e\n│   │   ├── __init__.py\n│   │   ├── helpers.py\n│   │   ├── resources.py\n│   │   ├── ...\n│   │   └── test_ec2_security_group_all_ports.py\n│   ├── \u003csubservice b (optional)\u003e\n│   │   ├── __init__.py\n│   │   ├── resources.py\n│   │   ├── ...\n│   │   └─ test_s3_bucket_web_hosting_disabled.py\n└── \u003cthird party service B\u003e\n    ├── __init__.py\n    ├── conftest.py\n    ├── helpers.py\n    ├── resources.py\n    └── test_user_has_escalation_policy.py\n```\n\n### Adding an example test\n\nLet's write a test to check that http://httpbin.org/ip returns an AWS IP:\n\n1. create a file `httpbin/test_httpbin_ip.py` with the contents:\n\n```python\nimport itertools\nimport ipaddress\nimport pytest\nimport json\nimport urllib.request\n\n\ndef get_httpbin_ips():\n    # IPs we always want to test\n    ips = [\n        '127.0.0.1',\n        '13.58.0.0',\n    ]\n\n    req = urllib.request.Request('http://httpbin.org/ip')\n\n    with urllib.request.urlopen(req) as response:\n        body = response.read().decode('utf-8')\n        ips.append(json.loads(body).get('origin', None))\n\n    return ips\n\n\ndef get_aws_ips():\n    req = urllib.request.Request('https://ip-ranges.amazonaws.com/ip-ranges.json')\n\n    with urllib.request.urlopen(req) as response:\n        body = response.read().decode('utf-8')\n        return json.loads(body)['prefixes']\n\n\n@pytest.mark.httpbin\n@pytest.mark.aws_ip_ranges\n@pytest.mark.parametrize(\n    ['ip', 'aws_ip_ranges'],\n    zip(get_httpbin_ips(), itertools.repeat(get_aws_ips())))\ndef test_httpbin_ip_in_aws(ip, aws_ip_ranges):\n    for aws_ip_range in aws_ip_ranges:\n        assert ipaddress.IPv4Address(ip) not in ipaddress.ip_network(aws_ip_range['ip_prefix']), \\\n          \"{0} is in AWS range {1[ip_prefix]} region {1[region]} service {1[service]}\".format(ip, aws_ip_range)\n```\n\nNotes:\n\n* we add two data fetching functions that return lists that we can zip into tuples for [the pytest parametrize decorator](https://docs.pytest.org/en/latest/parametrize.html#pytest-mark-parametrize-parametrizing-test-functions)\n* we add markers for the services we're fetching data from\n\n\n1. Running `frost test` with the test file explicitly included we see that one of the IPs is an AWS IP:\n\n```console\nfrost test httpbin/test_httpbin_ip_in_aws.py\nplatform darwin -- Python 3.6.2, pytest-3.3.2, py-1.5.2, pluggy-0.6.0\nmetadata: {'Python': '3.6.2', 'Platform': 'Darwin-15.6.0-x86_64-i386-64bit', 'Packages': {'pytest': '3.3.2', 'py': '1.5.2', 'pluggy': '0.6.0'}, 'Plugins': {'metadata': '1.5.1', 'json': '0.4.0', 'html': '1.16.1'}}\nrootdir: /Users/gguthe/frost, inifile:\nplugins: metadata-1.5.1, json-0.4.0, html-1.16.1\ncollected 3 items\n\nhttpbin/test_httpbin_ip_in_aws.py .F.                                                                                               [100%]\n\n================================================================ FAILURES =================================================================\n____________________________________________ test_httpbin_ip_in_aws[13.58.0.0-aws_ip_ranges1] _____________________________________________\n\nip = '13.58.0.0'\naws_ip_ranges = [{'ip_prefix': '13.32.0.0/15', 'region': 'GLOBAL', 'service': 'AMAZON'}, {'ip_prefix': '13.35.0.0/16', 'region': 'GLOB...on': 'us-west-1', 'service': 'AMAZON'}, {'ip_prefix': '13.57.0.0/16', 'region': 'us-west-1', 'service': 'AMAZON'}, ...]\n\n    @pytest.mark.httpbin\n    @pytest.mark.aws_ip_ranges\n    @pytest.mark.parametrize(\n        ['ip', 'aws_ip_ranges'],\n        zip(get_httpbin_ips(), itertools.repeat(get_aws_ips())),\n        # ids=lambda ip: ip\n        )\n    def test_httpbin_ip_in_aws(ip, aws_ip_ranges):\n        for aws_ip_range in aws_ip_ranges:\n\u003e           assert ipaddress.IPv4Address(ip) not in ipaddress.ip_network(aws_ip_range['ip_prefix']), \\\n              \"{0} is in AWS range {1[ip_prefix]} region {1[region]} service {1[service]}\".format(ip, aws_ip_range)\nE           AssertionError: 13.58.0.0 is in AWS range 13.58.0.0/15 region us-east-2 service AMAZON\nE           assert IPv4Address('13.58.0.0') not in IPv4Network('13.58.0.0/15')\nE            +  where IPv4Address('13.58.0.0') = \u003cclass 'ipaddress.IPv4Address'\u003e('13.58.0.0')\nE            +    where \u003cclass 'ipaddress.IPv4Address'\u003e = ipaddress.IPv4Address\nE            +  and   IPv4Network('13.58.0.0/15') = \u003cfunction ip_network at 0x107cf66a8\u003e('13.58.0.0/15')\nE            +    where \u003cfunction ip_network at 0x107cf66a8\u003e = ipaddress.ip_network\n\nhttpbin/test_httpbin_ip_in_aws.py:43: AssertionError\n=================================================== 1 failed, 2 passed in 15.69 seconds ===================================================\n```\n\nNote: marking tests as expected failures with `@pytest.mark.xfail` can hide data fetching errors\n\nTo improve this we could:\n\n1. Add parametrize ids so it's clearer which parametrize caused test failures\n1. Add directions about why it's an issue and how to fix it or what the associated risks are\n\nAs we add more tests we can:\n\n1. Move the JSON fetching functions to `\u003cservice name\u003e/resources.py` files and import them into the test\n1. Move the fetching logic to a shared library `\u003cservice name\u003e/client.py` and save to the pytest cache\n1. Add a `\u003cservice name\u003e/conftest.py` and register the service's marks in a `pytest_configure` to resolve some warnings\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmozilla%2Ffrost","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmozilla%2Ffrost","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmozilla%2Ffrost/lists"}