qwed-infra provides four guards to verify different aspects of your infrastructure. Every guard’s to_diagnostic() method converts its result into a unified InfraDiagnosticResult with an audit trace and proof reference. As of v0.3.0, every guard also exposes a to_verification_context() method that runs the verification and emits a portable Verification Context v1.0 document.
1. IamGuard
Engine: Python matching on the concrete request, combined with the Z3 theorem prover IamGuard decides whether an AWS IAM policy allows a concrete request. From v0.4.0 it decides every action, resource and condition match in Python on the request values, following the AWS policy language, and Z3 combines those outcomes under Deny precedence. An element outside the modelled policy language makes the whole resultUNVERIFIABLE, and a statement the guard can’t evaluate does so whenever the decision depends on it.
Capabilities
- Deny overrides: An explicit
Denyoverrides anAllow, regardless of statement order. - Matching: Actions match case-insensitively.
?matches exactly one character and*any run of characters. In a resource ARN with colons, both stay within one colon-separated segment, except a*that ends the last segment. Condition key names match case-insensitively. Case folding is ASCII only. - Condition operators: The
String*,Arn*,Numeric*andDate*families,IpAddress,NotIpAddress,Bool,Nulland the...IfExistsforms, with AWS multi-value semantics. - Absent keys: A condition on a key the request doesn’t carry is false, except for a negated operator (
StringNotEquals,NotIpAddressand the other...Not...forms) or an...IfExistsoperator, where it is true.Nulltests whether the key is present. - Policy variables:
${aws:username}and the${*},${?}and${$}escapes are substituted in resources and inString*andArn*condition values when the policyVersionis2012-10-17. In aNumeric*,Date*,Boolor IP condition value a policy variable is not substituted, and the condition can’t be evaluated. With any other version, or none, they are literal text, as in AWS. - Least privilege:
verify_least_privilege(policy)returnsallowed=Truewhen the policy grants full access. It judges this from the patterns, not by matching a literal*request. An Allow counts, whatever its condition, when it has anActionpattern and aResourcepattern each made only of*,?and:with at least one*(such as*:*or?*, orarn:*for a resource). A Deny counts only when it has no condition and names every action and every resource with a pattern of*alone, so a conditional guard-rail such as “deny without MFA” doesn’t make an admin policy compliant. An Allow whose coverage the guard can’t tell, such as a wildcarded service prefix (a*) or a wildcarded partition or service in a resource ARN, makes the resultUNVERIFIABLE.
What is UNVERIFIABLE
Every condition has three outcomes: it matches, it doesn’t match, or the guard can’t evaluate it. When the decision depends on a statement the guard can’t evaluate, the result isUNVERIFIABLE, for Allow and Deny statements alike. A Deny that applies still decides the request when another statement can’t be evaluated. The guard can’t evaluate:
- An unsupported operator, including the
ForAnyValue:andForAllValues:set operators. - A malformed policy value, even when its key is absent from the request. Numbers must be decimal digits with an optional minus sign and fraction, dates W3C dates, W3C date-times with a zone or epoch seconds, and booleans
trueorfalse. - A multi-valued request key, a request value of
nullor an empty list, an unresolved policy variable, or operators or keys that differ only in case. - Non-ASCII text compared case-insensitively.
- A resource match that needs a wildcard to cross a colon, a policy variable before the fifth colon of a resource ARN, or a wildcard in its service segment.
- IP values that aren’t addresses or CIDRs, including netmask forms, and IPv4-mapped or scoped IPv6 request addresses.
UNVERIFIABLE when a statement uses NotAction, NotResource or NotPrincipal, a Principal other than * or {"AWS": "*"}, an element outside the policy language (such as a misspelt Conditon), an empty or missing Action or Resource, or an Effect other than Allow or Deny. So is a policy without Statement, with a top-level element other than Version, Id and Statement, or with a Version other than 2012-10-17 or 2008-10-17. A single-object Statement is accepted. A Z3 unknown answer is also UNVERIFIABLE, not a proven denial.
Input bounds
IamGuard refuses a policy or request over these bounds asUNVERIFIABLE before it evaluates anything:
Policy variable substitution has two more bounds, checked while matching. A pattern longer than 8,192 characters after substitution, or substitution that adds more than 131,072 characters across one request, can’t be evaluated. Like any other statement the guard can’t evaluate, it makes the result
UNVERIFIABLE when the decision depends on it.
On an unexpected error, IamGuard records only the exception type in error, so no traceback or host path reaches diagnostics or Verification Context evidence.
API
Diagnostic Mapping
to_verification_context() admits only an allowed result. A proven denial is BLOCKED.
2. NetworkGuard
Engine: NetworkX (Graph Theory) NetworkGuard builds a directed graph from a topology of subnets, route tables and security groups, and uses graph traversal to verify reachability. From v0.4.0 it models an explicit set of inputs and returnsUNVERIFIABLE for anything else, instead of refusing only a list of known constructs.
Capabilities
- Public Access Check: Validates if a path exists from
Internetto a destination subnet.- Path:
Internet -> IGW -> Route Table -> Subnet -> Security Group.
- Path:
- Port Verification: Checks whether a port is open to the internet through the security group rules.
- Internet ranges: Split ranges whose union covers
0.0.0.0/0or::/0(for example0.0.0.0/1plus128.0.0.0/1) count as the internet, for security group rules and routes. An IPv4 route doesn’t pair with an IPv6-only rule.
Modelled topology
The result is
UNVERIFIABLE with unsupported_topology=True for any other key or route target, so NAT gateways, VPC peering, NACLs, transit gateways, endpoints, protocol-scoped rules (protocol, ip_protocol), prefix lists (prefix_list_id) and security group references (source_security_group_id) are refused whatever they are called. The same applies to:
- A rule without a valid
cidr, a rule mixingportwith a range, a reversed range, a one-sided-1port sentinel, or ports that aren’t ASCII integers in range. - Duplicate subnet ids, more than one route table for a subnet, or a route table without a
subnet_id. - A subnet that names an undeclared security group.
- A queried port that isn’t an integer in range.
- A private IP address as the source. Only reachability from
"internet"is graph-modelled.
API
resources, subnets missing id keys, and similar) map to a fail-closed BLOCKED document instead of raising an exception.
Diagnostic Mapping
3. CostGuard
Engine: Deterministic Arithmetic & Pricing Catalog CostGuard estimates the monthly cost of your infrastructure definition before deployment using an embedded, static price catalogue with Decimal arithmetic (no floating-point rounding errors). An instance costs its hourly price timescount times 730 hours. A volume costs its GB-month price times size_gb times count.
Price catalogue
From v0.4.0, instance and volume prices are kept in separate tables, so a volume type used as an instance type is an unknown instance type:CostGuard.INSTANCE_PRICING: EC2 and RDS instance types, in USD per instance-hour.CostGuard.VOLUME_PRICING: EBS volume types, in USD per GB-month at us-east-1 list prices:gp20.10,gp30.08,st10.045 andsc10.015.
us-east-1 only (CostGuard.PRICING_REGION). These replace CostGuard.PRICING_CATALOG.
Capabilities
- Budget enforcement: Compares the exact total with the exact budget, so an overrun of less than a cent is not within budget. The published
total_monthly_costis rounded up to the cent andbudgetdown. - Per-resource breakdown:
breakdowngives the monthly cost of each instance and volume. - Fail-closed unknowns: The estimate is incomplete (
has_unknown_types=True), and the resultBLOCKED, when any of these is present:- An instance or volume type that isn’t in the catalogue, or a missing type.
standard(magnetic) volumes aren’t priced, because their per-I/O-request charge can’t be known before deployment.io1andio2aren’t priced either. - A
countorsize_gbthat isn’t a positive integer. - Provisioned
iopsorthroughputthe catalogue can’t price: above thegp3baseline of 3000 IOPS or 125 MiB/s, or on any other volume type. - Any entry in the model’s
unmodelledlist, whichTerraformParserfills with declarations it does not model. If you build the resource dictionary yourself, list anything you leave out inunmodelled.
- An instance or volume type that isn’t in the catalogue, or a missing type.
VERIFIED diagnostic records the figures the decision was made on in its developer fields and proof evidence: exact_total_monthly_cost, exact_budget, pricing_region and pricing_catalogue_sha256 (a content hash of the price tables). to_diagnostic() re-checks the decision on the exact figures and returns BLOCKED when they don’t agree with within_budget or when the estimate was priced with a different catalogue.
API
BLOCKED document instead of raising an exception.
Diagnostic Mapping
4. ArtifactBoundaryGuard
Engine: File system scanning + TOML build config validation ArtifactBoundaryGuard is a release gate that verifies a Python package’s source tree andpyproject.toml build configuration before publishing. It ensures that no secrets, debug artifacts, or unintended files leak into the distribution.
Capabilities
- Secret Detection: Scans for
.pem,.key,.env, credential files, and other sensitive patterns in the package surface. - Debug Artifact Detection: Flags test files (
test_*.py), notebooks (*.ipynb), and debug directories (__pycache__,.git) included in the package. - Build Config Validation: Parses
[tool.hatch.build.targets.wheel]to confirm the package boundary is explicit. Blocks if the config is missing, invalid, or doesn’t reference the expected package name. - Other hatchling inputs (v0.4.0): Checks the other inputs known to change what hatchling ships in the wheel or to run project code at build time, and blocks what it doesn’t model. See Hatchling inputs.
- Disclosure Risk Detection: Flags project-structure files (
.gitignore,.dockerignore) that could leak internal conventions. - Fail-Closed on Missing TOML Parser: If neither
tomllibnortomliis available, every package isBLOCKED.
API
package_dir, so a caller cannot scan one directory while checking the wheel configuration of another. Symlink escapes, symlink loops, non-string build backends, and wheel entries outside the scanned boundary map to a fail-closed BLOCKED document.
Hatchling inputs
From v0.4.0, ArtifactBoundaryGuard blocks a package when its project has any of these:- A
hatch.tomlfile, which hatchling merges over[tool.hatch], or aPKG-INFOfile in the project root. [project] dynamicfields other thanversion.[build-system]keys other thanrequiresandbuild-backend(backend-pathlets the project supply its own backend).- A build requirement other than
hatchlingwith public PEP 440 version specifiers and an optional marker, in printable ASCII. - Root-level modules, namespace directories or programs named like standard library, build tool or interpreter names (such as
pip.py,argparse.py,org/orpython.bat). - Context formatting (
{env:...},{root}) in dependency strings. [tool.hatch.build]options that apply to every target and add files or run code (such asinclude,force-include,sources,packagesorhooks).- Sdist options that add or remap files (
force-include,sources,hooks), becausepython -m buildbuilds the wheel from the sdist. - Wheel options the guard doesn’t model (such as
shared-data,extra-metadata,sourcesorhooks), and wheelforce-includeeven withonly-packages(reported asmissing_control; every other input here isunknown_boundary). - A version source other than
regex, a versionpaththrough a symlink, a hidden file or directory, or outside the project root, and[tool.hatch.metadata]hooks. [project]readme files other than plainREADME*files in the project root, or license files other than plainLICENSE*,LICENCE*,COPYING*,NOTICE*orAUTHORS*files there. Symlinks and names that match a sensitive file pattern are refused.
Diagnostic Mapping
TerraformParser and unmodelled declarations
TerraformParser().parse_directory(path) reads the .tf files in one directory into a model with instances, policies, subnets, security_groups, volumes and, from v0.4.0, unmodelled. It models aws_instance, aws_iam_policy and aws_ebs_volume, and it records or refuses every other resource block instead of dropping it.
unmodelled is a list of {"address", "reason"} entries. The parser adds one for:
- A resource type it does not model.
- An instance or volume that uses
for_eachordynamic. - An
aws_instancewithoutroot_block_device, because its implicit root volume takes its size and type from the AMI.
BLOCKED while unmodelled has any entry. An aws_ebs_volume without size keeps size_gb empty, so CostGuard refuses to price it. The parser also carries count, iops and throughput on volumes and models root_block_device and ebs_block_device on an instance as volumes.
The parser raises ParseError, with the full list of errors, when:
- The path is not a directory, or the directory has no
.tffiles. - The directory holds
.tf.jsonfiles or Terraform override files (override.tf,*_override.tf). - The configuration calls a module.
- A
.tffile fails to parse. Files are read as UTF-8 on every platform. - An unmodelled resource may grant access: any
aws_iam_*type, or a type, attribute or block whose name containspolic,principal,permission,grantorauthoriz, or hasaclorrolesas an underscore-separated word.tagsmaps are not searched. - A policy document uses
NotAction,NotResourceorNotPrincipal, or holds HCL template directives (%{...}) or unresolved interpolation in its keys or values.
Verification Context documents
Every guard’sto_verification_context() method returns a VerificationContextDocument: a portable, JSON-serializable trust artifact that records what was verified, by whom, with what proof, and whether a downstream system should admit or deny. Use it when a verification decision has to travel beyond your process: CI/CD gates, release pipelines, and audit logs.
Guards compute from raw inputs
to_verification_context() takes raw verification inputs, never a pre-computed result object. Each guard runs its own deterministic solver internally before emitting the document. A result-accepting signature would be forgeable: a caller could fabricate a positive result and mint an ADMIT decision. formal_statement is keyword-only and required on every guard:
Attestation trust boundary
AVERIFIED result produces an ADMIT decision only when accompanied by a cryptographically valid ES256 (ECDSA P-256) JWT attestation. Validation checks the signature, issuer, expiry, and revocation status, plus binding to the exact claim and evidence: the token’s status must match, its query_hash must equal sha256(formal_statement), and its proof_hash must equal the diagnostic’s proof_ref. A token minted for one statement can never admit a different one.
Arbitrary non-empty attestation strings no longer grant ADMIT. They are rejected as forged tokens and produce BLOCKED.
Mint a valid token with mint_diagnostic_attestation(), which binds the token to a VERIFIED diagnostic’s own evidence commitment:
mint_diagnostic_attestation() and the lower-level create_verification_attestation() return an AttestationResult, never None. Check .is_issued before using .token: BLOCKED means signing failed, UNVERIFIABLE means the cryptography/pyjwt packages are unavailable.
Attestations are self-signed by the guard process with an ephemeral key and validated at the admission boundary. Multi-replica deployments require shared signing keys.
Verdict and admission mapping
The document is fail-closed by construction: anything that is not proven isDENY.
Malformed inputs at any VC boundary (invalid status values, non-dict developer fields, malformed topology, policy, budget, or package inputs) also map to
BLOCKED/DENY documents instead of exceptions.