From 8de7d9e6cacd81c1ee2f74193fa0c00e168bf2aa Mon Sep 17 00:00:00 2001
From: Thomas Sudeep Benardo <36351384+be-thomas@users.noreply.github.com>
Date: Mon, 26 Oct 2026 06:57:24 +0530
Subject: [PATCH 1/4] Document the IR and support the Terraform 1.x
configuration language
Schema 0.2 adds terraform metadata, preserved top-level blocks, detected
language features and min_version. The parser now reads .tf.json alongside
native HCL and preserves moved, import, removed, check, ephemeral, action and
unknown top-level blocks instead of dropping them. pkg/tfversion maps detected
features and required_version constraints to the oldest release that accepts
the input.
Emitters report every construct they cannot convert through stable W_* codes,
including preserved blocks, backend and cloud settings, conditions and variable
validations. Generated TypeScript is unchanged.
Adds docs/IR.md as the IR reference and docs/TERRAFORM-VERSIONS.md covering
support for Terraform 1.0 through 1.17, release history and the feature
registry.
---
README.md | 31 +-
docs/ARCHITECTURE.md | 39 +-
docs/CONFORMANCE.md | 17 +
docs/IR.md | 608 ++++++++++++++++++++++++
docs/ROADMAP.md | 8 +-
docs/TERRAFORM-VERSIONS.md | 253 ++++++++++
go.mod | 2 +-
pkg/emitters/awscdk/emitter.go | 1 +
pkg/emitters/awscdk/emitter_test.go | 94 ++++
pkg/emitters/pulumi/emitter.go | 1 +
pkg/emitters/pulumi/emitter_test.go | 94 ++++
pkg/emitters/warn.go | 209 +++++++++
pkg/emitters/warn_test.go | 178 +++++++
pkg/engine/engine_test.go | 5 +-
pkg/ir/graph_test.go | 235 ++++++++++
pkg/ir/types.go | 87 +++-
pkg/parsers/hcl/body.go | 316 +++++++++++++
pkg/parsers/hcl/corpus_test.go | 69 +++
pkg/parsers/hcl/json.go | 141 ++++++
pkg/parsers/hcl/json_test.go | 396 ++++++++++++++++
pkg/parsers/hcl/parser.go | 695 ++++++++++++++--------------
pkg/parsers/hcl/preserve.go | 86 ++++
pkg/parsers/hcl/preserve_test.go | 444 ++++++++++++++++++
pkg/parsers/hcl/schema.go | 59 +++
pkg/parsers/hcl/terraform.go | 191 ++++++++
pkg/parsers/hcl/versions_test.go | 421 +++++++++++++++++
pkg/tfversion/constraint.go | 96 ++++
pkg/tfversion/constraint_test.go | 79 ++++
pkg/tfversion/features.go | 520 +++++++++++++++++++++
pkg/tfversion/features_test.go | 179 +++++++
pkg/tfversion/version.go | 123 +++++
pkg/tfversion/version_test.go | 60 +++
32 files changed, 5363 insertions(+), 374 deletions(-)
create mode 100644 docs/IR.md
create mode 100644 docs/TERRAFORM-VERSIONS.md
create mode 100644 pkg/emitters/awscdk/emitter_test.go
create mode 100644 pkg/emitters/pulumi/emitter_test.go
create mode 100644 pkg/emitters/warn.go
create mode 100644 pkg/emitters/warn_test.go
create mode 100644 pkg/parsers/hcl/body.go
create mode 100644 pkg/parsers/hcl/corpus_test.go
create mode 100644 pkg/parsers/hcl/json.go
create mode 100644 pkg/parsers/hcl/json_test.go
create mode 100644 pkg/parsers/hcl/preserve.go
create mode 100644 pkg/parsers/hcl/preserve_test.go
create mode 100644 pkg/parsers/hcl/schema.go
create mode 100644 pkg/parsers/hcl/terraform.go
create mode 100644 pkg/parsers/hcl/versions_test.go
create mode 100644 pkg/tfversion/constraint.go
create mode 100644 pkg/tfversion/constraint_test.go
create mode 100644 pkg/tfversion/features.go
create mode 100644 pkg/tfversion/features_test.go
create mode 100644 pkg/tfversion/version.go
create mode 100644 pkg/tfversion/version_test.go
diff --git a/README.md b/README.md
index 15459b1..dfb2ae7 100644
--- a/README.md
+++ b/README.md
@@ -15,10 +15,10 @@ One parser. One IR. Zero lock-in.
[](#-timeline)
[](#-contributing)
-[](https://developer.hashicorp.com/terraform/language)
+[](docs/TERRAFORM-VERSIONS.md)
[](https://aws.amazon.com/cdk/)
[](https://www.pulumi.com/)
-[](docs/ARCHITECTURE.md#the-ir-contract)
+[](docs/IR.md)
[](https://go.dev)
@@ -27,7 +27,7 @@ One parser. One IR. Zero lock-in.
-[π Playground](playground/) Β· [π¦ Quick Start](#-quick-start) Β· [πΊοΈ Roadmap](docs/ROADMAP.md) Β· [π§ How It Works](#-how-it-works) Β· [π§± Architecture](docs/ARCHITECTURE.md) Β· [π§ͺ Conformance](docs/CONFORMANCE.md) Β· [π€ Contribute](CONTRIBUTING.md)
+[π Playground](playground/) Β· [π¦ Quick Start](#-quick-start) Β· [πΊοΈ Roadmap](docs/ROADMAP.md) Β· [π§ How It Works](#-how-it-works) Β· [π§± Architecture](docs/ARCHITECTURE.md) Β· [π IR Reference](docs/IR.md) Β· [π§ Version Support](docs/TERRAFORM-VERSIONS.md) Β· [π§ͺ Conformance](docs/CONFORMANCE.md) Β· [π€ Contribute](CONTRIBUTING.md)
@@ -160,14 +160,19 @@ Open `http://localhost:8080`, paste Terraform, get TypeScript. **No backend.**
## π§ How It Works
+Terraform **1.0β1.17** configuration parses in both syntaxes; conversion covers
+a documented subset of it. Anything outside that subset is preserved in the IR
+and reported as a coded warning, never silently dropped.
+
```text
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β Terraform β β Universal β β Dependency β β Native TS β
β HCL β βββΆ β IR β βββΆ β DAG β βββΆ β emitters β
-β .tf / .tfvarsβ β JSON-shaped β β topo-sorted β β CDK / Pulumi β
+β.tf / .tf.jsonβ β JSON-shaped β β topo-sorted β β CDK / Pulumi β
ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ ββββββββββββββββ
β² β² β² β²
hcl/v2 parser resources+vars Kahn's algorithm JSON mappings
+ HCL + JSON + preserved blocks
```
| Parse | pkg/parsers/hcl |
-Reads resource, data, variable, locals, output, module, provider blocks into the IR. |
+Reads native HCL and JSON (.tf and .tf.json) for every Terraform 1.0β1.17 top-level block. Constructs without a target mapping are preserved, never dropped β see version support. |
| Resolve | @@ -302,7 +307,7 @@ Add it to [`pkg/mappings/aws.json`](pkg/mappings/aws.json), rebuild, done. ```json { - "version": "0.1", + "version": "0.2", "resources": [ { "id": "aws_vpc.main", @@ -311,10 +316,14 @@ Add it to [`pkg/mappings/aws.json`](pkg/mappings/aws.json), rebuild, done. "attributes": { "cidr_block": { "kind": "string", "literal": "10.0.0.0/16" } } } ], - "edges": [{ "from": "aws_vpc.main", "to": "aws_subnet.public", "kind": "reference" }] + "min_version": "1.0.0", + "edges": [{ "from": "aws_subnet.public", "to": "aws_vpc.main", "kind": "reference" }] } ``` +`from` depends on `to`. Every field, value kind and guarantee is documented in +[docs/IR.md](docs/IR.md). + --- @@ -356,7 +365,7 @@ See [docs/CONFORMANCE.md](docs/CONFORMANCE.md) for the L0βL4 oracle design and | Milestone | Date | Highlights | State | |:--|:--|:--|:--:| | **Foundation** | Oct 2026 | HCL parser Β· IR Β· DAG Β· CDK + Pulumi emitters Β· WASM playground | β | -| **v0.1 Public Alpha** | Nov 2026 | Docs Β· tests Β· CI Β· GitHub Pages playground | π§ | +| **v0.1 Public Alpha** | Nov 2026 | Docs incl. [IR](docs/IR.md) & [version](docs/TERRAFORM-VERSIONS.md) references Β· tests Β· CI Β· GitHub Pages playground | π§ | | **v0.2 Depth** | Dec 2026 | Data sources Β· `locals` Β· richer L2 mappings | β³ | | **v0.3 Scale** | Q1 2027 | Modules Β· `count` / `for_each` Β· multi-file imports | β³ | | **v1.0 Stable** | Q2 2027 | CloudFormation + Terraform backends Β· plugin API | π― | @@ -383,11 +392,13 @@ OpenIaC/ βββ internal/conformance/ Collector and conformance layers βββ pkg/ β βββ ir/ Universal graph + topological sort -β βββ parsers/hcl/ HCL2 β IR +β βββ parsers/hcl/ HCL2 and JSON β IR +β βββ tfversion/ Terraform language version detection β βββ mappings/ Data-driven aws.json registry β βββ emitutil/ Naming, rewriting, rendering -β βββ emitters/ aws-cdk/ + pulumi/ +β βββ emitters/ aws-cdk/ + pulumi/ (+ shared warnings) β βββ engine/ Orchestration +βββ docs/ Architecture, IR, versions, conformance, roadmap βββ wasm/ js/wasm entry point βββ playground/ Monaco + WASM UI βββ examples/ Sample Terraform modules diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b4f8677..45e8245 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -5,7 +5,7 @@ target-agnostic graph, then renders that graph as TypeScript for AWS CDK or Pulumi. ```text -.tf files +.tf / .tf.json β βΌ ββββββββββββββ ββββββββββββββ ββββββββββββββ ββββββββββββββ @@ -23,8 +23,9 @@ writing one package, not a new frontend. | Package | Responsibility | |:--|:--| -| [`pkg/parsers/hcl`](../pkg/parsers/hcl/) | Reads native HCL syntax into the IR. The only package that knows Terraform exists. | -| [`pkg/ir`](../pkg/ir/) | Graph types, edge bookkeeping, deterministic topological order, cycle reporting. | +| [`pkg/parsers/hcl`](../pkg/parsers/hcl/) | Reads native HCL and JSON (`.tf` and `.tf.json`) into the IR. The only package that knows Terraform exists. | +| [`pkg/ir`](../pkg/ir/) | Graph types, edge bookkeeping, deterministic topological order, cycle reporting. Contract documented in [IR.md](IR.md). | +| [`pkg/tfversion`](../pkg/tfversion/) | Maps detected language features to `min_version`; parses `required_version` constraints. | | [`pkg/mappings`](../pkg/mappings/) | Embedded JSON registry describing target constructs per resource type. | | [`pkg/emitutil`](../pkg/emitutil/) | Naming, reference rewriting, value/template rendering shared by emitters. | | [`pkg/emitters/awscdk`](../pkg/emitters/awscdk/) | `aws-cdk-lib` TypeScript, L1 and L2 constructs. | @@ -37,19 +38,32 @@ writing one package, not a new frontend. The IR is deliberately flat. It has no loops, conditionals or expressions the emitter must evaluate β those are either resolved or reported as a warning. +Schema `0.2` is additive over `0.1`. The full reference β every field, value +kind, guarantee and the extension policy β is in [IR.md](IR.md). + ```go type Graph struct { - Version string - Resources []*Resource // managed resources and data sources - Variables []*Variable - Locals []*Local - Outputs []*Output - Modules []*Module - Providers []*Provider - Edges []Edge + Version string + Terraform *Terraform // merged terraform block settings + Resources []*Resource // managed resources and data sources + Variables []*Variable + Locals []*Local + Outputs []*Output + Modules []*Module + Providers []*Provider + Preserved []Block // moved, import, removed, check, ephemeral, action, unknown + Features []string // detected Terraform language features + MinVersion string // oldest Terraform release that accepts the input + Edges []Edge } ``` +`Preserved` is how the parser accepts the whole Terraform 1.x language without a +typed node per construct: anything OpenIaC cannot convert is kept in the graph so +an emitter can warn about it, and never enters `Resources` (both emitters treat +every entry there as a managed resource). See +[TERRAFORM-VERSIONS.md](TERRAFORM-VERSIONS.md). + ### Nodes A `Resource.ID` is the Terraform address: @@ -169,6 +183,9 @@ To add a target: 2. Implement `Emit`: call `graph.Order()`, build identifiers, construct one `RefRewriter`, render each node. 3. Collect every unsupported construct in `emitters.Warnings` β never drop it. + Call `emitters.WarnUnsupported(graph, warnings)` once, right after creating + the collector, so preserved blocks, unconverted `terraform` settings and + conditions are reported with their stable `W_*` codes. 4. Register the target in `engine.NewEmitter` and `engine.ParseTargets`. ## Determinism diff --git a/docs/CONFORMANCE.md b/docs/CONFORMANCE.md index 8b36f53..2e64728 100644 --- a/docs/CONFORMANCE.md +++ b/docs/CONFORMANCE.md @@ -382,6 +382,23 @@ One pinned image with: | `W_PROVIDER` | Non-AWS or aliased provider not converted | | `W_FUNCTION` | Unsupported HCL function | | `W_HEREDOC` | Heredoc left unchanged | +| `W_PRESERVED_BLOCK` | A top-level block has no target mapping and was preserved (`moved`, `import`, `removed`, `check`, `ephemeral`, `action`, or an unknown type) | +| `W_TERRAFORM_BACKEND` | `terraform.backend` was not converted | +| `W_TERRAFORM_CLOUD` | `terraform.cloud` was not converted | +| `W_TERRAFORM_PROVIDER_META` | `terraform.provider_meta` was not converted | +| `W_CONDITION` | A `precondition` / `postcondition` was not converted | +| `W_VARIABLE_VALIDATION` | A variable `validation` block was not converted | +| `W_UNSUPPORTED_FIELD` | A typed node carries an attribute or nested block the IR does not model | + +Warnings added from schema `0.2` onward are emitted as `CODE: message`, with +`file:line` taken from the IR's provenance so the text is portable. Codes are +grouped and sorted where the same construct repeats, and `Warnings` dedupes +identical text, so a fixture can assert an exact message. + +`W_PRESERVED_BLOCK` is the code that keeps `silent_drops` at zero for the +Terraform 1.x language: a construct OpenIaC cannot convert always produces at +least one warning. `required_version` alone never warns β it is metadata about +the input, not a conversion gap. Warning codes must be stable, documented and asserted by fixtures. Codes may be added; changing or removing one is a breaking change. diff --git a/docs/IR.md b/docs/IR.md new file mode 100644 index 0000000..c2d4bb4 --- /dev/null +++ b/docs/IR.md @@ -0,0 +1,608 @@ +# The OpenIaC IR + +The intermediate representation (IR) is the contract between parsers and +emitters. A parser turns one input language into an IR document; an emitter +renders that document in one target language. Everything the project does +happens on one side of that contract or the other, so the IR's shape is the +single most important design decision in the codebase. + +This document is the reference for that shape. It describes the JSON document, +the Go types in [`pkg/ir`](../pkg/ir/), and the guarantees a consumer may rely +on. + +- [Stability promise](#stability-promise) +- [Document envelope](#document-envelope) +- [Graph fields](#graph-fields) +- [Terraform metadata](#terraform-metadata) +- [Nodes](#nodes) +- [Values](#values) +- [Edges](#edges) +- [Features and minimum version](#features-and-minimum-version) +- [Preserved configuration](#preserved-configuration) +- [Determinism](#determinism) +- [Go API](#go-api) +- [Extension policy](#extension-policy) +- [Limitations and non-goals](#limitations-and-non-goals) +- [Complete example](#complete-example) + +## Stability promise + +The current schema is **`0.2`**, exported as `ir.Version`. While the major +version is `0`, a minor bump means the schema changed. The rules: + +| Change | Version effect | +|:--|:--| +| New optional field, new `Kind`, new `EdgeKind` | Minor bump (`0.1` β `0.2`) | +| Field renamed, removed, or changed in meaning | Major bump (`0.2` β `1.0`) | +| Behaviour of an existing field changes | Treated as a meaning change | + +Everything added since `0.1` is additive and `omitempty`: a `0.1` document +decodes into today's structs with the new fields left at their zero values, and +a `0.2` document that uses none of them serializes the same as before. + +Consumers should: + +- **Ignore unknown fields.** Do not reject a document because a newer producer + added a key. +- **Check `version` before trusting a field.** Read the major version; refuse a + document from a newer major version. +- **Never assume a field is present.** Every optional field is either + `omitempty` or documented as always present. + +## Document envelope + +A document is one JSON object: + +```jsonc +{ + "version": "0.2", // always present + "source": "main.tf", // optional: how the input was named + "terraform": { β¦ }, // optional + "resources": [ β¦ ], // always present, may be empty + "variables": [ β¦ ], // optional + "locals": [ β¦ ], // optional + "outputs": [ β¦ ], // optional + "modules": [ β¦ ], // optional + "providers": [ β¦ ], // optional + "preserved": [ β¦ ], // optional + "features": [ β¦ ], // optional + "min_version": "1.6.0", // optional + "edges": [ β¦ ] // always present, may be empty +} +``` + +`resources` and `edges` are the only collections without `omitempty`, because +consumers index into them and an explicit `[]` is friendlier than a missing +key. `ir.New` initialises both so a graph never serializes `null`. + +## Graph fields + +| Field | Go type | Meaning | +|:--|:--|:--| +| `version` | `string` | Schema version of this document. | +| `source` | `string` | The path or name the input came from. Parsers pass a comma-joined path list for multi-file modules. Informational only. | +| `terraform` | `*Terraform` | Merged `terraform` block settings. | +| `resources` | `[]*Resource` | Managed resources and data sources. | +| `variables` | `[]*Variable` | Declared input variables. | +| `locals` | `[]*Local` | Local values, one entry per attribute. | +| `outputs` | `[]*Output` | Declared outputs. | +| `modules` | `[]*Module` | Module calls. | +| `providers` | `[]*Provider` | Provider configuration blocks. | +| `preserved` | `[]Block` | Top-level configuration the IR has no typed node for. | +| `features` | `[]string` | Terraform language features detected in the input, sorted. | +| `min_version` | `string` | Oldest Terraform release that accepts the input. | +| `edges` | `[]Edge` | Dependency edges between nodes. | + +## Terraform metadata + +`terraform { β¦ }` is the one block that is not a node: it is module-wide +settings, and two of them (`required_version`, `required_providers`) describe +what Terraform must be able to run the module at all. Every `terraform` block in +the module is merged into one object. + +```go +type Terraform struct { + RequiredVersion string // verbatim, e.g. ">= 1.6.2" + RequiredProviders map[string]Value // local name -> {source, version, β¦} + Experiments []string + Backend *Block // Labels[0] is the backend type + Cloud *Block // HCP Terraform / Terraform Cloud + ProviderMeta []Block // Labels[0] is the provider name + Attributes map[string]Value // settings the IR does not model + Blocks []Block // nested blocks the IR does not model + File, Line +} +``` + +`required_version` is kept exactly as written. It is **not** validated at parse +time: an unparseable constraint must not fail a conversion. Use +`tfversion.ParseConstraint` if you need the lower bound. + +`RequiredProviders` normalises both syntaxes to one shape. Native HCL writes it +as a block with one attribute per provider; `.tf.json` writes it as an object +property. Both arrive as a map from local name to a `map` value holding +`source`, `version` and `configuration_aliases`. + +`Backend` is the legacy partial-configuration backend. `Cloud` is the HCP +Terraform alternative. Both are preserved raw; no emitter converts state +management. + +## Nodes + +A node is anything with an address that another node can reference. + +| Terraform block | Go type | Address | +|:--|:--|:--| +| `resource "aws_vpc" "main"` | `*Resource`, `Kind == "resource"` | `aws_vpc.main` | +| `data "aws_ami" "ubuntu"` | `*Resource`, `Kind == "data"` | `data.aws_ami.ubuntu` | +| `variable "region"` | `*Variable` | `var.region` | +| `locals { name = β¦ }` | `*Local` | `local.name` | +| `output "id"` | `*Output` | `output.id` | +| `module "vpc"` | `*Module` | `module.vpc` | +| `provider "aws"` | `*Provider` | `provider.aws` | + +Only nodes in `resources` participate in `Order` and `Stats`. Variables, locals, +modules and outputs are listed so emitters can declare or reference them, and so +`HasNode` can tell a real reference from a bare identifier. + +### Typed fields versus everything else + +Every node has a small set of typed fields β the ones emitters need by name β +plus two catch-alls: + +- `attributes map[string]Value` β settings the IR does not model +- `blocks []Block` β nested blocks the IR does not model + +The rule is: **typed fields are conveniences; `attributes` and `blocks` keep +everything else**, and a key promoted to a typed field is removed from +`attributes`, so nothing appears twice. A consumer can therefore always treat +the typed field and the catch-alls together as the complete configuration. + +Examples of typed fields: `Variable.Type`, `Variable.Nullable`, +`Variable.Ephemeral`, `Variable.Deprecated`, `Output.Type`, `Output.Value`, +`Resource.DependsOn`, `Resource.ProviderAlias`, `Module.Source`. + +### Provenance + +Top-level nodes and preserved blocks carry `file` and `line`; native nested +blocks carry both too. Blocks derived from a flat `.tf.json` body cannot be +located inside the file, so they carry the enclosing `file` and no `line`, and +warnings fall back to the file name alone. Locations exist so warnings can name +a position without the emitter re-reading the source. They are informational: a +document that moved between machines may have different paths. + +`Provider` and `Module` also carry `file`/`line`; both were added in `0.2`. + +### Blocks + +```go +type Block struct { + Type string + Labels []string + Attributes map[string]Value + Blocks []Block + Body *Value // JSON escape hatch, see below + File string + Line int +} +``` + +`Block.Body` is set **only** for an unrecognised top-level property in a +`.tf.json` document whose value is not an object or an array of objects β for +example `"stray": 42`. Native HCL always has a decomposable shape, so it always +fills `Attributes`/`Blocks` instead. A consumer that understands `Attributes` +and `Blocks` can ignore `Body`, but ignoring it silently drops a value, so +prefer to warn when it is set. + +## Values + +Every attribute is an `ir.Value`: + +```go +type Value struct { + Kind ValueKind + Literal any + Expr string + Raw string + Refs []string + Items []Value + Fields map[string]Value +} +``` + +| `Kind` | Payload | Notes | +|:--|:--|:--| +| `string` | `Literal` (`string`) | Plain string, templates already resolved if they were interpolation-only | +| `number` | `Literal` | `int64` when the value is an exact integer, else `float64` | +| `bool` | `Literal` (`bool`) | | +| `null` | β | `Literal` is nil | +| `list` | `Items` | Recursive; may mix literals and expressions | +| `map` | `Fields` | Recursive; may mix literals and expressions | +| `expr` | `Expr`, `Raw`, `Refs` | An expression the parser could not evaluate | + +### Numbers + +Numbers are stored as Go values rather than strings so they can be rendered +directly. Exact integers become `int64`; everything else becomes `float64`. +After a JSON round trip both arrive as `float64`, because that is how +`encoding/json` decodes into `any` β consumers that need integer semantics +should check for an exact value rather than a Go type. + +### Expressions + +An `expr` value means "this is code, not data". The fields: + +| Field | Meaning | +|:--|:--| +| `Expr` | The expression as it should be rendered. For native HCL, the source slice. For `.tf.json`, a template string is normalised to HCL syntax. | +| `Raw` | The original source text the expression came from. | +| `Refs` | Canonical addresses the expression reads, sorted and deduplicated. | + +For native HCL `Expr` and `Raw` are the same string. They are separate so a +future producer can normalise one without losing the other. + +`Refs` is how edges and reference rewriting work. A ref is the address of a +**node**, not of an attribute: `aws_vpc.main.id` contributes `aws_vpc.main`, +`var.region` contributes `var.region`, `data.aws_ami.ubuntu.id` contributes +`data.aws_ami.ubuntu`. Traversals rooted at `each`, `count`, `self`, `path` or +`terraform` contribute nothing, because they name no static node. + +An expression is not failure. `var.environment` cannot be resolved without +Terraform's evaluation context, but it is perfectly convertible: the emitter +rewrites the reference. Only values that no emitter can express produce a +warning. + +### Collection refs + +A `list` or `map` may also carry `Refs`, aggregating every reference found +inside its members. This is a convenience for consumers that only want to know +"does this value depend on anything", without walking it. Do not treat a +collection's `Refs` as an alternative to its members: the members remain the +authoritative structure. + +### Mixed collections + +A collection that mixes literals and expressions keeps its shape: + +```jsonc +"tags": { + "kind": "map", + "refs": ["var.environment"], + "fields": { + "Name": { "kind": "expr", "expr": "\"openiac-${var.environment}\"", "refs": ["var.environment"] } + } +} +``` + +Evaluating that object fails, but the shape is static, so it is represented +rather than degraded to one opaque string. The template stays a quoted HCL +template, which is what lets the emitters render it as a TypeScript template +literal. + +### `IsLiteral` + +`Value.IsLiteral()` reports whether a value can be rendered without reference +rewriting. It is true for `string`, `number`, `bool`, `null`, and for `list` / +`map` whose members are all literal. It is the check an emitter uses to decide +whether it can emit a constant. + +## Edges + +An edge means **`From` depends on `To`**, so `To` must be declared first. + +```go +type Edge struct { + From string + To string + Kind EdgeKind // "reference" or "depends_on" +} +``` + +| `Kind` | Created from | +|:--|:--| +| `reference` | Any traversal inside a resource's attributes or nested blocks | +| `depends_on` | The explicit `depends_on` meta-argument | + +Rules: + +- **Only resources and data sources produce edges.** An output reading + `aws_vpc.main.id` does not create an edge, because outputs are not ordered. +- **An edge is only created when both ends are nodes.** `HasNode` filters + references to variables, locals and modules out of the resource graph. +- **Duplicates and self-edges are dropped.** `AddEdge` is idempotent; add them in + any order. +- **Preserved blocks never create edges.** A `moved` or `import` block mentions + addresses, but it is not a dependency. + +`Graph.Order` runs Kahn's algorithm over resources. Ties are broken by address, +so the order is byte-stable across runs and machines. On a cycle it returns the +path: + +```text +dependency cycle: a.a -> b.b -> c.c -> a.a +``` + +## Features and minimum version + +`features` and `min_version` describe which Terraform release can run the input. +They are computed by [`pkg/tfversion`](../pkg/tfversion/) at parse time, so an +emitter never has to reason about versions. + +- `features` is a sorted list of stable snake_case names, one per detected + language feature (`moved`, `check`, `import_identity`, β¦). The registry and its + detection rules are documented in + [TERRAFORM-VERSIONS.md](TERRAFORM-VERSIONS.md). +- `min_version` is the newest of: the OpenIaC baseline `1.0.0`, the lower bound + of `required_version`, and the introduction version of every **reliable** + detected feature. + +A detector that can misfire (for example "moved across resource types", which is +hard to tell apart syntactically) is marked unreliable: it still appears in +`features`, but never raises `min_version`. Reporting an extra feature is +harmless; forcing a user onto a newer Terraform than they need is not. + +`required_version` is never rewritten or rejected. `min_version` is derived, not +declared: it is what the input needs, whether or not the author wrote a +constraint. + +## Preserved configuration + +Terraform 1.x has top-level constructs the IR has no typed node for. Rather than +drop them, the parser records them in `preserved`: + +| Block | Since | Why it is preserved | +|:--|:--|:--| +| `moved` | 1.1 | State refactoring; no runtime object | +| `import` | 1.5 | Imports existing infrastructure | +| `removed` | 1.7 | Removes an object from state | +| `check` | 1.5 | Continuous validation, not infrastructure | +| `ephemeral` | 1.10 | Ephemeral resource lifecycle | +| `action` | 1.14 | Provider-defined invocable actions | +| anything unknown | β | Forward compatibility | + +Preserved blocks are stored as ordinary `Block` values with their labels, +attributes, nested blocks, `file` and `line`. They are ordered by document +position, files in input order. + +**Preserved blocks are not nodes.** They never appear in `resources`, `Order`, +`Stats` or `HasNode`, because both emitters treat every entry in `resources` as +a managed resource. A consumer that converts one must do so explicitly. + +Emitters call `emitters.WarnUnsupported` once per run, which turns each +preserved block type, each unconverted terraform setting, each condition and each +variable validation into one coded warning. That is how the project keeps its +"warnings over silence" promise: nothing disappears without a line of output. + +## Determinism + +Two conversions of the same input must produce byte-identical output. The IR +carries no timestamps, hostnames, random identifiers or map iteration order: + +- Every list is emitted in a stable order: nodes in source order, features + sorted, edges in creation order, refs sorted, preserved blocks in document + order. +- Maps are unordered in Go but `encoding/json` sorts their keys, so documents + are stable on the wire. +- `Order` breaks ties by address. +- `source` is echoed exactly as given, so it can differ between machines; it is + informational and not part of any generated code. + +## Go API + +```go +graph := ir.New("main.tf") // version, source, empty resources/edges +graph.AddEdge("aws_subnet.public", "aws_vpc.main", ir.EdgeReference) + +graph.HasNode("aws_vpc.main") // true for resources, var.x, local.x, module.x +graph.ResourceByID("aws_vpc.main") // *Resource or nil +graph.Dependencies("aws_subnet.public")// sorted addresses it depends on +graph.Order() // ([]*Resource, error); cycle error names the path +graph.Stats() // (resources, data, variables, outputs, edges int) + +value.IsLiteral() // renderable without rewriting? +``` + +`pkg/engine` wraps these for whole conversions: `engine.Parse`, +`engine.ParseSource`, `engine.Convert`, `engine.ConvertSource` and +`engine.MarshalIR`. + +## Extension policy + +Adding a field is a minor version bump. To add one: + +1. Give it a JSON tag with `omitempty` unless consumers must always see it. +2. Keep the typed-versus-catch-all rule: if a parser starts extracting a key into + the new field, delete it from `attributes` so it is not duplicated. +3. If old documents must still work, document the zero value's meaning. +4. Update this file and the schema version in `pkg/ir/types.go`. +5. Add a round-trip test in `pkg/ir/graph_test.go`. + +New `Kind` and `EdgeKind` values are additive: a consumer that does not know a +kind must treat it as "cannot convert" and warn, never as a literal. + +## Limitations and non-goals + +- **No evaluation.** The IR does not carry the result of `count`, `for_each`, + functions or module expansion. Values that need them stay expressions. +- **No nested module graphs.** Modules are calls, not expanded subtrees. +- **No state.** The IR describes configuration, not resources that exist. +- **No imperative logic.** There are no conditionals or loops to render; a + parser either resolves them or reports an expression. +- **JSON bodies are flat below the top level.** HCL exposes no block structure in + a `.tf.json` body, so a nested block arrives as a `map` value. This is + documented rather than guessed. +- **`line` is informational.** It is not stable across reformatting and must not + be used for identity. + +## Complete example + +Input: + +```hcl +terraform { + required_version = ">= 1.6.2" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } + + backend "s3" { + bucket = "openiac-state" + key = "app/terraform.tfstate" + } +} + +moved { + from = aws_vpc.legacy + to = aws_vpc.main +} + +variable "environment" { + type = string + default = "dev" +} + +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + + tags = { + Name = "openiac-${var.environment}" + } + + lifecycle { + destroy = false + } +} + +output "vpc_id" { + value = aws_vpc.main.id +} +``` + +Document (`openiac ir`): + +```json +{ + "version": "0.2", + "source": "main.tf", + "terraform": { + "required_version": ">= 1.6.2", + "required_providers": { + "aws": { + "kind": "map", + "fields": { + "source": { "kind": "string", "literal": "hashicorp/aws" }, + "version": { "kind": "string", "literal": "~> 5.0" } + } + } + }, + "backend": { + "type": "backend", + "labels": ["s3"], + "attributes": { + "bucket": { "kind": "string", "literal": "openiac-state" }, + "key": { "kind": "string", "literal": "app/terraform.tfstate" } + }, + "line": 11 + }, + "file": "main.tf", + "line": 1 + }, + "resources": [ + { + "id": "aws_vpc.main", + "kind": "resource", + "type": "aws_vpc", + "name": "main", + "provider": "aws", + "attributes": { + "cidr_block": { "kind": "string", "literal": "10.0.0.0/16" }, + "tags": { + "kind": "map", + "refs": ["var.environment"], + "fields": { + "Name": { + "kind": "expr", + "expr": "\"openiac-${var.environment}\"", + "raw": "\"openiac-${var.environment}\"", + "refs": ["var.environment"] + } + } + } + }, + "blocks": [ + { + "type": "lifecycle", + "attributes": { "destroy": { "kind": "bool", "literal": false } }, + "line": 34 + } + ], + "file": "main.tf", + "line": 27 + } + ], + "variables": [ + { + "name": "environment", + "type": "string", + "default": { "kind": "string", "literal": "dev" }, + "file": "main.tf", + "line": 22 + } + ], + "outputs": [ + { + "name": "vpc_id", + "value": { + "kind": "expr", + "expr": "aws_vpc.main.id", + "raw": "aws_vpc.main.id", + "refs": ["aws_vpc.main"] + }, + "file": "main.tf", + "line": 39 + } + ], + "preserved": [ + { + "type": "moved", + "attributes": { + "from": { + "kind": "expr", + "expr": "aws_vpc.legacy", + "raw": "aws_vpc.legacy", + "refs": ["aws_vpc.legacy"] + }, + "to": { + "kind": "expr", + "expr": "aws_vpc.main", + "raw": "aws_vpc.main", + "refs": ["aws_vpc.main"] + } + }, + "file": "main.tf", + "line": 17 + } + ], + "features": ["lifecycle_destroy", "moved"], + "min_version": "1.16.0", + "edges": [ + { "from": "aws_vpc.main", "to": "var.environment", "kind": "reference" } + ] +} +``` + +Notes on this document: + +- The `moved` block is in `preserved`, not `resources`, so the graph has exactly + one node to emit. +- `min_version` is `1.16.0` because the resource lifecycle sets `destroy`, which + Terraform 1.16 introduced β not because of `required_version`, which allows an + older release. +- The output references `aws_vpc.main` but creates no edge: outputs are not + ordered against resources. +- The `tags` map keeps its shape and its reference instead of collapsing into one + opaque string. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index cea7044..a6244f1 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -21,8 +21,8 @@ The compiler exists and does something real. | Scope | Detail | |:--|:--| -| HCL parser | `resource`, `data`, `variable`, `locals`, `output`, `module`, `provider`, `depends_on` | -| IR | Flat graph, typed values, JSON schema `0.1` | +| HCL parser | Native HCL and `.tf.json`; every Terraform 1.0β1.17 top-level block is parsed or preserved | +| IR | Flat graph, typed values, preserved blocks, `features` / `min_version`, JSON schema `0.2` ([reference](IR.md)) | | Ordering | Deterministic topological sort with cycle reporting | | Rewriting | References, templates, comments; boundary-safe | | Emitters | AWS CDK (L1/L2) and Pulumi (aws SDK) | @@ -42,7 +42,7 @@ playground produces the same output as the CLI. | CI | Format, vet, test, native build, WASM build on every PR | | Pages | Playground deployed from `main` on every push | | Golden tests | Snapshot output for `examples/aws-web-app` in both targets | -| Docs | Architecture, contributing, roadmap, README | +| Docs | Architecture, IR reference, Terraform version support, contributing, roadmap, README | | Versioning | `openiac version` reads a single source of truth | --- @@ -57,7 +57,7 @@ Make real modules convert without hand-editing. | `locals` | Inline when static, warn when computed | No unresolved `local.*` in output | | Functions | `jsonencode`, `file`, `cidrsubnet`, `lookup` | Supported subset documented | | More L2 mappings | `aws_iam_role` β `iam.Role`, `aws_lambda_function` β `lambda.Function` | Snapshot tests per construct | -| Better warnings | Source file + line + suggested action | Warnings carry `file:line` | +| Better warnings | Source file + line + suggested action | Warnings carry `file:line` and a stable `W_*` code | --- diff --git a/docs/TERRAFORM-VERSIONS.md b/docs/TERRAFORM-VERSIONS.md new file mode 100644 index 0000000..240d49b --- /dev/null +++ b/docs/TERRAFORM-VERSIONS.md @@ -0,0 +1,253 @@ +# Terraform version support + +OpenIaC reads Terraform **1.0 through 1.17**. That is a statement about +*parsing*, not about conversion: every valid 1.x configuration is accepted and +represented, while the set of constructs that produce CDK or Pulumi code is +smaller and grows over time. + +Three rules follow from that split: + +- **Nothing valid is rejected.** A construct the IR has no node for is preserved; + an expression no emitter understands is kept as source text. +- **Nothing unconverted is silent.** Every construct that reaches an emitter + without a target representation produces a coded warning. See + [CONFORMANCE.md](CONFORMANCE.md#warning-taxonomy). +- **`min_version` is derived, not declared.** It reports the oldest Terraform + release that accepts the input, whether or not the author wrote a + `required_version` constraint. + +Support is implemented in [package `tfversion`](../pkg/tfversion/), which is +pure: it depends only on `pkg/ir` and `golang.org/x/mod/semver`, and it never +fails a parse. + +## Parse versus convert + +| | Parse | Convert | +|:--|:--|:--| +| HCL2 syntax (0.12+) | β | β | +| `resource`, `data`, `variable`, `locals`, `output`, `module`, `provider` | β | β for the mapped subset | +| `terraform` settings (`required_version`, `required_providers`, backend, cloud, `provider_meta`) | β | β state and metadata stay with Terraform | +| `moved`, `import`, `removed`, `check`, `ephemeral`, `action` | β preserved | β no target equivalent | +| `precondition` / `postcondition`, `validation` | β preserved | β warned | +| Anything newer than 1.17 | β preserved as an unknown block | β warned | + +## Release timeline + +| Release | Date | Language additions tracked by OpenIaC | +|:--|:--|:--| +| 1.0.0 | 2021-06-08 | HCL2 configuration baseline: `terraform`, providers, resources, data, modules | +| 1.1.0 | 2021-12-08 | `moved` blocks, `cloud` block, variable `nullable` | +| 1.2.0 | 2022-05-18 | `precondition` / `postcondition`, `lifecycle.replace_triggered_by` | +| 1.3.0 | 2022-09-21 | `optional()` object attributes, `moved` across module boundaries | +| 1.4.0 | 2023-03-08 | built-in `terraform_data` resource | +| 1.5.0 | 2023-06-12 | `check` blocks, `import` blocks | +| 1.6.0 | 2023-10-04 | `import.id` as an expression | +| 1.7.0 | 2024-01-17 | `removed` blocks, `import` with `for_each` | +| 1.8.0 | 2024-04-10 | `moved` across resource types | +| 1.9.0 | 2024-06-26 | destroy-time provisioners in `removed` blocks | +| 1.10.0 | 2024-11-27 | `ephemeral` resource blocks, ephemeral variables and outputs | +| 1.11.0 | 2025-02-27 | write-only arguments (no syntactic marker) | +| 1.12.0 | 2025-05-14 | import `identity` | +| 1.13.0 | 2025-08-20 | (no tracked language feature) | +| 1.14.0 | 2025-11-19 | `action` blocks | +| 1.15.0 | 2026-04-29 | `deprecated` on variables and outputs, output `type` | +| 1.16.0 | 2026-08-26 | `lifecycle.destroy`, `terraform_data` `store`, action lifecycle events | +| 1.17.0 | 2026-10-21 | variables and locals in provider requirements | + +The right-hand column lists what OpenIaC can identify from syntax alone, not +everything each release shipped. Tooling changes (`terraform test`, `terraform +query`, `terraform stacks`) have no configuration-language marker and are not +tracked. + +## Feature registry + +`pkg/tfversion` holds one row per feature. A row is: + +```go +{ + name: "check", // stable identifier in Graph.Features + since: "1.5.0", // canonical release that introduced it + description: "check blocks", + reliable: true, // may raise min_version + detect: func(s *scan) bool { β¦ }, +} +``` + +| Feature | Since | Detected from | +|:--|:--|:--| +| `action` | 1.14.0 | a preserved `action` block | +| `action_lifecycle_events` | 1.16.0 | `on_failure`, `before_destroy` or `after_destroy` inside an `action` block | +| `check` | 1.5.0 | a preserved `check` block | +| `cloud` | 1.1.0 | `Terraform.Cloud` | +| `conditions` | 1.2.0 | `precondition` / `postcondition` on a resource or output | +| `deprecated` | 1.15.0 | a non-empty `Variable.Deprecated` or `Output.Deprecated` | +| `ephemeral_resources` | 1.10.0 | a preserved `ephemeral` block | +| `ephemeral_values` | 1.10.0 | `Variable.Ephemeral` or `Output.Ephemeral` | +| `import` | 1.5.0 | a preserved `import` block | +| `import_expression` | 1.6.0 | an `import.id` that is not a literal string | +| `import_for_each` | 1.7.0 | an `import` block with `for_each` | +| `import_identity` | 1.12.0 | an `import` block with `identity` | +| `lifecycle_destroy` | 1.16.0 | `destroy` in a **resource's** `lifecycle` | +| `moved` | 1.1.0 | a preserved `moved` block | +| `moved_cross_type` | 1.8.0 | `from` / `to` in a `moved` block name different resource types | +| `moved_module` | 1.3.0 | `from` / `to` in a `moved` block name a `module.` segment | +| `nullable` | 1.1.0 | `Variable.Nullable` is set | +| `optional_attributes` | 1.3.0 | `optional(` in a variable's type constraint | +| `output_type` | 1.15.0 | a non-empty `Output.Type` | +| `provider_requirements_expressions` | 1.17.0 | a `required_providers` value that reads a variable or local | +| `removed` | 1.7.0 | a preserved `removed` block | +| `removed_provisioners` | 1.9.0 | a `provisioner` inside a `removed` block | +| `replace_triggered_by` | 1.2.0 | `replace_triggered_by` in a **resource's** `lifecycle` | +| `terraform_data` | 1.4.0 | a resource of type `terraform_data` | +| `terraform_data_store` | 1.16.0 | `store` on a `terraform_data` resource | + +### Reliable versus unreliable + +A detector can be syntactically correct and still report more than it should. If +it might fire on a configuration that works on an older release, it is marked +`reliable: false`: + +| Feature | Why | +|:--|:--| +| `moved_cross_type` | `addressType` is an approximation: it reads the second-to-last segment of the address and cannot see provider-specific variations. | +| `action_lifecycle_events` | `on_failure` is also a provisioner argument; only the enclosing `action` block makes it a 1.16 construct, and action blocks themselves require 1.14. | + +Unreliable features still appear in `features` β they are useful signal β but +they never raise `min_version`. Reporting an extra feature costs a reader a +minute; forcing a user onto a newer Terraform than they need can break their +pipeline. + +The detectors deliberately look at narrow places: + +- `lifecycle_destroy` and `replace_triggered_by` inspect only **resource** + lifecycle blocks. A `lifecycle { destroy = false }` inside a `removed` block + exists since 1.9 and must not be reported as the 1.16 resource argument. +- `conditions` inspects resources and outputs only. A `check` block's `assert` + is not a precondition. +- `terraform_data_store` requires the resource type to be `terraform_data`. + +### Deliberately not tracked + +| Construct | Why | +|:--|:--| +| Write-only arguments (1.11) | Provider-schema dependent; no syntactic marker. | +| `issensitive`, `templatestring`, `convert`, `provider::` functions | Function availability is release-specific but expressions are preserved anyway; a false bump is worse than a conservative one. | +| Cross-object references in variable validation (1.9) | `validation` exists since 0.13; the reference form cannot be told apart reliably. | +| Provider-defined functions (1.8) | Same: preserved as expressions, no reliable version signal. | + +If one of these becomes reliably detectable, add a row and a sample test. + +## `required_version` and `min_version` + +`Terraform.RequiredVersion` keeps the constraint **exactly as written**. It is +never validated at parse time: an unparseable constraint must not fail a +conversion. + +`tfversion.ParseConstraint` understands the operators Terraform accepts in +`required_version`: + +| Operator | Lower-bound contribution | +|:--|:--| +| bare `1.2.3`, `= 1.2.3` | `1.2.3` | +| `>= 1.2.3` | `1.2.3` | +| `~> 1.2.3`, `~> 1.2` | `1.2.3`, `1.2.0` | +| `> 1.2.3` | `1.2.4` | +| `<`, `<=`, `!=` | none | +| comma-separated list | the maximum of the clauses | + +The result is `Graph.MinVersion`, the newest of: + +1. the baseline `1.0.0`; +2. the constraint's lower bound (if it parses); +3. the `Since` value of every **reliable** detected feature. + +`~>` is treated as a lower bound only: OpenIaC does not model upper bounds, +because `min_version` answers "what is the oldest release that works", not "what +is the highest release that works". + +Examples: + +| Input | `min_version` | +|:--|:--| +| `resource "aws_vpc" "main"` | `1.0.0` | +| `required_version = ">= 0.12"` | `1.0.0` (baseline wins) | +| `required_version = ">= 1.6.2"` | `1.6.2` | +| a `check` block, no constraint | `1.5.0` | +| a `check` block, `>= 1.6.0` | `1.6.0` | +| an `action` block and a `moved` block | `1.14.0` | +| an unreliable detector firing alone | unchanged | + +## JSON configuration + +`ParseDir` reads `*.tf` and `*.tf.json` in the same directory and may mix them. +The suffix chooses the syntax: `hclparse.ParseHCL` for `.tf`, +`hclparse.ParseJSON` for `.tf.json` (case-insensitive). + +Two differences matter to consumers: + +- **Top level is recovered structurally.** A top-level schema gives every block + type its exact label count, which is how `.tf.json` blocks and labels are read + back. A label mismatch is an error, matching Terraform. +- **Bodies below the top level are flat.** HCL exposes no block structure inside + a JSON body, so an object property becomes a `map` value rather than a nested + `Block`. `lifecycle`, `default_tags`, `provisioner` and friends therefore + appear in `attributes`, not `blocks`. Every consumer must accept both shapes. + +Expressions keep working: a JSON string containing `${β¦}` or `%{β¦}` becomes an +`expr` value with its references collected, and is normalised to a quoted HCL +template so the emitters render identical TypeScript for both syntaxes. + +## Out of scope + +OpenIaC reads **configuration** files for whole modules. It does not read: + +| Path | Why | +|:--|:--| +| `.tftest.hcl` | Test definitions, not infrastructure | +| `.tfquery.hcl` | `terraform query` consultations | +| `.tfstack.hcl`, `.tfcomponent.hcl` | Stack and component definitions | +| `.tfvars`, `.tfvars.json` | Input values, not configuration | +| `.tfstate`, `.tfstate.backup` | State | +| `.terraform.lock.hcl`, `.terraform/` | Dependency material and provider plugins | +| Policy files (Sentinel, OPA) | Different language | + +Directories are not searched recursively: a subdirectory is usually a module, +and a module call is a node, not an inlined subtree. + +## Adding the next Terraform release + +1. Read the changelog and list new **top-level block types**, **meta-arguments** + and **nested blocks**. +2. For a new top-level block: add it to `topLevelSchema` and + `topLevelLabelCount` in `pkg/parsers/hcl/schema.go` if its label count is + fixed, so JSON documents are read correctly. Unknown types are already + preserved β the schema entry is what makes labels work. +3. Add a `registry` row in `pkg/tfversion/features.go`: name, `since`, + description, reliability and a detector. Prefer a narrow detector over a + generous one; mark it unreliable if it can fire on older configuration. +4. Add one minimal sample to `versionCases` in + `pkg/parsers/hcl/versions_test.go`. `TestEveryFeatureHasSample` fails if a + registered feature has no sample, and each case also asserts `min_version`, + so an over-reporting detector fails a test rather than a user. +5. Bump `tfversion.Latest`. +6. Update this file and, if the IR shape changes, [IR.md](IR.md) and + `ir.Version`. +7. Run the full suite and the corpus: + +```bash +go test ./... +OPENIAC_CORPUS=1 go test ./pkg/parsers/hcl -run TestParseConformanceCorpus -count=1 +``` + +## Corpus validation + +The conformance corpus contains 853 real-world modules. Parsing all of them is +the cheapest check that a change did not break syntax nobody wrote a unit test +for, so it is opt-in and runs on a schedule rather than on every edit: + +```bash +OPENIAC_CORPUS=1 go test ./pkg/parsers/hcl -run TestParseConformanceCorpus -count=1 +``` + +The test fails if any module fails to parse, or produces a document without a +schema version or `min_version`. diff --git a/go.mod b/go.mod index bc45f16..9670a6c 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.27.0 require ( github.com/hashicorp/hcl/v2 v2.25.0 github.com/zclconf/go-cty v1.19.0 + golang.org/x/mod v0.29.0 ) require ( @@ -12,7 +13,6 @@ require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect github.com/apparentlymart/go-textseg/v17 v17.0.1 // indirect github.com/mitchellh/go-wordwrap v1.0.1 // indirect - golang.org/x/mod v0.29.0 // indirect golang.org/x/sync v0.18.0 // indirect golang.org/x/text v0.31.0 // indirect golang.org/x/tools v0.38.0 // indirect diff --git a/pkg/emitters/awscdk/emitter.go b/pkg/emitters/awscdk/emitter.go index fc9ddcf..bd4f25a 100644 --- a/pkg/emitters/awscdk/emitter.go +++ b/pkg/emitters/awscdk/emitter.go @@ -48,6 +48,7 @@ func (e *Emitter) Emit(graph *ir.Graph, options emitters.Options) (*emitters.Res varIdents: make(map[string]string, len(graph.Variables)), usedModules: make(map[string]bool), } + emitters.WarnUnsupported(graph, r.warnings) namer := emitutil.NewNamer() for _, reserved := range []string{"cdk", "Construct", "Stack"} { diff --git a/pkg/emitters/awscdk/emitter_test.go b/pkg/emitters/awscdk/emitter_test.go new file mode 100644 index 0000000..8cf3822 --- /dev/null +++ b/pkg/emitters/awscdk/emitter_test.go @@ -0,0 +1,94 @@ +package awscdk_test + +import ( + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/emitters" + "github.com/be-thomas/openiac/pkg/emitters/awscdk" + "github.com/be-thomas/openiac/pkg/ir" +) + +func testGraph() *ir.Graph { + graph := ir.New("main.tf") + graph.Resources = []*ir.Resource{{ + ID: "aws_s3_bucket.logs", + Kind: ir.KindResource, + Type: "aws_s3_bucket", + Name: "logs", + Provider: "aws", + Attributes: map[string]ir.Value{"bucket": {Kind: ir.KindString, Literal: "logs"}}, + File: "main.tf", + Line: 1, + }} + return graph +} + +func emit(t *testing.T, graph *ir.Graph) *emitters.Result { + t.Helper() + result, err := awscdk.New().Emit(graph, emitters.Options{}) + if err != nil { + t.Fatalf("Emit: %v", err) + } + return result +} + +func TestUnsupportedConstructsWarnWithoutChangingOutput(t *testing.T) { + plain := emit(t, testGraph()) + + graph := testGraph() + graph.Terraform = &ir.Terraform{ + RequiredVersion: ">= 1.6.2", + Backend: &ir.Block{Type: "backend", Labels: []string{"s3"}, File: "main.tf", Line: 3}, + Cloud: &ir.Block{Type: "cloud", File: "main.tf", Line: 9}, + ProviderMeta: []ir.Block{{Type: "provider_meta", Labels: []string{"aws"}, File: "main.tf", Line: 13}}, + File: "main.tf", + Line: 2, + } + graph.Preserved = []ir.Block{ + {Type: "moved", File: "main.tf", Line: 20}, + {Type: "check", Labels: []string{"health"}, File: "main.tf", Line: 24}, + } + graph.Resources[0].Blocks = []ir.Block{{Type: "precondition", Line: 6}} + extended := emit(t, graph) + + if len(plain.Files) != len(extended.Files) { + t.Fatalf("files = %d vs %d", len(plain.Files), len(extended.Files)) + } + for i := range plain.Files { + if plain.Files[i] != extended.Files[i] { + t.Fatalf("generated %s changed when unsupported constructs were added:\n--- plain\n%s\n--- extended\n%s", + plain.Files[i].Path, plain.Files[i].Content, extended.Files[i].Content) + } + } + + for _, code := range []string{ + "W_PRESERVED_BLOCK", + "W_TERRAFORM_BACKEND", + "W_TERRAFORM_CLOUD", + "W_TERRAFORM_PROVIDER_META", + "W_CONDITION", + } { + if !hasWarningCode(extended.Warnings, code) { + t.Errorf("missing %s in warnings:\n%s", code, strings.Join(extended.Warnings, "\n")) + } + } +} + +func TestBaselineGraphHasNoCodedWarnings(t *testing.T) { + result := emit(t, testGraph()) + for _, warning := range result.Warnings { + if strings.HasPrefix(warning, "W_") { + t.Errorf("unexpected coded warning: %s", warning) + } + } +} + +func hasWarningCode(warnings []string, code string) bool { + for _, warning := range warnings { + if strings.HasPrefix(warning, code+":") { + return true + } + } + return false +} diff --git a/pkg/emitters/pulumi/emitter.go b/pkg/emitters/pulumi/emitter.go index 4c950b1..7c2c5fc 100644 --- a/pkg/emitters/pulumi/emitter.go +++ b/pkg/emitters/pulumi/emitter.go @@ -47,6 +47,7 @@ func (e *Emitter) Emit(graph *ir.Graph, options emitters.Options) (*emitters.Res resourceByID: make(map[string]*ir.Resource, len(graph.Resources)), varIdents: make(map[string]string, len(graph.Variables)), } + emitters.WarnUnsupported(graph, r.warnings) namer := emitutil.NewNamer() for _, reserved := range []string{"pulumi", "aws", "config", "exports"} { diff --git a/pkg/emitters/pulumi/emitter_test.go b/pkg/emitters/pulumi/emitter_test.go new file mode 100644 index 0000000..f37a567 --- /dev/null +++ b/pkg/emitters/pulumi/emitter_test.go @@ -0,0 +1,94 @@ +package pulumi_test + +import ( + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/emitters" + "github.com/be-thomas/openiac/pkg/emitters/pulumi" + "github.com/be-thomas/openiac/pkg/ir" +) + +func testGraph() *ir.Graph { + graph := ir.New("main.tf") + graph.Resources = []*ir.Resource{{ + ID: "aws_s3_bucket.logs", + Kind: ir.KindResource, + Type: "aws_s3_bucket", + Name: "logs", + Provider: "aws", + Attributes: map[string]ir.Value{"bucket": {Kind: ir.KindString, Literal: "logs"}}, + File: "main.tf", + Line: 1, + }} + return graph +} + +func emit(t *testing.T, graph *ir.Graph) *emitters.Result { + t.Helper() + result, err := pulumi.New().Emit(graph, emitters.Options{}) + if err != nil { + t.Fatalf("Emit: %v", err) + } + return result +} + +func TestUnsupportedConstructsWarnWithoutChangingOutput(t *testing.T) { + plain := emit(t, testGraph()) + + graph := testGraph() + graph.Terraform = &ir.Terraform{ + RequiredVersion: ">= 1.6.2", + Backend: &ir.Block{Type: "backend", Labels: []string{"s3"}, File: "main.tf", Line: 3}, + Cloud: &ir.Block{Type: "cloud", File: "main.tf", Line: 9}, + ProviderMeta: []ir.Block{{Type: "provider_meta", Labels: []string{"aws"}, File: "main.tf", Line: 13}}, + File: "main.tf", + Line: 2, + } + graph.Preserved = []ir.Block{ + {Type: "moved", File: "main.tf", Line: 20}, + {Type: "removed", File: "main.tf", Line: 24}, + } + graph.Resources[0].Blocks = []ir.Block{{Type: "precondition", Line: 6}} + extended := emit(t, graph) + + if len(plain.Files) != len(extended.Files) { + t.Fatalf("files = %d vs %d", len(plain.Files), len(extended.Files)) + } + for i := range plain.Files { + if plain.Files[i] != extended.Files[i] { + t.Fatalf("generated %s changed when unsupported constructs were added:\n--- plain\n%s\n--- extended\n%s", + plain.Files[i].Path, plain.Files[i].Content, extended.Files[i].Content) + } + } + + for _, code := range []string{ + "W_PRESERVED_BLOCK", + "W_TERRAFORM_BACKEND", + "W_TERRAFORM_CLOUD", + "W_TERRAFORM_PROVIDER_META", + "W_CONDITION", + } { + if !hasWarningCode(extended.Warnings, code) { + t.Errorf("missing %s in warnings:\n%s", code, strings.Join(extended.Warnings, "\n")) + } + } +} + +func TestBaselineGraphHasNoCodedWarnings(t *testing.T) { + result := emit(t, testGraph()) + for _, warning := range result.Warnings { + if strings.HasPrefix(warning, "W_") { + t.Errorf("unexpected coded warning: %s", warning) + } + } +} + +func hasWarningCode(warnings []string, code string) bool { + for _, warning := range warnings { + if strings.HasPrefix(warning, code+":") { + return true + } + } + return false +} diff --git a/pkg/emitters/warn.go b/pkg/emitters/warn.go new file mode 100644 index 0000000..8f4b989 --- /dev/null +++ b/pkg/emitters/warn.go @@ -0,0 +1,209 @@ +package emitters + +import ( + "fmt" + "path/filepath" + "sort" + "strconv" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// Stable warning codes. They are documented in docs/CONFORMANCE.md and may be +// added to, but changing or removing one is a breaking change. +const ( + codePreservedBlock = "W_PRESERVED_BLOCK" + codeTerraformBackend = "W_TERRAFORM_BACKEND" + codeTerraformCloud = "W_TERRAFORM_CLOUD" + codeTerraformMeta = "W_TERRAFORM_PROVIDER_META" + codeCondition = "W_CONDITION" + codeVariableValidation = "W_VARIABLE_VALIDATION" + codeUnsupportedField = "W_UNSUPPORTED_FIELD" +) + +// WarnUnsupported records one coded warning for every piece of the graph the +// target cannot convert. Parsers preserve Terraform 1.x constructs the IR has +// no node for; without this an unsupported construct would disappear silently. +// +// Emitters call it once, right after they create their warnings collector. +// Output is deterministic: preserved block types and attribute names are +// sorted, and locations use the base file name so paths stay portable. +func WarnUnsupported(graph *ir.Graph, w *Warnings) { + if graph == nil || w == nil { + return + } + + warnPreservedBlocks(graph.Preserved, w) + if tf := graph.Terraform; tf != nil { + warnTerraform(tf, w) + } + warnConditions(graph, w) + warnVariableValidations(graph.Variables, w) + warnUnmodelledFields(graph, w) +} + +func warnPreservedBlocks(blocks []ir.Block, w *Warnings) { + if len(blocks) == 0 { + return + } + + order := make([]string, 0, len(blocks)) + byType := make(map[string][]ir.Block, len(blocks)) + for _, block := range blocks { + if _, ok := byType[block.Type]; !ok { + order = append(order, block.Type) + } + byType[block.Type] = append(byType[block.Type], block) + } + sort.Strings(order) + + for _, blockType := range order { + items := byType[blockType] + first := location(items[0].File, items[0].Line) + if len(items) == 1 { + w.Addf("%s: %s %s block at %s is preserved but not converted", codePreservedBlock, article(blockType), blockType, first) + continue + } + w.Addf("%s: %d %s blocks are preserved but not converted (first at %s)", codePreservedBlock, len(items), blockType, first) + } +} + +func warnTerraform(tf *ir.Terraform, w *Warnings) { + if tf.Backend != nil { + w.Addf("%s: terraform backend%s at %s is not converted; configure state in the target stack instead", + codeTerraformBackend, label(tf.Backend.Labels), location(tf.Backend.File, tf.Backend.Line)) + } + if tf.Cloud != nil { + w.Addf("%s: terraform cloud block at %s is not converted", + codeTerraformCloud, location(tf.Cloud.File, tf.Cloud.Line)) + } + for _, block := range tf.ProviderMeta { + w.Addf("%s: provider_meta%s at %s is not converted", + codeTerraformMeta, label(block.Labels), location(block.File, block.Line)) + } +} + +// warnConditions reports preconditions and postconditions. Neither emitter can +// express them in generated code, and dropping them silently would lose a +// correctness check the author wrote. +func warnConditions(graph *ir.Graph, w *Warnings) { + for _, resource := range graph.Resources { + warnConditionFields(resource.ID, resource.File, resource.Attributes, resource.Blocks, w) + } + for _, output := range graph.Outputs { + warnConditionFields("output."+output.Name, output.File, output.Attributes, output.Blocks, w) + } +} + +func warnConditionFields(owner, file string, attrs map[string]ir.Value, blocks []ir.Block, w *Warnings) { + for _, name := range []string{"precondition", "postcondition"} { + if _, ok := attrs[name]; ok { + // .tf.json spells the condition as an object property, so there is no + // per-condition line to report. + w.Addf("%s: %s: %s is not converted", codeCondition, owner, name) + continue + } + for _, block := range blocks { + if block.Type == name { + w.Addf("%s: %s: %s block at %s is not converted", codeCondition, owner, name, location(file, block.Line)) + } + } + } +} + +func warnVariableValidations(variables []*ir.Variable, w *Warnings) { + for _, variable := range variables { + // .tf.json spells validation as an object property. + if _, ok := variable.Attributes["validation"]; ok { + w.Addf("%s: var.%s: validation is not converted (return an error from the stack instead)", + codeVariableValidation, variable.Name) + } + for _, block := range variable.Blocks { + if block.Type == "validation" { + w.Addf("%s: var.%s: validation block at %s is not converted (return an error from the stack instead)", + codeVariableValidation, variable.Name, location(variable.File, block.Line)) + } + } + } +} + +// warnUnmodelledFields reports typed nodes carrying settings the IR has no +// field for. Those settings land in Attributes/Blocks, which no emitter reads. +func warnUnmodelledFields(graph *ir.Graph, w *Warnings) { + if tf := graph.Terraform; tf != nil { + warnExtras("terraform", tf.File, tf.Attributes, tf.Blocks, nil, nil, w) + } + for _, variable := range graph.Variables { + warnExtras("var."+variable.Name, variable.File, variable.Attributes, variable.Blocks, + knownBlocks("validation"), knownBlocks("validation"), w) + } + for _, output := range graph.Outputs { + warnExtras("output."+output.Name, output.File, output.Attributes, output.Blocks, + knownBlocks("precondition", "postcondition"), knownBlocks("precondition", "postcondition"), w) + } +} + +func warnExtras(owner, file string, attrs map[string]ir.Value, blocks []ir.Block, skipAttrs, skipBlocks map[string]bool, w *Warnings) { + names := make([]string, 0, len(attrs)) + for name := range attrs { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + if skipAttrs[name] { + continue + } + w.Addf("%s: %s: attribute %q is not converted", codeUnsupportedField, owner, name) + } + + seen := make(map[string]bool, len(blocks)) + for _, block := range blocks { + if skipBlocks[block.Type] || seen[block.Type] { + continue + } + seen[block.Type] = true + w.Addf("%s: %s: block %q at %s is not converted", codeUnsupportedField, owner, block.Type, location(file, block.Line)) + } +} + +func knownBlocks(names ...string) map[string]bool { + out := make(map[string]bool, len(names)) + for _, name := range names { + out[name] = true + } + return out +} + +// location renders a source position as "file:line", or just the file when the +// position is unknown. Only the base name is used so warning text does not +// depend on where a checkout lives. +func location(file string, line int) string { + name := filepath.Base(file) + if name == "" || name == "." { + return "an unknown location" + } + if line > 0 { + return fmt.Sprintf("%s:%d", name, line) + } + return name +} + +func label(labels []string) string { + if len(labels) == 0 || labels[0] == "" { + return "" + } + return " " + strconv.Quote(labels[0]) +} + +// article picks the indefinite article for a block type so warnings read +// naturally: "a moved block", "an import block". +func article(word string) string { + if word == "" { + return "a" + } + switch word[0] { + case 'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U': + return "an" + } + return "a" +} diff --git a/pkg/emitters/warn_test.go b/pkg/emitters/warn_test.go new file mode 100644 index 0000000..4009167 --- /dev/null +++ b/pkg/emitters/warn_test.go @@ -0,0 +1,178 @@ +package emitters_test + +import ( + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/emitters" + "github.com/be-thomas/openiac/pkg/ir" +) + +func warnGraph() *ir.Graph { + graph := ir.New("main.tf") + graph.Terraform = &ir.Terraform{ + RequiredVersion: ">= 1.6.2", + Backend: &ir.Block{ + Type: "backend", + Labels: []string{"s3"}, + File: "main.tf", + Line: 2, + }, + Cloud: &ir.Block{ + Type: "cloud", + File: "main.tf", + Line: 8, + }, + ProviderMeta: []ir.Block{{ + Type: "provider_meta", + Labels: []string{"aws"}, + File: "main.tf", + Line: 12, + }}, + Attributes: map[string]ir.Value{"future_setting": {Kind: ir.KindString, Literal: "x"}}, + Blocks: []ir.Block{{Type: "future_block", File: "main.tf", Line: 2}}, + File: "main.tf", + Line: 1, + } + graph.Resources = []*ir.Resource{{ + ID: "aws_instance.web", + Kind: ir.KindResource, + Type: "aws_instance", + Name: "web", + Blocks: []ir.Block{{Type: "precondition", Line: 20}}, + File: "main.tf", + Line: 18, + }} + graph.Outputs = []*ir.Output{{ + Name: "ip", + Attributes: map[string]ir.Value{"precondition": {Kind: ir.KindMap}}, + File: "main.tf", + Line: 24, + }} + graph.Variables = []*ir.Variable{{ + Name: "password", + Attributes: map[string]ir.Value{"custom": {Kind: ir.KindString, Literal: "y"}}, + Blocks: []ir.Block{{Type: "validation", Line: 30}}, + File: "main.tf", + Line: 28, + }} + graph.Preserved = []ir.Block{ + {Type: "moved", File: "main.tf", Line: 3}, + {Type: "import", File: "main.tf", Line: 10}, + {Type: "import", File: "main.tf", Line: 14}, + } + return graph +} + +func collect(graph *ir.Graph) []string { + warnings := emitters.NewWarnings() + emitters.WarnUnsupported(graph, warnings) + return warnings.List() +} + +func TestWarnUnsupportedCodes(t *testing.T) { + got := collect(warnGraph()) + + want := []string{ + `W_PRESERVED_BLOCK: 2 import blocks are preserved but not converted (first at main.tf:10)`, + `W_PRESERVED_BLOCK: a moved block at main.tf:3 is preserved but not converted`, + `W_TERRAFORM_BACKEND: terraform backend "s3" at main.tf:2 is not converted; configure state in the target stack instead`, + `W_TERRAFORM_CLOUD: terraform cloud block at main.tf:8 is not converted`, + `W_TERRAFORM_PROVIDER_META: provider_meta "aws" at main.tf:12 is not converted`, + `W_CONDITION: aws_instance.web: precondition block at main.tf:20 is not converted`, + `W_CONDITION: output.ip: precondition is not converted`, + `W_VARIABLE_VALIDATION: var.password: validation block at main.tf:30 is not converted (return an error from the stack instead)`, + `W_UNSUPPORTED_FIELD: terraform: attribute "future_setting" is not converted`, + `W_UNSUPPORTED_FIELD: terraform: block "future_block" at main.tf:2 is not converted`, + `W_UNSUPPORTED_FIELD: var.password: attribute "custom" is not converted`, + } + if len(got) != len(want) { + t.Fatalf("warnings = %d, want %d:\n%s", len(got), len(want), strings.Join(got, "\n")) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("warning %d =\n %q\nwant\n %q", i, got[i], want[i]) + } + } +} + +func TestWarnUnsupportedArticle(t *testing.T) { + graph := ir.New("main.tf") + graph.Preserved = []ir.Block{ + {Type: "action", File: "main.tf", Line: 1}, + {Type: "ephemeral", File: "main.tf", Line: 5}, + {Type: "import", File: "main.tf", Line: 9}, + {Type: "moved", File: "main.tf", Line: 13}, + } + + want := []string{ + `W_PRESERVED_BLOCK: an action block at main.tf:1 is preserved but not converted`, + `W_PRESERVED_BLOCK: an ephemeral block at main.tf:5 is preserved but not converted`, + `W_PRESERVED_BLOCK: an import block at main.tf:9 is preserved but not converted`, + `W_PRESERVED_BLOCK: a moved block at main.tf:13 is preserved but not converted`, + } + got := collect(graph) + if len(got) != len(want) { + t.Fatalf("warnings = %v, want %v", got, want) + } + for i := range want { + if got[i] != want[i] { + t.Errorf("warning %d =\n %q\nwant\n %q", i, got[i], want[i]) + } + } +} + +func TestWarnUnsupportedIsDeterministic(t *testing.T) { + first := strings.Join(collect(warnGraph()), "\n") + for i := 0; i < 5; i++ { + if got := strings.Join(collect(warnGraph()), "\n"); got != first { + t.Fatalf("warnings changed between runs:\n%s\n---\n%s", first, got) + } + } +} + +func TestWarnUnsupportedDeduplicates(t *testing.T) { + graph := ir.New("main.tf") + graph.Resources = []*ir.Resource{{ + ID: "aws_instance.web", + Kind: ir.KindResource, + Type: "aws_instance", + Name: "web", + Blocks: []ir.Block{{Type: "precondition", Line: 9}, {Type: "precondition", Line: 9}}, + File: "main.tf", + }} + warnings := collect(graph) + if len(warnings) != 1 { + t.Fatalf("warnings = %v, want one", warnings) + } +} + +func TestWarnUnsupportedBaselineIsSilent(t *testing.T) { + graph := ir.New("main.tf") + graph.Terraform = &ir.Terraform{RequiredVersion: ">= 1.6.2"} + graph.Resources = []*ir.Resource{{ + ID: "aws_vpc.main", + Kind: ir.KindResource, + Type: "aws_vpc", + Name: "main", + Attributes: map[string]ir.Value{"cidr_block": {Kind: ir.KindString, Literal: "10.0.0.0/16"}}, + }} + if warnings := collect(graph); len(warnings) != 0 { + t.Fatalf("warnings = %v, want none", warnings) + } +} + +func TestWarnUnsupportedNil(t *testing.T) { + // Neither argument may panic; a nil graph simply has nothing to report. + emitters.WarnUnsupported(nil, emitters.NewWarnings()) + emitters.WarnUnsupported(ir.New("main.tf"), nil) +} + +func TestWarnUnsupportedUnknownLocation(t *testing.T) { + graph := ir.New("") + graph.Preserved = []ir.Block{{Type: "moved"}} + got := collect(graph) + if len(got) != 1 || !strings.Contains(got[0], "at an unknown location") { + t.Fatalf("warnings = %v", got) + } +} diff --git a/pkg/engine/engine_test.go b/pkg/engine/engine_test.go index 4238fed..3a05e68 100644 --- a/pkg/engine/engine_test.go +++ b/pkg/engine/engine_test.go @@ -9,6 +9,7 @@ import ( "github.com/be-thomas/openiac/pkg/emitters" "github.com/be-thomas/openiac/pkg/engine" + "github.com/be-thomas/openiac/pkg/ir" ) const source = ` @@ -189,8 +190,8 @@ func TestMarshalIR(t *testing.T) { if err := json.Unmarshal(data, &decoded); err != nil { t.Fatalf("IR is not valid JSON: %v", err) } - if decoded.Version != "0.1" { - t.Errorf("version = %q, want 0.1", decoded.Version) + if decoded.Version != ir.Version { + t.Errorf("version = %q, want %q", decoded.Version, ir.Version) } if len(decoded.Resources) != 2 || len(decoded.Edges) == 0 { t.Errorf("resources=%d edges=%d", len(decoded.Resources), len(decoded.Edges)) diff --git a/pkg/ir/graph_test.go b/pkg/ir/graph_test.go index a656a9d..6812201 100644 --- a/pkg/ir/graph_test.go +++ b/pkg/ir/graph_test.go @@ -1,6 +1,7 @@ package ir_test import ( + "encoding/json" "strings" "testing" @@ -127,3 +128,237 @@ func TestStats(t *testing.T) { t.Fatalf("stats = %d/%d/%d/%d/%d, want 1/1/1/1/1", resources, data, variables, outputs, edges) } } + +func TestNewDocumentShape(t *testing.T) { + if ir.Version != "0.2" { + t.Fatalf("ir.Version = %q, want the 0.2 schema", ir.Version) + } + graph := ir.New("main.tf") + if graph.Version != ir.Version { + t.Fatalf("version = %q, want %q", graph.Version, ir.Version) + } + + encoded, err := json.Marshal(graph) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + // An empty graph must still serialize the fields consumers index into, and + // must not emit empty optional collections. + want := `{"version":"0.2","source":"main.tf","resources":[],"edges":[]}` + if string(encoded) != want { + t.Fatalf("Marshal = %s, want %s", encoded, want) + } +} + +func TestJSONRoundTrip(t *testing.T) { + nullable := false + graph := ir.New("main.tf") + graph.Terraform = &ir.Terraform{ + RequiredVersion: ">= 1.6.2", + RequiredProviders: map[string]ir.Value{ + "aws": {Kind: ir.KindMap, Fields: map[string]ir.Value{ + "source": {Kind: ir.KindString, Literal: "hashicorp/aws"}, + "version": {Kind: ir.KindString, Literal: "~> 5.0"}, + }}, + }, + Experiments: []string{"module_variable_optional_attrs"}, + Backend: &ir.Block{Type: "backend", Labels: []string{"s3"}, Attributes: map[string]ir.Value{"bucket": {Kind: ir.KindString, Literal: "state"}}}, + Cloud: &ir.Block{Type: "cloud", Attributes: map[string]ir.Value{"organization": {Kind: ir.KindString, Literal: "example"}}}, + ProviderMeta: []ir.Block{{ + Type: "provider_meta", + Labels: []string{"aws"}, + }}, + Attributes: map[string]ir.Value{"future": {Kind: ir.KindString, Literal: "x"}}, + File: "main.tf", + Line: 1, + } + graph.Resources = []*ir.Resource{{ + ID: "aws_instance.web", + Kind: ir.KindResource, + Type: "aws_instance", + Name: "web", + Provider: "aws", + ProviderAlias: "aws.west", + DependsOn: []string{"aws_vpc.main"}, + Attributes: map[string]ir.Value{ + "ami": {Kind: ir.KindString, Literal: "ami-123"}, + "count": {Kind: ir.KindNumber, Literal: int64(2)}, + "enabled": {Kind: ir.KindBool, Literal: true}, + "missing": {Kind: ir.KindNull}, + "subnets": {Kind: ir.KindList, Items: []ir.Value{{Kind: ir.KindString, Literal: "a"}}}, + "vpc_id": {Kind: ir.KindExpr, Expr: "aws_vpc.main.id", Raw: "aws_vpc.main.id", Refs: []string{"aws_vpc.main"}}, + "tags": {Kind: ir.KindMap, Fields: map[string]ir.Value{"env": {Kind: ir.KindString, Literal: "dev"}}}, + "nested_empty": {Kind: ir.KindMap, Fields: map[string]ir.Value{}}, + "empty_list": {Kind: ir.KindList}, + "unset_optional": {}, + }, + Blocks: []ir.Block{{Type: "lifecycle", Attributes: map[string]ir.Value{"destroy": {Kind: ir.KindBool, Literal: false}}}}, + File: "main.tf", + Line: 10, + }} + graph.Variables = []*ir.Variable{{ + Name: "config", + Type: "object({ retries = optional(number, 3) })", + Default: &ir.Value{Kind: ir.KindString, Literal: "x"}, + Description: "config", + Sensitive: true, + Nullable: &nullable, + Ephemeral: true, + Deprecated: "use config2", + Attributes: map[string]ir.Value{"custom": {Kind: ir.KindString, Literal: "y"}}, + Blocks: []ir.Block{{Type: "validation", Attributes: map[string]ir.Value{"condition": {Kind: ir.KindString, Literal: "true"}}}}, + File: "main.tf", + Line: 30, + }} + graph.Locals = []*ir.Local{{Name: "name", Value: ir.Value{Kind: ir.KindString, Literal: "app"}, File: "main.tf", Line: 40}} + graph.Outputs = []*ir.Output{{ + Name: "ip", + Value: ir.Value{Kind: ir.KindExpr, Expr: "aws_instance.web.private_ip", Raw: "aws_instance.web.private_ip"}, + Description: "private ip", + Sensitive: true, + Type: "string", + Ephemeral: true, + Deprecated: "use ips", + Attributes: map[string]ir.Value{"custom": {Kind: ir.KindString, Literal: "z"}}, + Blocks: []ir.Block{{Type: "precondition"}}, + File: "main.tf", + Line: 50, + }} + graph.Modules = []*ir.Module{{ + Name: "vpc", + Source: "terraform-aws-modules/vpc/aws", + Version: "5.0.0", + Attributes: map[string]ir.Value{"cidr": {Kind: ir.KindString, Literal: "10.0.0.0/16"}}, + File: "main.tf", + Line: 60, + }} + graph.Providers = []*ir.Provider{{ + Name: "aws", + Alias: "west", + Attributes: map[string]ir.Value{"region": {Kind: ir.KindString, Literal: "us-west-2"}}, + Blocks: []ir.Block{{Type: "default_tags"}}, + File: "main.tf", + Line: 70, + }} + graph.Preserved = []ir.Block{{ + Type: "moved", + File: "main.tf", + Line: 80, + Attributes: map[string]ir.Value{ + "from": {Kind: ir.KindExpr, Expr: "aws_vpc.old", Raw: "aws_vpc.old"}, + "to": {Kind: ir.KindExpr, Expr: "aws_vpc.main", Raw: "aws_vpc.main"}, + }, + }, { + Type: "stray_argument", + Body: &ir.Value{Kind: ir.KindNumber, Literal: int64(42)}, + File: "main.tf", + Line: 90, + }} + graph.Features = []string{"moved", "terraform_data"} + graph.MinVersion = "1.4.0" + graph.AddEdge("aws_instance.web", "aws_vpc.main", ir.EdgeDependsOn) + + first, err := json.Marshal(graph) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + + var decoded ir.Graph + if err := json.Unmarshal(first, &decoded); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + // Compare the encoding rather than the Go values: JSON numbers decode to + // float64, so a literal int64 would never be DeepEqual even though the + // document is identical. + second, err := json.Marshal(&decoded) + if err != nil { + t.Fatalf("Marshal: %v", err) + } + if string(first) != string(second) { + t.Fatalf("round trip changed the document:\nfirst: %s\nsecond: %s", first, second) + } +} + +func TestDecodeLegacyDocument(t *testing.T) { + // Schema 0.1 had no terraform, preserved, features or min_version fields. + legacy := `{ + "version": "0.1", + "source": "main.tf", + "resources": [{"id": "aws_vpc.main", "kind": "resource", "type": "aws_vpc", "name": "main"}], + "edges": [] +}` + var graph ir.Graph + if err := json.Unmarshal([]byte(legacy), &graph); err != nil { + t.Fatalf("Unmarshal: %v", err) + } + if graph.Version != "0.1" { + t.Errorf("version = %q", graph.Version) + } + if len(graph.Resources) != 1 || graph.Resources[0].ID != "aws_vpc.main" { + t.Fatalf("resources = %v", graph.Resources) + } + if graph.Terraform != nil || len(graph.Preserved) != 0 || graph.MinVersion != "" { + t.Errorf("0.2 fields should stay unset: %#v", graph) + } + if !graph.HasNode("aws_vpc.main") { + t.Error("HasNode(aws_vpc.main) = false") + } +} + +func TestOrderAndStatsIgnorePreserved(t *testing.T) { + graph := graphWith("aws_vpc.main", "aws_subnet.public") + graph.AddEdge("aws_subnet.public", "aws_vpc.main", ir.EdgeReference) + graph.Preserved = []ir.Block{ + {Type: "moved"}, + {Type: "import"}, + {Type: "removed"}, + {Type: "check", Labels: []string{"health"}}, + {Type: "ephemeral", Labels: []string{"random_password", "db"}}, + {Type: "action", Labels: []string{"aws_lb_target_group", "register"}}, + } + + ordered, err := graph.Order() + if err != nil { + t.Fatalf("Order: %v", err) + } + if len(ordered) != 2 || ordered[0].ID != "aws_vpc.main" || ordered[1].ID != "aws_subnet.public" { + t.Fatalf("order = %v", ordered) + } + + resources, data, _, _, edges := graph.Stats() + if resources != 2 || data != 0 || edges != 1 { + t.Fatalf("stats = %d/%d/%d", resources, data, edges) + } + + for _, id := range []string{"moved", "check.health", "random_password.db", "aws_lb_target_group.register"} { + if graph.HasNode(id) { + t.Errorf("HasNode(%q) = true, preserved blocks are not nodes", id) + } + } +} + +func TestValueIsLiteral(t *testing.T) { + cases := []struct { + name string + value ir.Value + want bool + }{ + {"string", ir.Value{Kind: ir.KindString, Literal: "a"}, true}, + {"number", ir.Value{Kind: ir.KindNumber, Literal: 1.5}, true}, + {"bool", ir.Value{Kind: ir.KindBool, Literal: true}, true}, + {"null", ir.Value{Kind: ir.KindNull}, true}, + {"expr", ir.Value{Kind: ir.KindExpr, Expr: "var.x"}, false}, + {"empty list", ir.Value{Kind: ir.KindList}, true}, + {"empty map", ir.Value{Kind: ir.KindMap}, true}, + {"literal list", ir.Value{Kind: ir.KindList, Items: []ir.Value{{Kind: ir.KindString, Literal: "a"}}}, true}, + {"mixed list", ir.Value{Kind: ir.KindList, Items: []ir.Value{{Kind: ir.KindExpr, Expr: "var.x"}}}, false}, + {"literal map", ir.Value{Kind: ir.KindMap, Fields: map[string]ir.Value{"a": {Kind: ir.KindNumber, Literal: 1}}}, true}, + {"mixed map", ir.Value{Kind: ir.KindMap, Fields: map[string]ir.Value{"a": {Kind: ir.KindExpr, Expr: "var.x"}}}, false}, + {"zero value", ir.Value{}, false}, + } + for _, c := range cases { + if got := c.value.IsLiteral(); got != c.want { + t.Errorf("%s: IsLiteral() = %v, want %v", c.name, got, c.want) + } + } +} diff --git a/pkg/ir/types.go b/pkg/ir/types.go index c5b49fa..0dd57c5 100644 --- a/pkg/ir/types.go +++ b/pkg/ir/types.go @@ -5,10 +5,15 @@ // in a target language. Nothing in the IR represents loops, conditionals or // other imperative logic β those are resolved by the parser before the graph is // built. +// +// Schema 0.2 is additive over 0.1: no existing field changed type or meaning. +// Configuration the IR does not model is preserved rather than dropped, in +// Graph.Preserved, in Terraform, or in each node's Attributes and Blocks. The +// full contract is documented in docs/IR.md. package ir // Version is the schema version of the IR document. -const Version = "0.1" +const Version = "0.2" // Kind identifies what a node represents. type Kind string @@ -28,13 +33,48 @@ const ( type Graph struct { Version string `json:"version"` Source string `json:"source,omitempty"` + Terraform *Terraform `json:"terraform,omitempty"` Resources []*Resource `json:"resources"` Variables []*Variable `json:"variables,omitempty"` Locals []*Local `json:"locals,omitempty"` Outputs []*Output `json:"outputs,omitempty"` Modules []*Module `json:"modules,omitempty"` Providers []*Provider `json:"providers,omitempty"` - Edges []Edge `json:"edges"` + // Preserved holds top-level configuration the IR has no typed node for: + // moved, import, removed, check, ephemeral, action, and any future or + // unrecognised block type. Preserved blocks carry no node identity and never + // appear in Resources, Order or Stats. + Preserved []Block `json:"preserved,omitempty"` + // Features lists the Terraform language features detected in the input, in + // sorted order. See package tfversion. + Features []string `json:"features,omitempty"` + // MinVersion is the oldest Terraform release that accepts this + // configuration, derived from Features and Terraform.RequiredVersion. + MinVersion string `json:"min_version,omitempty"` + Edges []Edge `json:"edges"` +} + +// Terraform is the merge of every terraform block in the module. Settings the +// IR models are typed; everything else is kept in Attributes and Blocks so +// nothing is lost. +type Terraform struct { + RequiredVersion string `json:"required_version,omitempty"` + // RequiredProviders maps a provider local name (for example "aws") to its + // declaration: a map with source, version and configuration_aliases. + RequiredProviders map[string]Value `json:"required_providers,omitempty"` + Experiments []string `json:"experiments,omitempty"` + // Backend is the legacy state backend; Labels[0] is the backend type. + Backend *Block `json:"backend,omitempty"` + // Cloud is the HCP Terraform / Terraform Cloud integration block. + Cloud *Block `json:"cloud,omitempty"` + // ProviderMeta holds provider_meta blocks; Labels[0] is the provider name. + ProviderMeta []Block `json:"provider_meta,omitempty"` + // Attributes keeps terraform settings the IR does not model. + Attributes map[string]Value `json:"attributes,omitempty"` + // Blocks keeps nested terraform blocks the IR does not model. + Blocks []Block `json:"blocks,omitempty"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Resource is a managed resource or data source. @@ -57,13 +97,21 @@ type Resource struct { } // Block is a nested configuration block (for example a security group ingress -// rule). +// rule), or a preserved top-level construct that has no typed node. type Block struct { Type string `json:"type"` Labels []string `json:"labels,omitempty"` Attributes map[string]Value `json:"attributes,omitempty"` Blocks []Block `json:"blocks,omitempty"` - Line int `json:"line,omitempty"` + // Body preserves a JSON value the parser could not decompose into + // attributes and blocks. It is set only for unrecognised top-level + // properties of a .tf.json document; native HCL always fills Attributes and + // Blocks. + Body *Value `json:"body,omitempty"` + // File is set for top-level blocks. Nested blocks inherit their parent's + // file and leave this empty. + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Variable is a declared input variable. @@ -73,12 +121,26 @@ type Variable struct { Default *Value `json:"default,omitempty"` Description string `json:"description,omitempty"` Sensitive bool `json:"sensitive,omitempty"` + // Nullable is Terraform 1.1+. Nil means the argument was not set. + Nullable *bool `json:"nullable,omitempty"` + // Ephemeral is Terraform 1.10+. + Ephemeral bool `json:"ephemeral,omitempty"` + // Deprecated is the deprecation message, Terraform 1.15+. + Deprecated string `json:"deprecated,omitempty"` + // Attributes keeps variable settings the IR does not model. + Attributes map[string]Value `json:"attributes,omitempty"` + // Blocks keeps nested blocks such as validation. + Blocks []Block `json:"blocks,omitempty"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Local is a named local value. type Local struct { Name string `json:"name"` Value Value `json:"value"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Output is a declared output value. @@ -87,6 +149,18 @@ type Output struct { Value Value `json:"value"` Description string `json:"description,omitempty"` Sensitive bool `json:"sensitive,omitempty"` + // Type is the output type constraint, Terraform 1.15+. + Type string `json:"type,omitempty"` + // Ephemeral is Terraform 1.10+. + Ephemeral bool `json:"ephemeral,omitempty"` + // Deprecated is the deprecation message, Terraform 1.15+. + Deprecated string `json:"deprecated,omitempty"` + // Attributes keeps output settings the IR does not model. + Attributes map[string]Value `json:"attributes,omitempty"` + // Blocks keeps nested blocks such as precondition and postcondition. + Blocks []Block `json:"blocks,omitempty"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Module is a module call. OpenIaC does not yet expand modules; the call is @@ -97,6 +171,8 @@ type Module struct { Version string `json:"version,omitempty"` Attributes map[string]Value `json:"attributes,omitempty"` Blocks []Block `json:"blocks,omitempty"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // Provider is a provider configuration block. @@ -104,6 +180,9 @@ type Provider struct { Name string `json:"name"` Alias string `json:"alias,omitempty"` Attributes map[string]Value `json:"attributes,omitempty"` + Blocks []Block `json:"blocks,omitempty"` + File string `json:"file,omitempty"` + Line int `json:"line,omitempty"` } // ValueKind describes how a Value is stored. diff --git a/pkg/parsers/hcl/body.go b/pkg/parsers/hcl/body.go new file mode 100644 index 0000000..afc40f3 --- /dev/null +++ b/pkg/parsers/hcl/body.go @@ -0,0 +1,316 @@ +package hclparser + +import ( + "fmt" + "math/big" + "sort" + "strings" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclsyntax" + hcljson "github.com/hashicorp/hcl/v2/json" + "github.com/zclconf/go-cty/cty" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// parseBody converts the content of a block into IR attributes and nested +// blocks. +// +// Native HCL keeps its full structure. JSON bodies are flat by necessity: HCL +// exposes no block structure below the top level, so every object property +// becomes a map value. +func parseBody(body hcl.Body, src []byte) (map[string]ir.Value, []ir.Block, error) { + if hcljson.IsJSONBody(body) { + return parseJSONBody(body, src) + } + + native, ok := body.(*hclsyntax.Body) + if !ok { + return nil, nil, fmt.Errorf("unsupported HCL body type %T", body) + } + + attrs := make(map[string]ir.Value, len(native.Attributes)) + names := make([]string, 0, len(native.Attributes)) + for name := range native.Attributes { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + attrs[name] = parseExpr(native.Attributes[name].Expr, src) + } + + blocks := make([]ir.Block, 0, len(native.Blocks)) + for _, block := range native.Blocks { + blockAttrs, nested, err := parseBody(block.Body, src) + if err != nil { + return nil, nil, err + } + blocks = append(blocks, ir.Block{ + Type: block.Type, + Labels: append([]string(nil), block.Labels...), + Attributes: blockAttrs, + Blocks: nested, + File: block.TypeRange.Filename, + Line: block.TypeRange.Start.Line, + }) + } + return attrs, blocks, nil +} + +func parseJSONBody(body hcl.Body, src []byte) (map[string]ir.Value, []ir.Block, error) { + attributes, diags := body.JustAttributes() + if diags.HasErrors() { + return nil, nil, diags + } + + attrs := make(map[string]ir.Value, len(attributes)) + names := make([]string, 0, len(attributes)) + for name := range attributes { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + attrs[name] = parseExpr(attributes[name].Expr, src) + } + // JSON cannot distinguish a nested block from an object property, so nested + // blocks are never produced here. Callers that know their block schema (the + // terraform block) request it explicitly. + return attrs, nil, nil +} + +// parseExpr converts an HCL expression to an IR value. +func parseExpr(expr hcl.Expression, src []byte) ir.Value { + if hcljson.IsJSONExpression(expr) { + return parseJSONExpr(expr, src) + } + return parseHCLExpr(expr, src) +} + +func parseHCLExpr(expr hcl.Expression, src []byte) ir.Value { + raw := sliceRange(src, expr.Range()) + + if value, ok := literalValue(expr); ok { + return value + } + if value, ok := structuredValue(expr, src); ok { + return value + } + return ir.Value{ + Kind: ir.KindExpr, + Expr: raw, + Raw: raw, + Refs: collectRefs(expr), + } +} + +// structuredValue handles collections that mix literals and expressions, such +// as tags = { Name = "x", Env = var.environment }. Evaluating such a value +// fails, but its shape is still static and can be represented in the IR. +func structuredValue(expr hcl.Expression, src []byte) (ir.Value, bool) { + switch e := expr.(type) { + case *hclsyntax.ParenthesesExpr: + return structuredValue(e.Expression, src) + case *hclsyntax.ObjectConsExpr: + fields := make(map[string]ir.Value, len(e.Items)) + for _, item := range e.Items { + key, diags := item.KeyExpr.Value(nil) + if diags.HasErrors() || !key.IsKnown() || key.Type() != cty.String { + return ir.Value{}, false + } + fields[key.AsString()] = parseExpr(item.ValueExpr, src) + } + return ir.Value{ + Kind: ir.KindMap, + Fields: fields, + Refs: collectRefs(expr), + }, true + case *hclsyntax.TupleConsExpr: + items := make([]ir.Value, 0, len(e.Exprs)) + for _, item := range e.Exprs { + items = append(items, parseExpr(item, src)) + } + return ir.Value{ + Kind: ir.KindList, + Items: items, + Refs: collectRefs(expr), + }, true + default: + return ir.Value{}, false + } +} + +// literalValue evaluates an expression only if it is self-contained. Anything +// that reads a variable, resource or function is left as an expression. +func literalValue(expr hcl.Expression) (value ir.Value, ok bool) { + defer func() { + if recover() != nil { + value, ok = ir.Value{}, false + } + }() + + val, diags := expr.Value(nil) + if diags.HasErrors() || val == cty.NilVal || !val.IsWhollyKnown() { + return ir.Value{}, false + } + return fromCty(val) +} + +func fromCty(val cty.Value) (ir.Value, bool) { + if val.IsNull() { + return ir.Value{Kind: ir.KindNull}, true + } + if !val.IsKnown() { + return ir.Value{}, false + } + + typ := val.Type() + switch { + case typ == cty.String: + return ir.Value{Kind: ir.KindString, Literal: val.AsString()}, true + case typ == cty.Number: + return numberValue(val), true + case typ == cty.Bool: + return ir.Value{Kind: ir.KindBool, Literal: val.True()}, true + case typ.IsListType(), typ.IsSetType(), typ.IsTupleType(): + items := make([]ir.Value, 0, val.LengthInt()) + for it := val.ElementIterator(); it.Next(); { + _, item := it.Element() + converted, ok := fromCty(item) + if !ok { + return ir.Value{}, false + } + items = append(items, converted) + } + return ir.Value{Kind: ir.KindList, Items: items}, true + case typ.IsMapType(), typ.IsObjectType(): + fields := make(map[string]ir.Value, val.LengthInt()) + for it := val.ElementIterator(); it.Next(); { + key, item := it.Element() + converted, ok := fromCty(item) + if !ok { + return ir.Value{}, false + } + fields[key.AsString()] = converted + } + return ir.Value{Kind: ir.KindMap, Fields: fields}, true + default: + return ir.Value{}, false + } +} + +func numberValue(val cty.Value) ir.Value { + f := val.AsBigFloat() + if f.IsInt() { + if i, acc := f.Int64(); acc == big.Exact { + return ir.Value{Kind: ir.KindNumber, Literal: i} + } + } + fl, _ := f.Float64() + return ir.Value{Kind: ir.KindNumber, Literal: fl} +} + +func collectRefs(expr hcl.Expression) []string { + seen := map[string]bool{} + var refs []string + for _, traversal := range expr.Variables() { + addr, ok := traversalAddress(traversal) + if !ok || seen[addr] { + continue + } + seen[addr] = true + refs = append(refs, addr) + } + sort.Strings(refs) + return refs +} + +// traversalAddress maps an HCL traversal to the canonical address of the node +// it starts at, dropping the attribute path. +// +// aws_vpc.main.id -> aws_vpc.main +// var.region -> var.region +// data.aws_ami.ubuntu.id -> data.aws_ami.ubuntu +func traversalAddress(traversal hcl.Traversal) (string, bool) { + parts := make([]string, 0, len(traversal)) + for _, step := range traversal { + switch s := step.(type) { + case hcl.TraverseRoot: + parts = append(parts, s.Name) + case hcl.TraverseAttr: + parts = append(parts, s.Name) + case hcl.TraverseIndex: + // Indexed roots (e.g. each.value) are not static addresses. + return "", false + } + } + if len(parts) == 0 { + return "", false + } + + switch parts[0] { + case "var", "local", "module": + if len(parts) >= 2 { + return parts[0] + "." + parts[1], true + } + case "data": + if len(parts) >= 3 { + return "data." + parts[1] + "." + parts[2], true + } + case "path", "terraform", "count", "each", "self": + return "", false + default: + if len(parts) >= 2 { + return parts[0] + "." + parts[1], true + } + } + return "", false +} + +func sliceRange(src []byte, r hcl.Range) string { + if r.Start.Byte < 0 || r.End.Byte > len(src) || r.Start.Byte > r.End.Byte { + return "" + } + return string(src[r.Start.Byte:r.End.Byte]) +} + +func providerPrefix(resourceType string) string { + if i := strings.IndexByte(resourceType, '_'); i > 0 { + return resourceType[:i] + } + return resourceType +} + +func literalString(v ir.Value) string { + if v.Kind == ir.KindString { + s, _ := v.Literal.(string) + return s + } + return "" +} + +func renderValue(v ir.Value) string { + switch v.Kind { + case ir.KindString: + s, _ := v.Literal.(string) + return fmt.Sprintf("%q", s) + case ir.KindNumber, ir.KindBool, ir.KindNull: + return fmt.Sprint(v.Literal) + case ir.KindExpr: + return v.Expr + default: + return "" + } +} + +// typeText renders a type constraint the way Terraform writes it: the source +// text of the expression, or a plain string for JSON's "type": "string". +func typeText(v ir.Value) string { + if s := strings.TrimSpace(v.Expr); s != "" { + return s + } + if s := literalString(v); s != "" { + return s + } + return strings.TrimSpace(renderValue(v)) +} diff --git a/pkg/parsers/hcl/corpus_test.go b/pkg/parsers/hcl/corpus_test.go new file mode 100644 index 0000000..83c5d8c --- /dev/null +++ b/pkg/parsers/hcl/corpus_test.go @@ -0,0 +1,69 @@ +package hclparser_test + +import ( + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "testing" + + "github.com/be-thomas/openiac/pkg/ir" + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" +) + +// TestParseConformanceCorpus parses every collected fixture module. It is opt-in +// because it walks thousands of files: +// +// OPENIAC_CORPUS=1 go test ./pkg/parsers/hcl -run TestParseConformanceCorpus -count=1 +// +// The corpus is real-world configuration, so it is also the cheapest guard +// against a regression that only shows up outside the hand-written fixtures. +func TestParseConformanceCorpus(t *testing.T) { + if os.Getenv("OPENIAC_CORPUS") == "" { + t.Skip("set OPENIAC_CORPUS=1 to parse the conformance corpus") + } + + root := filepath.Join("..", "..", "..", "conformance", "fixtures") + var inputs []string + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() && entry.Name() == "input" { + inputs = append(inputs, path) + return fs.SkipDir + } + return nil + }) + if err != nil { + t.Fatalf("walk %s: %v", root, err) + } + sort.Strings(inputs) + if len(inputs) == 0 { + t.Fatalf("no fixture inputs found under %s", root) + } + + var failures []string + for _, dir := range inputs { + graph, err := hclparser.ParseDir(dir) + if err != nil { + failures = append(failures, fmt.Sprintf("%s: %v", dir, err)) + continue + } + if graph.Version != ir.Version { + failures = append(failures, fmt.Sprintf("%s: version %q, want %q", dir, graph.Version, ir.Version)) + } + if graph.MinVersion == "" { + failures = append(failures, fmt.Sprintf("%s: min_version is empty", dir)) + } + } + + if len(failures) > 0 { + t.Errorf("%d of %d fixture modules failed to parse:", len(failures), len(inputs)) + for _, failure := range failures { + t.Error(failure) + } + } + t.Logf("parsed %d fixture modules", len(inputs)) +} diff --git a/pkg/parsers/hcl/json.go b/pkg/parsers/hcl/json.go new file mode 100644 index 0000000..29cfcc4 --- /dev/null +++ b/pkg/parsers/hcl/json.go @@ -0,0 +1,141 @@ +package hclparser + +import ( + "fmt" + "strings" + + "github.com/hashicorp/hcl/v2" + "github.com/zclconf/go-cty/cty" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// parseJSONExpr converts an expression that came from a .tf.json document. +// +// It differs from the native path in two ways that make the shared logic +// unusable on its own: +// +// - A JSON expression's Value(nil) treats every string as a literal, so +// "${var.region}" would be stored verbatim with no refs. +// - Value(nil) also evaluates objects and arrays, which would lose the +// refs inside them. +// +// The source shape therefore decides the path: '{' and '[' are decomposed with +// hcl.ExprMap and hcl.ExprList, and only scalars are handed to Value(nil). +func parseJSONExpr(expr hcl.Expression, src []byte) ir.Value { + trimmed := strings.TrimSpace(sliceRange(src, expr.Range())) + + switch { + case strings.HasPrefix(trimmed, "{"): + if value, ok := jsonObject(expr, src); ok { + return value + } + case strings.HasPrefix(trimmed, "["): + if value, ok := jsonArray(expr, src); ok { + return value + } + } + + if value, ok := literalValue(expr); ok { + text, isString := value.Literal.(string) + if value.Kind == ir.KindString && isString && isTemplateText(text) { + // Rendering the decoded text back as an HCL template keeps the + // emitters' existing template handling working unchanged. + quoted := hclQuoteTemplate(text) + return ir.Value{ + Kind: ir.KindExpr, + Expr: quoted, + Raw: quoted, + Refs: collectRefs(expr), + } + } + return value + } + + // Anything left has no literal value. Keep the source text so nothing is + // silently dropped. + raw := strings.TrimSpace(sliceRange(src, expr.Range())) + return ir.Value{ + Kind: ir.KindExpr, + Expr: raw, + Raw: raw, + Refs: collectRefs(expr), + } +} + +func jsonObject(expr hcl.Expression, src []byte) (ir.Value, bool) { + pairs, diags := hcl.ExprMap(expr) + if diags.HasErrors() { + return ir.Value{}, false + } + + fields := make(map[string]ir.Value, len(pairs)) + for _, pair := range pairs { + key, keyDiags := pair.Key.Value(nil) + if keyDiags.HasErrors() || !key.IsKnown() || key.Type() != cty.String { + return ir.Value{}, false + } + fields[key.AsString()] = parseExpr(pair.Value, src) + } + return ir.Value{ + Kind: ir.KindMap, + Fields: fields, + Refs: collectRefs(expr), + }, true +} + +func jsonArray(expr hcl.Expression, src []byte) (ir.Value, bool) { + exprs, diags := hcl.ExprList(expr) + if diags.HasErrors() { + return ir.Value{}, false + } + + items := make([]ir.Value, 0, len(exprs)) + for _, item := range exprs { + items = append(items, parseExpr(item, src)) + } + return ir.Value{ + Kind: ir.KindList, + Items: items, + Refs: collectRefs(expr), + }, true +} + +// isTemplateText reports whether decoded JSON text contains HCL template +// markers, meaning it is an expression rather than a plain string. +func isTemplateText(s string) bool { + return strings.Contains(s, "${") || strings.Contains(s, "%{") +} + +// hclQuoteTemplate renders text as an HCL quoted template. +// +// strconv.Quote cannot be used: HCL does not accept every JSON escape, and the +// template markers themselves must survive. Only the characters that would end +// the string or change its meaning on the way back are escaped. +func hclQuoteTemplate(s string) string { + var b strings.Builder + b.Grow(len(s) + 2) + b.WriteByte('"') + for _, r := range s { + switch r { + case '\\': + b.WriteString(`\\`) + case '"': + b.WriteString(`\"`) + case '\n': + b.WriteString(`\n`) + case '\r': + b.WriteString(`\r`) + case '\t': + b.WriteString(`\t`) + default: + if r < 0x20 || r == 0x7f { + fmt.Fprintf(&b, `\u%04x`, r) + continue + } + b.WriteRune(r) + } + } + b.WriteByte('"') + return b.String() +} diff --git a/pkg/parsers/hcl/json_test.go b/pkg/parsers/hcl/json_test.go new file mode 100644 index 0000000..b6e6360 --- /dev/null +++ b/pkg/parsers/hcl/json_test.go @@ -0,0 +1,396 @@ +package hclparser_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/ir" + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" +) + +const jsonSample = `{ + "terraform": { + "required_version": ">= 1.5.0", + "required_providers": { + "aws": { + "source": "hashicorp/aws", + "version": "~> 5.0" + } + }, + "backend": { + "s3": { + "bucket": "state-bucket", + "key": "terraform.tfstate" + } + } + }, + "variable": { + "region": { + "type": "string", + "default": "us-east-1" + }, + "environment": { + "type": "string", + "default": "dev" + } + }, + "locals": { + "name_prefix": "app-${var.environment}" + }, + "provider": { + "aws": { + "region": "${var.region}" + } + }, + "resource": { + "aws_vpc": { + "main": { + "cidr_block": "10.0.0.0/16", + "tags": { + "Name": "app-${var.environment}", + "Environment": "${var.environment}" + } + } + }, + "aws_subnet": { + "public": { + "vpc_id": "${aws_vpc.main.id}", + "cidr_block": "10.0.1.0/24" + } + }, + "aws_instance": { + "web": { + "ami": "ami-123", + "subnet_id": "${aws_subnet.public.id}", + "depends_on": ["aws_vpc.main"], + "provider": "aws.west" + } + } + }, + "data": { + "aws_ami": { + "ubuntu": { + "most_recent": true + } + } + }, + "module": { + "vpc": { + "source": "./modules/vpc", + "version": "1.2.0" + } + }, + "output": { + "bucket_arn": { + "value": "${aws_s3_bucket.logs.arn}", + "description": "Logs bucket" + } + } +}` + +func parseJSONSample(t *testing.T) *ir.Graph { + t.Helper() + graph, err := hclparser.ParseString(jsonSample, "main.tf.json") + if err != nil { + t.Fatalf("ParseString(.tf.json): %v", err) + } + return graph +} + +func TestJSONResources(t *testing.T) { + graph := parseJSONSample(t) + + if got, want := len(graph.Resources), 4; got != want { + t.Fatalf("resources = %d, want %d", got, want) + } + vpc := graph.ResourceByID("aws_vpc.main") + if vpc == nil { + t.Fatal("aws_vpc.main missing") + } + if vpc.Provider != "aws" { + t.Errorf("provider = %q, want aws", vpc.Provider) + } + if cidr := vpc.Attributes["cidr_block"]; cidr.Kind != ir.KindString || cidr.Literal != "10.0.0.0/16" { + t.Errorf("cidr_block = %#v", cidr) + } + + ami := graph.ResourceByID("data.aws_ami.ubuntu") + if ami == nil { + t.Fatal("data.aws_ami.ubuntu missing") + } + if ami.Kind != ir.KindData { + t.Errorf("data kind = %q", ami.Kind) + } +} + +func TestJSONInterpolationBecomesExpression(t *testing.T) { + graph := parseJSONSample(t) + vpc := graph.ResourceByID("aws_vpc.main") + + tags := vpc.Attributes["tags"] + if tags.Kind != ir.KindMap { + t.Fatalf("tags kind = %q, want map", tags.Kind) + } + env, ok := tags.Fields["Environment"] + if !ok { + t.Fatal("tags.Environment missing") + } + if env.Kind != ir.KindExpr { + t.Fatalf("tags.Environment kind = %q, want expr", env.Kind) + } + if !contains(env.Refs, "var.environment") { + t.Errorf("refs = %v, want var.environment", env.Refs) + } + if !strings.Contains(env.Expr, "var.environment") { + t.Errorf("expr = %q, want a template with var.environment", env.Expr) + } + if !strings.HasPrefix(env.Expr, `"`) { + t.Errorf("expr = %q, want an HCL quoted template", env.Expr) + } +} + +func TestJSONDependsOnAndProvider(t *testing.T) { + graph := parseJSONSample(t) + instance := graph.ResourceByID("aws_instance.web") + if instance == nil { + t.Fatal("aws_instance.web missing") + } + if len(instance.DependsOn) != 1 || instance.DependsOn[0] != "aws_vpc.main" { + t.Errorf("DependsOn = %v, want [aws_vpc.main]", instance.DependsOn) + } + if instance.ProviderAlias != "aws.west" { + t.Errorf("ProviderAlias = %q, want aws.west", instance.ProviderAlias) + } + if _, ok := instance.Attributes["depends_on"]; ok { + t.Error("depends_on should not stay in attributes") + } + if !hasEdge(graph, "aws_instance.web", "aws_vpc.main") { + t.Error("missing depends_on edge aws_instance.web -> aws_vpc.main") + } + if !hasEdge(graph, "aws_subnet.public", "aws_vpc.main") { + t.Error("missing reference edge aws_subnet.public -> aws_vpc.main") + } +} + +func TestJSONTerraformMetadata(t *testing.T) { + graph := parseJSONSample(t) + tf := graph.Terraform + if tf == nil { + t.Fatal("terraform metadata missing") + } + if tf.RequiredVersion != ">= 1.5.0" { + t.Errorf("required_version = %q", tf.RequiredVersion) + } + if tf.Backend == nil || len(tf.Backend.Labels) != 1 || tf.Backend.Labels[0] != "s3" { + t.Fatalf("backend = %#v, want s3", tf.Backend) + } + if tf.Backend.File != "main.tf.json" { + // JSON bodies are flat, so the enclosing terraform block supplies the file. + t.Errorf("backend file = %q, want main.tf.json", tf.Backend.File) + } + if got := tf.Backend.Attributes["bucket"]; got.Kind != ir.KindString || got.Literal != "state-bucket" { + t.Errorf("backend bucket = %#v", got) + } + aws, ok := tf.RequiredProviders["aws"] + if !ok || aws.Kind != ir.KindMap { + t.Fatalf("required_providers.aws = %#v", aws) + } + if source := aws.Fields["source"]; source.Kind != ir.KindString || source.Literal != "hashicorp/aws" { + t.Errorf("aws source = %#v", source) + } +} + +func TestJSONVariablesAndModules(t *testing.T) { + graph := parseJSONSample(t) + + if len(graph.Variables) != 2 { + t.Fatalf("variables = %d, want 2", len(graph.Variables)) + } + region := graph.Variables[0] + if region.Name != "region" { + t.Fatalf("first variable = %q, want region", region.Name) + } + if region.Type != "string" { + t.Errorf("region type = %q, want string", region.Type) + } + if region.Default == nil || region.Default.Literal != "us-east-1" { + t.Errorf("region default = %#v", region.Default) + } + if region.File != "main.tf.json" || region.Line == 0 { + t.Errorf("region provenance = %q:%d", region.File, region.Line) + } + + if len(graph.Modules) != 1 { + t.Fatalf("modules = %d, want 1", len(graph.Modules)) + } + module := graph.Modules[0] + if module.Name != "vpc" || module.Source != "./modules/vpc" || module.Version != "1.2.0" { + t.Errorf("module = %#v", module) + } + if _, ok := module.Attributes["source"]; ok { + t.Error("source should be typed, not duplicated in attributes") + } + + if len(graph.Providers) != 1 || graph.Providers[0].Name != "aws" { + t.Fatalf("providers = %#v", graph.Providers) + } + regionAttr := graph.Providers[0].Attributes["region"] + if regionAttr.Kind != ir.KindExpr || !contains(regionAttr.Refs, "var.region") { + t.Errorf("provider region = %#v", regionAttr) + } +} + +func TestJSONLocalsAndOutputs(t *testing.T) { + graph := parseJSONSample(t) + + if len(graph.Locals) != 1 { + t.Fatalf("locals = %d, want 1", len(graph.Locals)) + } + prefix := graph.Locals[0] + if prefix.Name != "name_prefix" || prefix.Value.Kind != ir.KindExpr { + t.Errorf("local = %#v", prefix) + } + if !contains(prefix.Value.Refs, "var.environment") { + t.Errorf("local refs = %v", prefix.Value.Refs) + } + + if len(graph.Outputs) != 1 { + t.Fatalf("outputs = %d, want 1", len(graph.Outputs)) + } + out := graph.Outputs[0] + if out.Name != "bucket_arn" || out.Description != "Logs bucket" { + t.Errorf("output = %#v", out) + } + if !contains(out.Value.Refs, "aws_s3_bucket.logs") { + t.Errorf("output refs = %v, want aws_s3_bucket.logs", out.Value.Refs) + } +} + +func TestJSONEscapesAndEmptyCollections(t *testing.T) { + graph, err := hclparser.ParseString(`{ + "resource": { + "aws_ssm_parameter": { + "quoted": { + "value": "a \"quoted\" \\ value\nsecond line ${var.suffix}", + "empty_object": {}, + "empty_array": [], + "numbers": [1, 2.5, true, null] + } + } + } +}`, "main.tf.json") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + + param := graph.ResourceByID("aws_ssm_parameter.quoted") + if param == nil { + t.Fatal("resource missing") + } + + value := param.Attributes["value"] + if value.Kind != ir.KindExpr { + t.Fatalf("value kind = %q, want expr", value.Kind) + } + if !strings.Contains(value.Expr, `\"quoted\"`) { + t.Errorf("value expr lost the escaped quote: %q", value.Expr) + } + if !strings.Contains(value.Expr, `\n`) { + t.Errorf("value expr lost the escaped newline: %q", value.Expr) + } + if !contains(value.Refs, "var.suffix") { + t.Errorf("value refs = %v, want var.suffix", value.Refs) + } + + if got := param.Attributes["empty_object"]; got.Kind != ir.KindMap { + t.Errorf("empty_object kind = %q, want map", got.Kind) + } + if got := param.Attributes["empty_array"]; got.Kind != ir.KindList { + t.Errorf("empty_array kind = %q, want list", got.Kind) + } + + numbers := param.Attributes["numbers"] + if numbers.Kind != ir.KindList || len(numbers.Items) != 4 { + t.Fatalf("numbers = %#v", numbers) + } + want := []ir.ValueKind{ir.KindNumber, ir.KindNumber, ir.KindBool, ir.KindNull} + for i, kind := range want { + if numbers.Items[i].Kind != kind { + t.Errorf("numbers[%d] kind = %q, want %q", i, numbers.Items[i].Kind, kind) + } + } +} + +func TestJSONUnknownPropertyIsPreserved(t *testing.T) { + graph, err := hclparser.ParseString(`{ + "future_block": { + "from": "a", + "to": "b" + }, + "repeated": [{"n": 1}, {"n": 2}], + "scalar": 42, + "resource": {"aws_vpc": {"main": {}}} +}`, "main.tf.json") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + + byType := map[string][]ir.Block{} + for _, b := range graph.Preserved { + byType[b.Type] = append(byType[b.Type], b) + } + if got := len(byType["future_block"]); got != 1 { + t.Fatalf("future_block preserved %d times, want 1", got) + } + if _, ok := byType["future_block"][0].Attributes["from"]; !ok { + t.Error("future_block attributes missing") + } + if got := len(byType["repeated"]); got != 2 { + t.Errorf("repeated preserved %d times, want 2", got) + } + scalar := byType["scalar"] + if len(scalar) != 1 || scalar[0].Body == nil || scalar[0].Body.Literal != int64(42) { + t.Errorf("scalar preserved = %#v", scalar) + } + if len(graph.Resources) != 1 { + t.Errorf("resources = %d, want 1", len(graph.Resources)) + } +} + +func TestJSONMalformed(t *testing.T) { + if _, err := hclparser.ParseString(`{"resource": `, "broken.tf.json"); err == nil { + t.Fatal("expected a parse error") + } +} + +func TestParseDirMixedSyntax(t *testing.T) { + dir := t.TempDir() + files := map[string]string{ + "vpc.tf": `resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" }`, + "subnet.tf.json": `{ + "resource": { + "aws_subnet": { + "public": {"vpc_id": "${aws_vpc.main.id}"} + } + } +}`, + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + graph, err := hclparser.ParseDir(dir) + if err != nil { + t.Fatalf("ParseDir: %v", err) + } + if len(graph.Resources) != 2 { + t.Fatalf("resources = %d, want 2", len(graph.Resources)) + } + if !hasEdge(graph, "aws_subnet.public", "aws_vpc.main") { + t.Error("cross-syntax edge missing") + } +} diff --git a/pkg/parsers/hcl/parser.go b/pkg/parsers/hcl/parser.go index 436cdfa..d64b06a 100644 --- a/pkg/parsers/hcl/parser.go +++ b/pkg/parsers/hcl/parser.go @@ -1,10 +1,18 @@ -// Package hclparser reads Terraform HCL (HCL2 / Terraform 0.12+) into the -// OpenIaC intermediate representation. +// Package hclparser reads Terraform configuration into the OpenIaC +// intermediate representation. +// +// Both syntaxes Terraform accepts are supported: native HCL (.tf) and JSON +// (.tf.json). Native HCL keeps its full block structure; JSON bodies below the +// top level cannot express blocks, so an object property becomes a map value. +// +// The parser accepts the whole Terraform 1.x configuration language. Constructs +// the IR has no typed node for β moved, import, removed, check, ephemeral, +// action and anything newer β are preserved in the graph instead of dropped, so +// emitters can warn about them. See docs/TERRAFORM-VERSIONS.md. package hclparser import ( "fmt" - "math/big" "os" "path/filepath" "sort" @@ -13,12 +21,13 @@ import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclparse" "github.com/hashicorp/hcl/v2/hclsyntax" - "github.com/zclconf/go-cty/cty" "github.com/be-thomas/openiac/pkg/ir" + "github.com/be-thomas/openiac/pkg/tfversion" ) -// ParseDir parses every top-level .tf file in dir. +// ParseDir parses every Terraform configuration file directly inside dir. +// Subdirectories are not descended into: they are usually modules. func ParseDir(dir string) (*ir.Graph, error) { entries, err := os.ReadDir(dir) if err != nil { @@ -27,30 +36,25 @@ func ParseDir(dir string) (*ir.Graph, error) { var paths []string for _, entry := range entries { - if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".tf") { + if entry.IsDir() || !isTerraformFile(entry.Name()) { continue } paths = append(paths, filepath.Join(dir, entry.Name())) } if len(paths) == 0 { - return nil, fmt.Errorf("no .tf files found in %s", dir) + return nil, fmt.Errorf("no Terraform configuration files (*.tf, *.tf.json) found in %s", dir) } sort.Strings(paths) return ParseFiles(paths) } -// ParseFiles parses the given .tf files into one graph. +// ParseFiles parses the given Terraform configuration files into one graph. +// Native HCL and JSON files may be mixed. func ParseFiles(paths []string) (*ir.Graph, error) { p := &parser{ graph: ir.New(strings.Join(paths, ",")), src: make(map[string][]byte, len(paths)), } - - type parsedFile struct { - name string - file *hcl.File - } - files := make([]parsedFile, 0, len(paths)) hclParser := hclparse.NewParser() for _, path := range paths { @@ -58,50 +62,67 @@ func ParseFiles(paths []string) (*ir.Graph, error) { if err != nil { return nil, fmt.Errorf("read %s: %w", path, err) } - file, diags := hclParser.ParseHCL(src, path) + + var ( + file *hcl.File + diags hcl.Diagnostics + ) + if isJSONFile(path) { + file, diags = hclParser.ParseJSON(src, path) + } else { + file, diags = hclParser.ParseHCL(src, path) + } if diags.HasErrors() { return nil, fmt.Errorf("parse %s:\n%s", path, diags.Error()) } - p.src[path] = src - files = append(files, parsedFile{name: path, file: file}) - } - for _, f := range files { - body, ok := f.file.Body.(*hclsyntax.Body) - if !ok { - return nil, fmt.Errorf("%s: expected native HCL syntax", f.name) - } - if err := p.parseTopLevel(f.name, body); err != nil { + p.src[path] = src + if err := p.parseFile(path, file); err != nil { return nil, err } } - - p.resolveEdges() - return p.graph, nil + return p.finish() } -// ParseString parses HCL source held in memory. It powers the WASM playground. +// ParseString parses Terraform source held in memory. It powers the WASM +// playground. The filename's suffix selects the syntax, exactly as ParseFiles +// does. func ParseString(src, filename string) (*ir.Graph, error) { if filename == "" { filename = "input.tf" } + p := &parser{ graph: ir.New(filename), src: map[string][]byte{filename: []byte(src)}, } - file, diags := hclparse.NewParser().ParseHCL([]byte(src), filename) + + hclParser := hclparse.NewParser() + var ( + file *hcl.File + diags hcl.Diagnostics + ) + if isJSONFile(filename) { + file, diags = hclParser.ParseJSON([]byte(src), filename) + } else { + file, diags = hclParser.ParseHCL([]byte(src), filename) + } if diags.HasErrors() { return nil, fmt.Errorf("parse %s:\n%s", filename, diags.Error()) } - body, ok := file.Body.(*hclsyntax.Body) - if !ok { - return nil, fmt.Errorf("%s: expected native HCL syntax", filename) - } - if err := p.parseTopLevel(filename, body); err != nil { + + if err := p.parseFile(filename, file); err != nil { return nil, err } - p.resolveEdges() - return p.graph, nil + return p.finish() +} + +func isTerraformFile(name string) bool { + return strings.HasSuffix(name, ".tf") || isJSONFile(name) +} + +func isJSONFile(name string) bool { + return strings.HasSuffix(strings.ToLower(name), ".tf.json") } type parser struct { @@ -109,60 +130,144 @@ type parser struct { src map[string][]byte } -func (p *parser) parseTopLevel(filename string, body *hclsyntax.Body) error { - src := p.src[filename] +// block is the syntax-independent view of a top-level block. Native HCL and +// JSON differ only in how the block is recovered; everything downstream reads +// the body through hcl.Body. +type block struct { + file string + typ string + labels []string + body hcl.Body + line int +} - for _, block := range body.Blocks { - switch block.Type { - case "resource": - if len(block.Labels) != 2 { - return fmt.Errorf("%s:%d: resource block needs type and name labels", filename, block.TypeRange.Start.Line) - } - p.addResource(filename, src, ir.KindResource, block) - case "data": - if len(block.Labels) != 2 { - return fmt.Errorf("%s:%d: data block needs type and name labels", filename, block.TypeRange.Start.Line) - } - p.addResource(filename, src, ir.KindData, block) - case "variable": - if len(block.Labels) != 1 { - return fmt.Errorf("%s:%d: variable block needs a name label", filename, block.TypeRange.Start.Line) - } - p.addVariable(src, block) - case "locals": - p.addLocals(src, block) - case "output": - if len(block.Labels) != 1 { - return fmt.Errorf("%s:%d: output block needs a name label", filename, block.TypeRange.Start.Line) - } - p.addOutput(src, block) - case "module": - if len(block.Labels) != 1 { - return fmt.Errorf("%s:%d: module block needs a name label", filename, block.TypeRange.Start.Line) - } - p.addModule(src, block) - case "provider": - if len(block.Labels) != 1 { - return fmt.Errorf("%s:%d: provider block needs a name label", filename, block.TypeRange.Start.Line) - } - p.addProvider(src, block) - case "terraform": - // Backend and required_providers metadata do not affect the graph. - default: - // Unknown top-level blocks are ignored, matching Terraform's forward - // compatibility behaviour for future block types. +func (p *parser) parseFile(path string, file *hcl.File) error { + if native, ok := file.Body.(*hclsyntax.Body); ok { + return p.parseNative(path, native) + } + return p.parseJSON(path, file.Body) +} + +func (p *parser) parseNative(filename string, body *hclsyntax.Body) error { + for _, b := range body.Blocks { + blk := block{ + file: filename, + typ: b.Type, + labels: b.Labels, + body: b.Body, + line: b.TypeRange.Start.Line, + } + if err := p.addTopLevel(blk); err != nil { + return err + } + } + + // Terraform rejects arguments at the top level, but a parser that silently + // drops them is worse than one that keeps them. + names := make([]string, 0, len(body.Attributes)) + for name := range body.Attributes { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + attr := body.Attributes[name] + value := parseExpr(attr.Expr, p.src[filename]) + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: name, + Body: &value, + File: filename, + Line: attr.SrcRange.Start.Line, + }) + } + return nil +} + +func (p *parser) parseJSON(filename string, body hcl.Body) error { + content, remain, diags := body.PartialContent(topLevelSchema) + if diags.HasErrors() { + return fmt.Errorf("parse %s:\n%s", filename, diags.Error()) + } + + for _, b := range content.Blocks { + blk := block{ + file: filename, + typ: b.Type, + labels: b.Labels, + body: b.Body, + line: b.TypeRange.Start.Line, + } + if err := p.addTopLevel(blk); err != nil { + return err } } + + // The schema hides what it consumed, so everything left is an unknown + // top-level property: either a block type this parser does not know yet, or + // an argument Terraform would reject. Preserve it. + attributes, attrDiags := remain.JustAttributes() + if attrDiags.HasErrors() { + return fmt.Errorf("parse %s:\n%s", filename, attrDiags.Error()) + } + names := make([]string, 0, len(attributes)) + for name := range attributes { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + p.preserveJSONProperty(filename, name, attributes[name].Expr, attributes[name].NameRange.Start.Line) + } return nil } -func (p *parser) addResource(filename string, src []byte, kind ir.Kind, block *hclsyntax.Block) { - resourceType, name := block.Labels[0], block.Labels[1] - attrs, blocks := parseBody(*block.Body, src) +func (p *parser) addTopLevel(blk block) error { + if want, known := topLevelLabelCount[blk.typ]; known && len(blk.labels) != want { + return labelError(blk) + } + switch blk.typ { + case "terraform": + return p.addTerraform(blk) + case "locals": + return p.addLocals(blk) + case "resource": + return p.addResource(blk, ir.KindResource) + case "data": + return p.addResource(blk, ir.KindData) + case "variable": + return p.addVariable(blk) + case "output": + return p.addOutput(blk) + case "module": + return p.addModule(blk) + case "provider": + return p.addProvider(blk) + default: + return p.preserveBlock(blk) + } +} + +func labelError(blk block) error { + switch topLevelLabelCount[blk.typ] { + case 0: + return fmt.Errorf("%s:%d: %s block takes no labels", blk.file, blk.line, blk.typ) + case 1: + return fmt.Errorf("%s:%d: %s block needs a name label", blk.file, blk.line, blk.typ) + default: + return fmt.Errorf("%s:%d: %s block needs type and name labels", blk.file, blk.line, blk.typ) + } +} + +func (p *parser) addResource(blk block, kind ir.Kind) error { + src := p.src[blk.file] + attrs, blocks, err := parseBody(blk.body, src) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + resourceType, name := blk.labels[0], blk.labels[1] id := resourceType + "." + name if kind == ir.KindData { - id = "data." + resourceType + "." + name + id = "data." + id } res := &ir.Resource{ @@ -173,79 +278,166 @@ func (p *parser) addResource(filename string, src []byte, kind ir.Kind, block *h Provider: providerPrefix(resourceType), Attributes: attrs, Blocks: blocks, - File: filename, - Line: block.TypeRange.Start.Line, + File: blk.file, + Line: blk.line, } if meta, ok := attrs["depends_on"]; ok { - res.DependsOn = append(res.DependsOn, meta.Refs...) + res.DependsOn = append(res.DependsOn, valueAddresses(meta)...) delete(attrs, "depends_on") } if meta, ok := attrs["provider"]; ok { - res.ProviderAlias = strings.TrimSpace(meta.Expr) + res.ProviderAlias = providerAddress(meta) delete(attrs, "provider") } + if len(attrs) == 0 { + res.Attributes = nil + } p.graph.Resources = append(p.graph.Resources, res) + return nil } -func (p *parser) addVariable(src []byte, block *hclsyntax.Block) { - attrs, _ := parseBody(*block.Body, src) - v := &ir.Variable{Name: block.Labels[0]} +func (p *parser) addVariable(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + v := &ir.Variable{ + Name: blk.labels[0], + Blocks: blocks, + File: blk.file, + Line: blk.line, + } + if typeExpr, ok := attrs["type"]; ok { - v.Type = strings.TrimSpace(typeExpr.Expr) - if v.Type == "" { - v.Type = renderValue(typeExpr) - } + v.Type = typeText(typeExpr) + delete(attrs, "type") } if def, ok := attrs["default"]; ok { v.Default = &def + delete(attrs, "default") } if desc, ok := attrs["description"]; ok { v.Description = literalString(desc) + delete(attrs, "description") } - if sensitive, ok := attrs["sensitive"]; ok { - v.Sensitive = sensitive.Kind == ir.KindBool && sensitive.Literal == true + if sensitive, ok := attrs["sensitive"]; ok && sensitive.Kind == ir.KindBool { + v.Sensitive = sensitive.Literal == true + delete(attrs, "sensitive") } + if nullable, ok := attrs["nullable"]; ok && nullable.Kind == ir.KindBool { + value := nullable.Literal == true + v.Nullable = &value + delete(attrs, "nullable") + } + if ephemeral, ok := attrs["ephemeral"]; ok && ephemeral.Kind == ir.KindBool { + v.Ephemeral = ephemeral.Literal == true + delete(attrs, "ephemeral") + } + if deprecated, ok := attrs["deprecated"]; ok { + v.Deprecated = literalString(deprecated) + delete(attrs, "deprecated") + } + if len(attrs) > 0 { + v.Attributes = attrs + } + p.graph.Variables = append(p.graph.Variables, v) + return nil } -func (p *parser) addLocals(src []byte, block *hclsyntax.Block) { - body := block.Body - names := make([]string, 0, len(body.Attributes)) - for name := range body.Attributes { +func (p *parser) addLocals(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + names := make([]string, 0, len(attrs)) + for name := range attrs { names = append(names, name) } sort.Strings(names) for _, name := range names { p.graph.Locals = append(p.graph.Locals, &ir.Local{ Name: name, - Value: parseExpr(body.Attributes[name].Expr, src), + Value: attrs[name], + File: blk.file, + Line: blk.line, + }) + } + + // A locals block cannot contain nested blocks. If one appears anyway, keep + // it rather than drop it. + if len(blocks) > 0 { + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: blk.typ, + Blocks: blocks, + File: blk.file, + Line: blk.line, }) } + return nil } -func (p *parser) addOutput(src []byte, block *hclsyntax.Block) { - attrs, _ := parseBody(*block.Body, src) - out := &ir.Output{Name: block.Labels[0]} +func (p *parser) addOutput(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + out := &ir.Output{ + Name: blk.labels[0], + Blocks: blocks, + File: blk.file, + Line: blk.line, + } + if value, ok := attrs["value"]; ok { out.Value = value + delete(attrs, "value") } if desc, ok := attrs["description"]; ok { out.Description = literalString(desc) + delete(attrs, "description") + } + if sensitive, ok := attrs["sensitive"]; ok && sensitive.Kind == ir.KindBool { + out.Sensitive = sensitive.Literal == true + delete(attrs, "sensitive") + } + if typeExpr, ok := attrs["type"]; ok { + out.Type = typeText(typeExpr) + delete(attrs, "type") + } + if ephemeral, ok := attrs["ephemeral"]; ok && ephemeral.Kind == ir.KindBool { + out.Ephemeral = ephemeral.Literal == true + delete(attrs, "ephemeral") + } + if deprecated, ok := attrs["deprecated"]; ok { + out.Deprecated = literalString(deprecated) + delete(attrs, "deprecated") } - if sensitive, ok := attrs["sensitive"]; ok { - out.Sensitive = sensitive.Kind == ir.KindBool && sensitive.Literal == true + if len(attrs) > 0 { + out.Attributes = attrs } + p.graph.Outputs = append(p.graph.Outputs, out) + return nil } -func (p *parser) addModule(src []byte, block *hclsyntax.Block) { - attrs, blocks := parseBody(*block.Body, src) +func (p *parser) addModule(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + m := &ir.Module{ - Name: block.Labels[0], + Name: blk.labels[0], Attributes: attrs, Blocks: blocks, + File: blk.file, + Line: blk.line, } if source, ok := attrs["source"]; ok { m.Source = literalString(source) @@ -255,18 +447,43 @@ func (p *parser) addModule(src []byte, block *hclsyntax.Block) { m.Version = literalString(version) delete(attrs, "version") } + if len(attrs) == 0 { + m.Attributes = nil + } + p.graph.Modules = append(p.graph.Modules, m) + return nil } -func (p *parser) addProvider(src []byte, block *hclsyntax.Block) { - attrs, _ := parseBody(*block.Body, src) - provider := &ir.Provider{Name: block.Labels[0]} +func (p *parser) addProvider(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + provider := &ir.Provider{ + Name: blk.labels[0], + Blocks: blocks, + File: blk.file, + Line: blk.line, + } if alias, ok := attrs["alias"]; ok { provider.Alias = literalString(alias) delete(attrs, "alias") } - provider.Attributes = attrs + if len(attrs) > 0 { + provider.Attributes = attrs + } + p.graph.Providers = append(p.graph.Providers, provider) + return nil +} + +// finish resolves edges and records the language features the graph needs. +func (p *parser) finish() (*ir.Graph, error) { + p.resolveEdges() + p.graph.Features, p.graph.MinVersion = tfversion.Analyze(p.graph) + return p.graph, nil } // resolveEdges turns value references into graph edges now that every node @@ -327,243 +544,37 @@ func blockRefs(block ir.Block) []string { return refs } -func parseBody(body hclsyntax.Body, src []byte) (map[string]ir.Value, []ir.Block) { - attrs := make(map[string]ir.Value, len(body.Attributes)) - names := make([]string, 0, len(body.Attributes)) - for name := range body.Attributes { - names = append(names, name) - } - sort.Strings(names) - for _, name := range names { - attrs[name] = parseExpr(body.Attributes[name].Expr, src) - } - - blocks := make([]ir.Block, 0, len(body.Blocks)) - for _, block := range body.Blocks { - blockAttrs, nested := parseBody(*block.Body, src) - blocks = append(blocks, ir.Block{ - Type: block.Type, - Labels: block.Labels, - Attributes: blockAttrs, - Blocks: nested, - Line: block.TypeRange.Start.Line, - }) - } - return attrs, blocks -} - -func parseExpr(expr hclsyntax.Expression, src []byte) ir.Value { - raw := sliceRange(src, expr.Range()) - - if value, ok := literalValue(expr); ok { - return value - } - if value, ok := structuredValue(expr, src); ok { - return value - } - return ir.Value{ - Kind: ir.KindExpr, - Expr: raw, - Raw: raw, - Refs: collectRefs(expr), - } -} - -// structuredValue handles collections that mix literals and expressions, such -// as tags = { Name = "x", Env = var.environment }. Evaluating such a value -// fails, but its shape is still static and can be represented in the IR. -func structuredValue(expr hclsyntax.Expression, src []byte) (ir.Value, bool) { - switch e := expr.(type) { - case *hclsyntax.ParenthesesExpr: - return structuredValue(e.Expression, src) - case *hclsyntax.ObjectConsExpr: - fields := make(map[string]ir.Value, len(e.Items)) - for _, item := range e.Items { - key, diags := item.KeyExpr.Value(nil) - if diags.HasErrors() || !key.IsKnown() || key.Type() != cty.String { - return ir.Value{}, false - } - fields[key.AsString()] = parseExpr(item.ValueExpr, src) - } - return ir.Value{ - Kind: ir.KindMap, - Fields: fields, - Refs: collectRefs(expr), - }, true - case *hclsyntax.TupleConsExpr: - items := make([]ir.Value, 0, len(e.Exprs)) - for _, item := range e.Exprs { - items = append(items, parseExpr(item, src)) - } - return ir.Value{ - Kind: ir.KindList, - Items: items, - Refs: collectRefs(expr), - }, true - default: - return ir.Value{}, false - } -} - -// literalValue evaluates an expression only if it is self-contained. Anything -// that reads a variable, resource or function is left as an expression. -func literalValue(expr hclsyntax.Expression) (value ir.Value, ok bool) { - defer func() { - if recover() != nil { - value, ok = ir.Value{}, false - } - }() - - val, diags := expr.Value(nil) - if diags.HasErrors() || val == cty.NilVal || !val.IsWhollyKnown() { - return ir.Value{}, false - } - return fromCty(val) -} - -func fromCty(val cty.Value) (ir.Value, bool) { - if val.IsNull() { - return ir.Value{Kind: ir.KindNull}, true - } - if !val.IsKnown() { - return ir.Value{}, false - } - - typ := val.Type() - switch { - case typ == cty.String: - return ir.Value{Kind: ir.KindString, Literal: val.AsString()}, true - case typ == cty.Number: - return numberValue(val), true - case typ == cty.Bool: - return ir.Value{Kind: ir.KindBool, Literal: val.True()}, true - case typ.IsListType(), typ.IsSetType(), typ.IsTupleType(): - items := make([]ir.Value, 0, val.LengthInt()) - for it := val.ElementIterator(); it.Next(); { - _, item := it.Element() - converted, ok := fromCty(item) - if !ok { - return ir.Value{}, false - } - items = append(items, converted) - } - return ir.Value{Kind: ir.KindList, Items: items}, true - case typ.IsMapType(), typ.IsObjectType(): - fields := make(map[string]ir.Value, val.LengthInt()) - for it := val.ElementIterator(); it.Next(); { - key, item := it.Element() - converted, ok := fromCty(item) - if !ok { - return ir.Value{}, false - } - fields[key.AsString()] = converted - } - return ir.Value{Kind: ir.KindMap, Fields: fields}, true - default: - return ir.Value{}, false - } -} - -func numberValue(val cty.Value) ir.Value { - f := val.AsBigFloat() - if f.IsInt() { - if i, acc := f.Int64(); acc == big.Exact { - return ir.Value{Kind: ir.KindNumber, Literal: i} - } - } - fl, _ := f.Float64() - return ir.Value{Kind: ir.KindNumber, Literal: fl} -} - -func collectRefs(expr hclsyntax.Expression) []string { - seen := map[string]bool{} - var refs []string - for _, traversal := range expr.Variables() { - addr, ok := traversalAddress(traversal) - if !ok || seen[addr] { - continue - } - seen[addr] = true - refs = append(refs, addr) - } - sort.Strings(refs) - return refs -} - -// traversalAddress maps an HCL traversal to the canonical address of the node -// it starts at, dropping the attribute path. -// -// aws_vpc.main.id -> aws_vpc.main -// var.region -> var.region -// data.aws_ami.ubuntu.id -> data.aws_ami.ubuntu -func traversalAddress(traversal hcl.Traversal) (string, bool) { - parts := make([]string, 0, len(traversal)) - for _, step := range traversal { - switch s := step.(type) { - case hcl.TraverseRoot: - parts = append(parts, s.Name) - case hcl.TraverseAttr: - parts = append(parts, s.Name) - case hcl.TraverseIndex: - // Indexed roots (e.g. each.value) are not static addresses. - return "", false - } - } - if len(parts) == 0 { - return "", false - } - - switch parts[0] { - case "var", "local", "module": - if len(parts) >= 2 { - return parts[0] + "." + parts[1], true - } - case "data": - if len(parts) >= 3 { - return "data." + parts[1] + "." + parts[2], true - } - case "path", "terraform", "count", "each", "self": - return "", false - default: - if len(parts) >= 2 { - return parts[0] + "." + parts[1], true - } - } - return "", false -} - -func sliceRange(src []byte, r hcl.Range) string { - if r.Start.Byte < 0 || r.End.Byte > len(src) || r.Start.Byte > r.End.Byte { - return "" - } - return string(src[r.Start.Byte:r.End.Byte]) -} - -func providerPrefix(resourceType string) string { - if i := strings.IndexByte(resourceType, '_'); i > 0 { - return resourceType[:i] - } - return resourceType -} - -func literalString(v ir.Value) string { - if v.Kind == ir.KindString { - s, _ := v.Literal.(string) +// providerAddress renders a provider meta-argument. Native HCL gives an +// expression (aws.west); JSON gives a plain string when it is written as one. +func providerAddress(v ir.Value) string { + if s := strings.TrimSpace(v.Expr); s != "" { return s } - return "" + return strings.TrimSpace(literalString(v)) } -func renderValue(v ir.Value) string { +// valueAddresses flattens a depends_on argument into node addresses. Both +// depends_on = [aws_vpc.main] and JSON's ["aws_vpc.main"] are accepted. +func valueAddresses(v ir.Value) []string { switch v.Kind { + case ir.KindList: + var out []string + for _, item := range v.Items { + out = append(out, valueAddresses(item)...) + } + return out case ir.KindString: - s, _ := v.Literal.(string) - return fmt.Sprintf("%q", s) - case ir.KindNumber, ir.KindBool, ir.KindNull: - return fmt.Sprint(v.Literal) + if s := strings.TrimSpace(literalString(v)); s != "" { + return []string{s} + } + return nil case ir.KindExpr: - return v.Expr - default: - return "" + if len(v.Refs) > 0 { + return v.Refs + } + if s := strings.TrimSpace(v.Expr); s != "" { + return []string{s} + } } + return nil } diff --git a/pkg/parsers/hcl/preserve.go b/pkg/parsers/hcl/preserve.go new file mode 100644 index 0000000..900ab9b --- /dev/null +++ b/pkg/parsers/hcl/preserve.go @@ -0,0 +1,86 @@ +package hclparser + +import ( + "fmt" + + "github.com/hashicorp/hcl/v2" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// preserveBlock keeps a top-level block the IR has no typed node for: moved, +// import, removed, check, ephemeral, action, and any block type a later +// Terraform release adds. +// +// A preserved block never becomes a graph node, so it cannot affect +// dependencies, ordering or resource statistics. Emitters report it with a +// warning instead. +func (p *parser) preserveBlock(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: blk.typ, + Labels: append([]string(nil), blk.labels...), + Attributes: attrs, + Blocks: blocks, + File: blk.file, + Line: blk.line, + }) + return nil +} + +// preserveJSONProperty keeps a top-level property of a .tf.json document that +// the schema did not claim. +// +// JSON spells blocks in three shapes, and only one of them can be told apart +// from an ordinary value without a schema: +// +// "moved": {"from": "a", "to": "b"} one block, properties are arguments +// "moved": [{...}, {...}] one block per element +// "future": "scalar" cannot be a block +// +// The first two are recovered; anything else is kept whole in Body rather than +// guessed at. +func (p *parser) preserveJSONProperty(filename, name string, expr hcl.Expression, line int) { + value := parseExpr(expr, p.src[filename]) + + switch value.Kind { + case ir.KindMap: + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: name, + Attributes: value.Fields, + File: filename, + Line: line, + }) + case ir.KindList: + for _, item := range value.Items { + if item.Kind != ir.KindMap { + p.preserveJSONBody(filename, name, value, line) + return + } + } + for _, item := range value.Items { + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: name, + Attributes: item.Fields, + File: filename, + Line: line, + }) + } + default: + p.preserveJSONBody(filename, name, value, line) + } +} + +func (p *parser) preserveJSONBody(filename, name string, value ir.Value, line int) { + body := value + p.graph.Preserved = append(p.graph.Preserved, ir.Block{ + Type: name, + Body: &body, + File: filename, + Line: line, + }) +} diff --git a/pkg/parsers/hcl/preserve_test.go b/pkg/parsers/hcl/preserve_test.go new file mode 100644 index 0000000..9b09214 --- /dev/null +++ b/pkg/parsers/hcl/preserve_test.go @@ -0,0 +1,444 @@ +package hclparser_test + +import ( + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/ir" + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" +) + +const modernModule = ` +terraform { + required_version = ">= 1.6.2" + + required_providers { + aws = { + source = "hashicorp/aws" + version = "~> 5.0" + } + } + + backend "s3" { + bucket = "state" + key = "app/terraform.tfstate" + } + + cloud { + organization = "example" + } + + provider_meta "aws" { + module_name = "example" + } + + experiments = [module_variable_optional_attrs] +} + +moved { + from = aws_vpc.old + to = aws_vpc.main +} + +import { + to = aws_vpc.main + id = aws_vpc.existing.id +} + +removed { + from = aws_instance.legacy + + lifecycle { + destroy = false + } + + provisioner "local-exec" { + when = destroy + command = "echo bye" + } +} + +check "health" { + data "http" "ping" { + url = "https://example.com" + } + + assert { + condition = data.http.ping.status_code == 200 + error_message = "unhealthy" + } +} + +ephemeral "random_password" "db" { + length = 16 +} + +action "aws_lb_target_group" "register" { + config { + target_group_arn = aws_lb_target_group.main.arn + } +} + +variable "password" { + type = string + sensitive = true + nullable = false + ephemeral = true + deprecated = "use db_password instead" + description = "db password" + + validation { + condition = length(var.password) >= 8 + error_message = "too short" + } +} + +variable "config" { + type = object({ + name = string + retries = optional(number, 3) + }) +} + +output "instance_ip" { + value = aws_instance.web.private_ip + type = string + ephemeral = true + deprecated = "use instance_ips" + description = "private ip" + + precondition { + condition = aws_instance.web.id != "" + error_message = "no instance" + } +} + +provider "aws" { + region = "us-east-1" + + default_tags { + tags = { Environment = "dev" } + } +} + +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + + lifecycle { + replace_triggered_by = [terraform_data.redeploy] + destroy = false + } +} + +resource "terraform_data" "redeploy" { + input = "v2" +} + +resource "aws_subnet" "public" { + vpc_id = aws_vpc.main.id +} + +resource "aws_instance" "web" { + ami = "ami-123" + instance_type = "t3.micro" +} +` + +func parseModern(t *testing.T) *ir.Graph { + t.Helper() + graph, err := hclparser.ParseString(modernModule, "main.tf") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + return graph +} + +func preservedByType(graph *ir.Graph) map[string][]ir.Block { + out := map[string][]ir.Block{} + for _, block := range graph.Preserved { + out[block.Type] = append(out[block.Type], block) + } + return out +} + +func TestPreservedTopLevelBlocks(t *testing.T) { + graph := parseModern(t) + preserved := preservedByType(graph) + + cases := []struct { + typ string + labels []string + }{ + {"moved", nil}, + {"import", nil}, + {"removed", nil}, + {"check", []string{"health"}}, + {"ephemeral", []string{"random_password", "db"}}, + {"action", []string{"aws_lb_target_group", "register"}}, + } + for _, c := range cases { + blocks := preserved[c.typ] + if len(blocks) != 1 { + t.Errorf("%s preserved %d times, want 1", c.typ, len(blocks)) + continue + } + if len(blocks[0].Labels) != len(c.labels) { + t.Errorf("%s labels = %v, want %v", c.typ, blocks[0].Labels, c.labels) + continue + } + for i, label := range c.labels { + if blocks[0].Labels[i] != label { + t.Errorf("%s label %d = %q, want %q", c.typ, i, blocks[0].Labels[i], label) + } + } + if blocks[0].File != "main.tf" || blocks[0].Line == 0 { + t.Errorf("%s provenance = %q:%d", c.typ, blocks[0].File, blocks[0].Line) + } + } + + if len(graph.Resources) != 4 { + t.Errorf("resources = %d, want 4", len(graph.Resources)) + } + for _, res := range graph.Resources { + switch res.Type { + case "aws_vpc", "aws_subnet", "aws_instance", "terraform_data": + default: + t.Errorf("preserved type leaked into resources: %s", res.ID) + } + } + + ordered, err := graph.Order() + if err != nil { + t.Fatalf("Order: %v", err) + } + if len(ordered) != len(graph.Resources) { + t.Errorf("ordered %d nodes, want %d", len(ordered), len(graph.Resources)) + } +} + +func TestPreservedNestedStructure(t *testing.T) { + graph := parseModern(t) + preserved := preservedByType(graph) + + removed := preserved["removed"][0] + if _, ok := removed.Attributes["from"]; !ok { + t.Error("removed.from missing") + } + var lifecycle, provisioner bool + for _, block := range removed.Blocks { + switch block.Type { + case "lifecycle": + lifecycle = true + if _, ok := block.Attributes["destroy"]; !ok { + t.Error("removed.lifecycle.destroy missing") + } + case "provisioner": + provisioner = true + if len(block.Labels) != 1 || block.Labels[0] != "local-exec" { + t.Errorf("provisioner labels = %v", block.Labels) + } + } + } + if !lifecycle || !provisioner { + t.Errorf("removed blocks = %v, want lifecycle and provisioner", removed.Blocks) + } + + check := preserved["check"][0] + if len(check.Blocks) != 2 { + t.Fatalf("check blocks = %d, want 2", len(check.Blocks)) + } + + action := preserved["action"][0] + if len(action.Blocks) != 1 || action.Blocks[0].Type != "config" { + t.Fatalf("action blocks = %v", action.Blocks) + } +} + +func TestVariableAndOutputPreservation(t *testing.T) { + graph := parseModern(t) + + if len(graph.Variables) != 2 { + t.Fatalf("variables = %d, want 2", len(graph.Variables)) + } + password := graph.Variables[0] + if password.Name != "password" { + t.Fatalf("first variable = %q", password.Name) + } + if password.Nullable == nil || *password.Nullable { + t.Errorf("nullable = %v, want false", password.Nullable) + } + if !password.Ephemeral { + t.Error("ephemeral not parsed") + } + if password.Deprecated != "use db_password instead" { + t.Errorf("deprecated = %q", password.Deprecated) + } + if len(password.Blocks) != 1 || password.Blocks[0].Type != "validation" { + t.Fatalf("validation block missing: %v", password.Blocks) + } + if _, ok := password.Attributes["nullable"]; ok { + t.Error("nullable should be typed, not duplicated in attributes") + } + + config := graph.Variables[1] + if !strings.Contains(config.Type, "optional(") { + t.Errorf("config type = %q, want an optional() constraint", config.Type) + } + + if len(graph.Outputs) != 1 { + t.Fatalf("outputs = %d, want 1", len(graph.Outputs)) + } + out := graph.Outputs[0] + if out.Type != "string" { + t.Errorf("output type = %q, want string", out.Type) + } + if !out.Ephemeral || out.Deprecated != "use instance_ips" { + t.Errorf("output = %#v", out) + } + if len(out.Blocks) != 1 || out.Blocks[0].Type != "precondition" { + t.Fatalf("precondition block missing: %v", out.Blocks) + } +} + +func TestTerraformMetadataNative(t *testing.T) { + graph := parseModern(t) + tf := graph.Terraform + if tf == nil { + t.Fatal("terraform metadata missing") + } + if tf.RequiredVersion != ">= 1.6.2" { + t.Errorf("required_version = %q", tf.RequiredVersion) + } + if tf.Backend == nil || tf.Backend.Labels[0] != "s3" { + t.Fatalf("backend = %#v", tf.Backend) + } + if tf.Backend.File != "main.tf" || tf.Backend.Line == 0 { + t.Errorf("backend provenance = %q:%d", tf.Backend.File, tf.Backend.Line) + } + if tf.Cloud == nil { + t.Fatal("cloud missing") + } + if got := tf.Cloud.Attributes["organization"]; got.Literal != "example" { + t.Errorf("cloud organization = %#v", got) + } + if len(tf.ProviderMeta) != 1 || tf.ProviderMeta[0].Labels[0] != "aws" { + t.Fatalf("provider_meta = %#v", tf.ProviderMeta) + } + if aws, ok := tf.RequiredProviders["aws"]; !ok || aws.Kind != ir.KindMap { + t.Fatalf("required_providers.aws = %#v", aws) + } + if len(tf.Experiments) != 1 || tf.Experiments[0] != "module_variable_optional_attrs" { + t.Errorf("experiments = %v", tf.Experiments) + } + if tf.File != "main.tf" || tf.Line == 0 { + t.Errorf("terraform provenance = %q:%d", tf.File, tf.Line) + } +} + +func TestProviderBlocksPreserved(t *testing.T) { + graph := parseModern(t) + if len(graph.Providers) != 1 { + t.Fatalf("providers = %d, want 1", len(graph.Providers)) + } + provider := graph.Providers[0] + if len(provider.Blocks) != 1 || provider.Blocks[0].Type != "default_tags" { + t.Fatalf("provider blocks = %v", provider.Blocks) + } + if provider.File != "main.tf" || provider.Line == 0 { + t.Errorf("provider provenance = %q:%d", provider.File, provider.Line) + } +} + +func TestFeaturesAndMinVersion(t *testing.T) { + graph := parseModern(t) + + want := []string{ + "action", + "check", + "cloud", + "conditions", + "deprecated", + "ephemeral_resources", + "ephemeral_values", + "import", + "import_expression", + "lifecycle_destroy", + "moved", + "nullable", + "optional_attributes", + "output_type", + "removed", + "removed_provisioners", + "replace_triggered_by", + "terraform_data", + } + for _, name := range want { + if !contains(graph.Features, name) { + t.Errorf("feature %q not detected; got %v", name, graph.Features) + } + } + if graph.MinVersion != "1.16.0" { + t.Errorf("min_version = %q, want 1.16.0", graph.MinVersion) + } +} + +func TestMinVersionBaseline(t *testing.T) { + graph, err := hclparser.ParseString(`resource "aws_vpc" "main" { cidr_block = "10.0.0.0/16" }`, "main.tf") + if err != nil { + t.Fatal(err) + } + if graph.MinVersion != "1.0.0" { + t.Errorf("min_version = %q, want 1.0.0", graph.MinVersion) + } + if len(graph.Features) != 0 { + t.Errorf("features = %v, want none", graph.Features) + } +} + +func TestUnknownTopLevelBlockPreserved(t *testing.T) { + graph, err := hclparser.ParseString(` +future_block "a" "b" { + setting = "x" +} + +stray_argument = "y" +`, "main.tf") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + + preserved := preservedByType(graph) + future := preserved["future_block"] + if len(future) != 1 || len(future[0].Labels) != 2 { + t.Fatalf("future_block = %#v", future) + } + if got := future[0].Attributes["setting"]; got.Literal != "x" { + t.Errorf("future_block.setting = %#v", got) + } + + stray := preserved["stray_argument"] + if len(stray) != 1 || stray[0].Body == nil || stray[0].Body.Literal != "y" { + t.Fatalf("stray_argument = %#v", stray) + } +} + +func TestLabelValidation(t *testing.T) { + cases := []string{ + `resource "aws_vpc" {}`, + `variable {}`, + `module "a" "b" {}`, + } + for _, source := range cases { + if _, err := hclparser.ParseString(source, "main.tf"); err == nil { + t.Errorf("expected a label error for %q", source) + } + } +} + +func TestParseDirRequiresTerraformFiles(t *testing.T) { + if _, err := hclparser.ParseDir(t.TempDir()); err == nil { + t.Fatal("expected an error for an empty directory") + } else if !strings.Contains(err.Error(), "*.tf") { + t.Errorf("error = %v", err) + } +} diff --git a/pkg/parsers/hcl/schema.go b/pkg/parsers/hcl/schema.go new file mode 100644 index 0000000..4a2deca --- /dev/null +++ b/pkg/parsers/hcl/schema.go @@ -0,0 +1,59 @@ +package hclparser + +import "github.com/hashicorp/hcl/v2" + +// topLevelSchema describes every top-level block Terraform accepts, so a +// .tf.json document can be decomposed into real blocks with real labels. +// +// hcl.Body hides block structure below the top level, but at the top level +// PartialContent recovers it exactly: hcl/v2's JSON body peels one label per +// nested object and hard-errors when the label count does not match. The schema +// must therefore mirror Terraform's own block headers precisely. +var topLevelSchema = &hcl.BodySchema{Blocks: []hcl.BlockHeaderSchema{ + {Type: "terraform"}, + {Type: "locals"}, + {Type: "moved"}, + {Type: "import"}, + {Type: "removed"}, + {Type: "resource", LabelNames: []string{"type", "name"}}, + {Type: "data", LabelNames: []string{"type", "name"}}, + {Type: "ephemeral", LabelNames: []string{"type", "name"}}, + {Type: "action", LabelNames: []string{"type", "name"}}, + {Type: "check", LabelNames: []string{"name"}}, + {Type: "variable", LabelNames: []string{"name"}}, + {Type: "output", LabelNames: []string{"name"}}, + {Type: "module", LabelNames: []string{"name"}}, + {Type: "provider", LabelNames: []string{"name"}}, +}} + +// terraformBodySchema describes the nested blocks of a terraform block. +// +// required_providers is a block in native HCL and an object property in JSON; +// listing it as a block makes PartialContent turn the JSON form into a block +// too, so both syntaxes converge on the same parsing path. +var terraformBodySchema = &hcl.BodySchema{Blocks: []hcl.BlockHeaderSchema{ + {Type: "required_providers"}, + {Type: "backend", LabelNames: []string{"type"}}, + {Type: "cloud"}, + {Type: "provider_meta", LabelNames: []string{"provider"}}, +}} + +// topLevelLabelCount is the number of labels Terraform requires for a +// recognised top-level block. Native HCL does not validate labels while +// parsing, so the parser checks them itself. +var topLevelLabelCount = map[string]int{ + "terraform": 0, + "locals": 0, + "moved": 0, + "import": 0, + "removed": 0, + "resource": 2, + "data": 2, + "ephemeral": 2, + "action": 2, + "check": 1, + "variable": 1, + "output": 1, + "module": 1, + "provider": 1, +} diff --git a/pkg/parsers/hcl/terraform.go b/pkg/parsers/hcl/terraform.go new file mode 100644 index 0000000..80505b2 --- /dev/null +++ b/pkg/parsers/hcl/terraform.go @@ -0,0 +1,191 @@ +package hclparser + +import ( + "fmt" + "sort" + "strings" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// addTerraform merges one terraform block into the graph's Terraform metadata. +// +// Terraform permits only one terraform block per module, but modules in the +// wild repeat it and the merge is harmless, so every block is folded in. +// +// Native HCL spells required_providers, backend, cloud and provider_meta as +// nested blocks. JSON spells each of them as an object property, which the flat +// JSON body reports as a map value; both shapes are accepted here. +func (p *parser) addTerraform(blk block) error { + attrs, blocks, err := parseBody(blk.body, p.src[blk.file]) + if err != nil { + return fmt.Errorf("%s:%d: %w", blk.file, blk.line, err) + } + + tf := p.graph.Terraform + if tf == nil { + tf = &ir.Terraform{File: blk.file, Line: blk.line} + p.graph.Terraform = tf + } + + mergeTerraformAttrs(tf, attrs) + mergeTerraformBlocks(tf, blocks) + + if len(attrs) > 0 { + if tf.Attributes == nil { + tf.Attributes = make(map[string]ir.Value, len(attrs)) + } + for name, value := range attrs { + tf.Attributes[name] = value + } + } + return nil +} + +// mergeTerraformAttrs consumes the typed settings written as arguments and +// leaves everything else in attrs. +func mergeTerraformAttrs(tf *ir.Terraform, attrs map[string]ir.Value) { + if v, ok := attrs["required_version"]; ok { + if s := literalString(v); s != "" { + tf.RequiredVersion = s + delete(attrs, "required_version") + } else if s := strings.TrimSpace(v.Expr); s != "" { + tf.RequiredVersion = s + delete(attrs, "required_version") + } + } + + if v, ok := attrs["experiments"]; ok { + if list, ok := stringList(v); ok { + tf.Experiments = append(tf.Experiments, list...) + delete(attrs, "experiments") + } + } + + if v, ok := attrs["required_providers"]; ok && v.Kind == ir.KindMap { + if tf.RequiredProviders == nil { + tf.RequiredProviders = make(map[string]ir.Value, len(v.Fields)) + } + for name, decl := range v.Fields { + tf.RequiredProviders[name] = decl + } + delete(attrs, "required_providers") + } + + if v, ok := attrs["backend"]; ok { + if b, ok := labelledBlock("backend", v); ok { + if tf.Backend == nil { + // JSON bodies are flat, so the nested block has no range of its + // own; the enclosing terraform block supplies the file. + b.File = tf.File + tf.Backend = &b + } + delete(attrs, "backend") + } + } + + if v, ok := attrs["cloud"]; ok && v.Kind == ir.KindMap { + if tf.Cloud == nil { + tf.Cloud = &ir.Block{Type: "cloud", Attributes: v.Fields, File: tf.File} + } + delete(attrs, "cloud") + } + + if v, ok := attrs["provider_meta"]; ok && v.Kind == ir.KindMap { + names := make([]string, 0, len(v.Fields)) + for name := range v.Fields { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + body := v.Fields[name] + if body.Kind != ir.KindMap { + continue + } + tf.ProviderMeta = append(tf.ProviderMeta, ir.Block{ + Type: "provider_meta", + Labels: []string{name}, + Attributes: body.Fields, + File: tf.File, + }) + } + delete(attrs, "provider_meta") + } +} + +// mergeTerraformBlocks folds nested terraform blocks into the metadata. +func mergeTerraformBlocks(tf *ir.Terraform, blocks []ir.Block) { + for _, b := range blocks { + switch b.Type { + case "required_providers": + if tf.RequiredProviders == nil { + tf.RequiredProviders = make(map[string]ir.Value, len(b.Attributes)) + } + for name, decl := range b.Attributes { + tf.RequiredProviders[name] = decl + } + case "backend": + if tf.Backend == nil { + backend := b + tf.Backend = &backend + } else { + tf.Blocks = append(tf.Blocks, b) + } + case "cloud": + if tf.Cloud == nil { + cloud := b + tf.Cloud = &cloud + } else { + tf.Blocks = append(tf.Blocks, b) + } + case "provider_meta": + tf.ProviderMeta = append(tf.ProviderMeta, b) + default: + tf.Blocks = append(tf.Blocks, b) + } + } +} + +// labelledBlock turns JSON's {"label": {β¦}} spelling of a single-label block +// into the block it represents. +func labelledBlock(typ string, v ir.Value) (ir.Block, bool) { + if v.Kind != ir.KindMap || len(v.Fields) != 1 { + return ir.Block{}, false + } + for label, body := range v.Fields { + if body.Kind != ir.KindMap { + return ir.Block{}, false + } + return ir.Block{ + Type: typ, + Labels: []string{label}, + Attributes: body.Fields, + }, true + } + return ir.Block{}, false +} + +// stringList reads a list of literal strings. Native HCL reports a bare +// identifier such as module_variable_optional_attrs as an expression, so the +// source text is accepted too. +func stringList(v ir.Value) ([]string, bool) { + if v.Kind != ir.KindList { + return nil, false + } + out := make([]string, 0, len(v.Items)) + for _, item := range v.Items { + switch item.Kind { + case ir.KindString: + out = append(out, literalString(item)) + case ir.KindExpr: + text := strings.TrimSpace(item.Expr) + if text == "" { + return nil, false + } + out = append(out, text) + default: + return nil, false + } + } + return out, true +} diff --git a/pkg/parsers/hcl/versions_test.go b/pkg/parsers/hcl/versions_test.go new file mode 100644 index 0000000..070436d --- /dev/null +++ b/pkg/parsers/hcl/versions_test.go @@ -0,0 +1,421 @@ +package hclparser_test + +import ( + "testing" + + "github.com/be-thomas/openiac/pkg/ir" + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" + "github.com/be-thomas/openiac/pkg/tfversion" +) + +// versionCase is one minimal configuration per registered Terraform feature. +// min is the version the whole snippet needs, so it also checks that detectors +// do not over-report. +type versionCase struct { + feature string + min string + source string +} + +var versionCases = []versionCase{ + { + feature: "action", min: "1.14.0", + source: ` +action "aws_lb_target_group" "register" { + config { + target_group_arn = "arn:aws:elasticloadbalancing:us-east-1:123:targetgroup/web/abc" + } +} +`, + }, + { + feature: "action_lifecycle_events", min: "1.14.0", + source: ` +action "aws_cloudfront_invalidation" "purge" { + config { + paths = ["/*"] + } + + on_failure = "continue" +} +`, + }, + { + feature: "check", min: "1.5.0", + source: ` +check "health" { + assert { + condition = true + error_message = "unhealthy" + } +} +`, + }, + { + feature: "cloud", min: "1.1.0", + source: ` +terraform { + cloud { + organization = "example" + } +} +`, + }, + { + feature: "conditions", min: "1.2.0", + source: ` +resource "aws_instance" "web" { + ami = "ami-123" + + precondition { + condition = true + error_message = "no instance" + } +} +`, + }, + { + feature: "deprecated", min: "1.15.0", + source: ` +variable "legacy" { + default = "old" + deprecated = "use the new variable instead" +} +`, + }, + { + feature: "ephemeral_resources", min: "1.10.0", + source: ` +ephemeral "random_password" "db" { + length = 16 +} +`, + }, + { + feature: "ephemeral_values", min: "1.10.0", + source: ` +variable "token" { + type = string + ephemeral = true +} +`, + }, + { + feature: "import", min: "1.5.0", + source: ` +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" +} + +import { + to = aws_vpc.main + id = "vpc-123" +} +`, + }, + { + feature: "import_expression", min: "1.6.0", + source: ` +resource "aws_vpc" "existing" { + cidr_block = "10.0.0.0/16" +} + +import { + to = aws_vpc.existing + id = aws_vpc.existing.id +} +`, + }, + { + feature: "import_for_each", min: "1.7.0", + source: ` +import { + for_each = { a = "vpc-1" } + to = aws_vpc.main + id = each.value +} +`, + }, + { + feature: "import_identity", min: "1.12.0", + source: ` +import { + to = aws_instance.example + identity = { + id = "i-abcd1234" + region = "us-east-1" + } +} +`, + }, + { + feature: "lifecycle_destroy", min: "1.16.0", + source: ` +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + + lifecycle { + destroy = false + } +} +`, + }, + { + feature: "moved", min: "1.1.0", + source: ` +moved { + from = aws_vpc.old + to = aws_vpc.main +} +`, + }, + { + feature: "moved_cross_type", min: "1.1.0", + source: ` +moved { + from = aws_vpc.old + to = aws_security_group.main +} +`, + }, + { + feature: "moved_module", min: "1.3.0", + source: ` +moved { + from = module.old.aws_vpc.main + to = module.new.aws_vpc.main +} +`, + }, + { + feature: "nullable", min: "1.1.0", + source: ` +variable "name" { + type = string + nullable = false +} +`, + }, + { + feature: "optional_attributes", min: "1.3.0", + source: ` +variable "config" { + type = object({ + name = string + retries = optional(number, 3) + }) +} +`, + }, + { + feature: "output_type", min: "1.15.0", + source: ` +output "ip" { + value = "10.0.0.1" + type = string +} +`, + }, + { + feature: "provider_requirements_expressions", min: "1.17.0", + source: ` +variable "aws_version" { + default = "5.0" +} + +terraform { + required_providers { + aws = { + source = "hashicorp/aws" + version = var.aws_version + } + } +} +`, + }, + { + feature: "removed", min: "1.7.0", + source: ` +removed { + from = aws_instance.legacy +} +`, + }, + { + feature: "removed_provisioners", min: "1.9.0", + source: ` +removed { + from = aws_instance.legacy + + provisioner "local-exec" { + when = destroy + command = "echo bye" + } +} +`, + }, + { + feature: "replace_triggered_by", min: "1.2.0", + source: ` +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" + + lifecycle { + replace_triggered_by = [terraform_data.redeploy] + } +} +`, + }, + { + feature: "terraform_data", min: "1.4.0", + source: ` +resource "terraform_data" "redeploy" { + input = "v1" +} +`, + }, + { + feature: "terraform_data_store", min: "1.16.0", + source: ` +resource "terraform_data" "cache" { + store { + key = "cache" + } +} +`, + }, +} + +func TestFeatureDetection(t *testing.T) { + for _, c := range versionCases { + c := c + t.Run(c.feature, func(t *testing.T) { + graph, err := hclparser.ParseString(c.source, "main.tf") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + if !contains(graph.Features, c.feature) { + t.Fatalf("features = %v, want %q", graph.Features, c.feature) + } + if graph.MinVersion != c.min { + t.Errorf("min_version = %q, want %q (features %v)", graph.MinVersion, c.min, graph.Features) + } + }) + } +} + +func TestEveryFeatureHasSample(t *testing.T) { + covered := make(map[string]bool, len(versionCases)) + for _, c := range versionCases { + covered[c.feature] = true + } + for _, feature := range tfversion.Features() { + if !covered[feature.Name] { + t.Errorf("feature %q has no sample configuration", feature.Name) + } + } +} + +func TestVersionCasesUseOnlyKnownFeatures(t *testing.T) { + known := make(map[string]bool) + for _, feature := range tfversion.Features() { + known[feature.Name] = true + } + for _, c := range versionCases { + if !known[c.feature] { + t.Errorf("%q is not in the feature registry", c.feature) + } + if _, ok := tfversion.Canonical(c.min); !ok { + t.Errorf("%s: invalid min version %q", c.feature, c.min) + } + } +} + +// TestUnreliableFeaturesDoNotRaiseMinVersion guards the conservative default: +// a detector that can misfire must not move min_version on its own. +func TestUnreliableFeaturesDoNotRaiseMinVersion(t *testing.T) { + for _, feature := range tfversion.Features() { + if feature.Reliable { + continue + } + if got := tfversion.MinVersion([]string{feature.Name}, ""); got != tfversion.Baseline { + t.Errorf("MinVersion([%q]) = %q, want %q", feature.Name, got, tfversion.Baseline) + } + if feature.Since == tfversion.Baseline { + t.Errorf("%s: an unreliable feature cannot be part of the baseline", feature.Name) + } + } +} + +// TestPreservedBlocksDoNotCreateNodes keeps moved/import/removed/check/ephemeral +// out of the resource graph, because both emitters treat every node as managed. +func TestPreservedBlocksDoNotCreateNodes(t *testing.T) { + source := ` +moved { + from = aws_vpc.old + to = aws_vpc.main +} + +import { + to = aws_vpc.main + id = "vpc-123" +} + +removed { + from = aws_instance.legacy +} + +check "health" { + assert { + condition = true + error_message = "unhealthy" + } +} + +ephemeral "random_password" "db" { + length = 16 +} + +action "aws_lb_target_group" "register" { + config { + target_group_arn = "arn" + } +} + +resource "aws_vpc" "main" { + cidr_block = "10.0.0.0/16" +} +` + graph, err := hclparser.ParseString(source, "main.tf") + if err != nil { + t.Fatalf("ParseString: %v", err) + } + if len(graph.Resources) != 1 || graph.Resources[0].ID != "aws_vpc.main" { + t.Fatalf("resources = %v, want only aws_vpc.main", resourceIDs(graph)) + } + if len(graph.Edges) != 0 { + t.Errorf("edges = %v, want none", graph.Edges) + } + + ordered, err := graph.Order() + if err != nil { + t.Fatalf("Order: %v", err) + } + if len(ordered) != 1 || ordered[0].ID != "aws_vpc.main" { + t.Errorf("order = %v, want only aws_vpc.main", ordered) + } + if resources, data, _, _, edges := graph.Stats(); resources != 1 || data != 0 || edges != 0 { + t.Errorf("stats = (%d resources, %d data, %d edges)", resources, data, edges) + } + if graph.HasNode("moved") || graph.HasNode("random_password.db") { + t.Error("a preserved block leaked into the node set") + } +} + +func resourceIDs(graph *ir.Graph) []string { + out := make([]string, 0, len(graph.Resources)) + for _, res := range graph.Resources { + out = append(out, res.ID) + } + return out +} diff --git a/pkg/tfversion/constraint.go b/pkg/tfversion/constraint.go new file mode 100644 index 0000000..9a6f3c8 --- /dev/null +++ b/pkg/tfversion/constraint.go @@ -0,0 +1,96 @@ +package tfversion + +import ( + "fmt" + "strings" +) + +// Clause is one operator-and-version term of a required_version constraint. +type Clause struct { + Op string // "=", "!=", ">", ">=", "<", "<=", "~>" + Version string // canonical "MAJOR.MINOR.PATCH" +} + +// Constraint is a parsed required_version value. +// +// Only a conservative lower bound is modelled: "~> 1.5" is treated as +// ">= 1.5.0" and upper bounds are ignored. Raw always holds the original text, +// which is what the IR preserves. +type Constraint struct { + Raw string + Clauses []Clause + LowerBound string // canonical; empty when the constraint implies no lower bound +} + +// ParseConstraint parses a Terraform required_version constraint. +// +// It accepts comma-separated clauses with the operators =, !=, >, >=, <, <= +// and ~>, and bare versions (which Terraform reads as =). It is deliberately +// best-effort: callers treat an error as "no usable bound", never as a parse +// failure of the module. +func ParseConstraint(s string) (Constraint, error) { + raw := s + c := Constraint{Raw: raw} + + trimmed := strings.TrimSpace(s) + if trimmed == "" { + return c, fmt.Errorf("empty version constraint") + } + + for _, part := range strings.Split(trimmed, ",") { + clause, err := parseClause(part) + if err != nil { + return c, err + } + c.Clauses = append(c.Clauses, clause) + + lower, has := clause.lowerBound() + if has && (c.LowerBound == "" || Compare(lower, c.LowerBound) > 0) { + c.LowerBound = lower + } + } + return c, nil +} + +func parseClause(part string) (Clause, error) { + part = strings.TrimSpace(part) + if part == "" { + return Clause{}, fmt.Errorf("empty version constraint clause") + } + + op := "=" + rest := part + for _, candidate := range []string{">=", "<=", "~>", "!=", "==", ">", "<", "="} { + if strings.HasPrefix(part, candidate) { + if candidate == "==" { + return Clause{}, fmt.Errorf("unsupported version operator %q", candidate) + } + op = candidate + rest = strings.TrimSpace(part[len(candidate):]) + break + } + } + if rest == "" { + return Clause{}, fmt.Errorf("version constraint %q has no version", part) + } + + version, ok := Canonical(rest) + if !ok { + return Clause{}, fmt.Errorf("invalid version %q", rest) + } + return Clause{Op: op, Version: version}, nil +} + +// lowerBound reports the smallest version a clause guarantees. +func (c Clause) lowerBound() (string, bool) { + switch c.Op { + case "=", ">=", "~>": + return c.Version, true + case ">": + v, ok := bumpPatch(c.Version) + return v, ok + default: + // "!=", "<" and "<=" say nothing about the minimum. + return "", false + } +} diff --git a/pkg/tfversion/constraint_test.go b/pkg/tfversion/constraint_test.go new file mode 100644 index 0000000..83c53de --- /dev/null +++ b/pkg/tfversion/constraint_test.go @@ -0,0 +1,79 @@ +package tfversion_test + +import ( + "testing" + + "github.com/be-thomas/openiac/pkg/tfversion" +) + +func TestParseConstraintLowerBound(t *testing.T) { + cases := []struct { + in string + want string + }{ + {"1.2.3", "1.2.3"}, + {"= 1.2.3", "1.2.3"}, + {">= 1.5.0", "1.5.0"}, + {">= 1.5", "1.5.0"}, + {"~> 1.3", "1.3.0"}, + {"~> 1.3.7", "1.3.7"}, + {"> 1.5.0", "1.5.1"}, + {"> 1.5", "1.5.1"}, + {"< 2.0", ""}, + {"<= 2.0", ""}, + {"!= 1.4.0", ""}, + {"!= 1.4.0, >= 1.6.2", "1.6.2"}, + {"< 2.0, >= 1.6.2", "1.6.2"}, + {">= 1.0, < 2.0, ~> 1.2.7", "1.2.7"}, + {" >=1.6.0 , <2.0 ", "1.6.0"}, + } + for _, c := range cases { + got, err := tfversion.ParseConstraint(c.in) + if err != nil { + t.Errorf("ParseConstraint(%q): %v", c.in, err) + continue + } + if got.LowerBound != c.want { + t.Errorf("ParseConstraint(%q).LowerBound = %q, want %q", c.in, got.LowerBound, c.want) + } + if got.Raw != c.in { + t.Errorf("ParseConstraint(%q).Raw = %q", c.in, got.Raw) + } + } +} + +func TestParseConstraintClauses(t *testing.T) { + c, err := tfversion.ParseConstraint(">= 1.5.0, != 1.5.3, < 2.0") + if err != nil { + t.Fatalf("ParseConstraint: %v", err) + } + want := []tfversion.Clause{ + {Op: ">=", Version: "1.5.0"}, + {Op: "!=", Version: "1.5.3"}, + {Op: "<", Version: "2.0.0"}, + } + if len(c.Clauses) != len(want) { + t.Fatalf("clauses = %#v, want %#v", c.Clauses, want) + } + for i := range want { + if c.Clauses[i] != want[i] { + t.Errorf("clause %d = %#v, want %#v", i, c.Clauses[i], want[i]) + } + } +} + +func TestParseConstraintErrors(t *testing.T) { + for _, in := range []string{ + "", + " ", + "== 1.0.0", + ">=", + "garbage", + ">= 1.2.3-beta", + ">= 1.2.3, ,", + } { + if _, err := tfversion.ParseConstraint(in); err == nil { + t.Errorf("ParseConstraint(%q) succeeded, want an error", in) + } + } +} diff --git a/pkg/tfversion/features.go b/pkg/tfversion/features.go new file mode 100644 index 0000000..31a73c6 --- /dev/null +++ b/pkg/tfversion/features.go @@ -0,0 +1,520 @@ +package tfversion + +import ( + "fmt" + "sort" + "strings" + + "github.com/be-thomas/openiac/pkg/ir" +) + +// Feature describes one Terraform language feature that OpenIaC detects in an +// IR graph. +type Feature struct { + // Name is the stable identifier reported in Graph.Features. + Name string + // Since is the canonical Terraform release that introduced the feature. + Since string + // Description is a one-line human summary. + Description string + // Reliable reports whether detection is strong enough to move MinVersion. + // Unreliable features are still reported, but never raise the version. + Reliable bool + // Detect inspects a graph for the feature. + Detect func(*ir.Graph) bool +} + +type feature struct { + name string + since string + description string + reliable bool + detect func(*scan) bool +} + +// registry is the single source of truth for feature detection. Rows are added +// only for constructs whose presence is unambiguous in the IR; see +// docs/TERRAFORM-VERSIONS.md for the full rationale and the features that are +// deliberately not tracked. +var registry = []feature{ + { + name: "action", since: "1.14.0", reliable: true, + description: "Provider-defined action blocks", + detect: func(s *scan) bool { return len(s.preserved["action"]) > 0 }, + }, + { + name: "action_lifecycle_events", since: "1.16.0", reliable: false, + description: "Action failure modes and destroy-time events", + detect: func(s *scan) bool { + return blockSetsAny(s.preserved["action"], "on_failure", "before_destroy", "after_destroy") + }, + }, + { + name: "check", since: "1.5.0", reliable: true, + description: "check blocks", + detect: func(s *scan) bool { return len(s.preserved["check"]) > 0 }, + }, + { + name: "cloud", since: "1.1.0", reliable: true, + description: "HCP Terraform / Terraform Cloud integration block", + detect: func(s *scan) bool { return s.cloud }, + }, + { + name: "conditions", since: "1.2.0", reliable: true, + description: "precondition and postcondition blocks", + detect: hasConditions, + }, + { + name: "deprecated", since: "1.15.0", reliable: true, + description: "Deprecation messages on variables and outputs", + detect: func(s *scan) bool { + for _, v := range s.variables { + if v.Deprecated != "" { + return true + } + } + for _, o := range s.outputs { + if o.Deprecated != "" { + return true + } + } + return false + }, + }, + { + name: "ephemeral_resources", since: "1.10.0", reliable: true, + description: "ephemeral resource blocks", + detect: func(s *scan) bool { return len(s.preserved["ephemeral"]) > 0 }, + }, + { + name: "ephemeral_values", since: "1.10.0", reliable: true, + description: "Ephemeral variables and outputs", + detect: func(s *scan) bool { + for _, v := range s.variables { + if v.Ephemeral { + return true + } + } + for _, o := range s.outputs { + if o.Ephemeral { + return true + } + } + return false + }, + }, + { + name: "import", since: "1.5.0", reliable: true, + description: "import blocks", + detect: func(s *scan) bool { return len(s.preserved["import"]) > 0 }, + }, + { + name: "import_expression", since: "1.6.0", reliable: true, + description: "import id given as an expression", + detect: func(s *scan) bool { + for _, b := range s.preserved["import"] { + if v, ok := b.Attributes["id"]; ok && v.Kind != ir.KindString { + return true + } + } + return false + }, + }, + { + name: "import_for_each", since: "1.7.0", reliable: true, + description: "import blocks with for_each", + detect: func(s *scan) bool { + return anyPreserved(s.preserved["import"], func(b ir.Block) bool { + _, ok := b.Attributes["for_each"] + return ok + }) + }, + }, + { + name: "import_identity", since: "1.12.0", reliable: true, + description: "import blocks using identity instead of id", + detect: func(s *scan) bool { + // Native HCL spells identity as a block, .tf.json as a property. + return anyPreserved(s.preserved["import"], func(b ir.Block) bool { + _, ok := b.Attributes["identity"] + return ok || hasBlockType(b.Blocks, "identity") + }) + }, + }, + { + name: "lifecycle_destroy", since: "1.16.0", reliable: true, + description: "lifecycle destroy argument", + detect: func(s *scan) bool { + return resourceLifecycleField(s.resources, "destroy") + }, + }, + { + name: "moved", since: "1.1.0", reliable: true, + description: "moved blocks", + detect: func(s *scan) bool { return len(s.preserved["moved"]) > 0 }, + }, + { + name: "moved_cross_type", since: "1.8.0", reliable: false, + description: "moved blocks changing the resource type", + detect: func(s *scan) bool { + return anyPreserved(s.preserved["moved"], func(b ir.Block) bool { + from := addressType(valueText(b.Attributes["from"])) + to := addressType(valueText(b.Attributes["to"])) + return from != "" && to != "" && from != to + }) + }, + }, + { + name: "moved_module", since: "1.3.0", reliable: true, + description: "moved blocks that cross module boundaries", + detect: func(s *scan) bool { + return anyPreserved(s.preserved["moved"], func(b ir.Block) bool { + return strings.Contains(valueText(b.Attributes["from"]), "module.") || + strings.Contains(valueText(b.Attributes["to"]), "module.") + }) + }, + }, + { + name: "nullable", since: "1.1.0", reliable: true, + description: "nullable variable argument", + detect: func(s *scan) bool { + for _, v := range s.variables { + if v.Nullable != nil { + return true + } + } + return false + }, + }, + { + name: "optional_attributes", since: "1.3.0", reliable: true, + description: "optional object type attributes", + detect: func(s *scan) bool { + for _, v := range s.variables { + if strings.Contains(strings.ReplaceAll(v.Type, " ", ""), "optional(") { + return true + } + } + return false + }, + }, + { + name: "output_type", since: "1.15.0", reliable: true, + description: "output type constraints", + detect: func(s *scan) bool { + for _, o := range s.outputs { + if o.Type != "" { + return true + } + } + return false + }, + }, + { + name: "provider_requirements_expressions", since: "1.17.0", reliable: true, + description: "variables and locals in provider requirements", + detect: func(s *scan) bool { + for _, v := range s.requiredProviders { + if hasRefs(v) { + return true + } + } + return false + }, + }, + { + name: "removed", since: "1.7.0", reliable: true, + description: "removed blocks", + detect: func(s *scan) bool { return len(s.preserved["removed"]) > 0 }, + }, + { + name: "removed_provisioners", since: "1.9.0", reliable: true, + description: "destroy-time provisioners in removed blocks", + detect: func(s *scan) bool { + return removedProvisioners(s.preserved["removed"]) + }, + }, + { + name: "replace_triggered_by", since: "1.2.0", reliable: true, + description: "lifecycle replace_triggered_by argument", + detect: func(s *scan) bool { + return resourceLifecycleField(s.resources, "replace_triggered_by") + }, + }, + { + name: "terraform_data", since: "1.4.0", reliable: true, + description: "the built-in terraform_data resource", + detect: func(s *scan) bool { + for _, r := range s.resources { + if r.Type == "terraform_data" { + return true + } + } + return false + }, + }, + { + name: "terraform_data_store", since: "1.16.0", reliable: true, + description: "terraform_data store blocks", + detect: func(s *scan) bool { + for _, r := range s.resources { + if r.Type != "terraform_data" { + continue + } + if _, ok := r.Attributes["store"]; ok { + return true + } + if hasBlockType(r.Blocks, "store") { + return true + } + } + return false + }, + }, +} + +// Features returns the feature registry in alphabetical order. Each entry +// carries a Detect function that scans the given graph. +func Features() []Feature { + out := make([]Feature, 0, len(registry)) + for _, f := range registry { + f := f + out = append(out, Feature{ + Name: f.name, + Since: f.since, + Description: f.description, + Reliable: f.reliable, + Detect: func(g *ir.Graph) bool { return f.detect(scanGraph(g)) }, + }) + } + return out +} + +// Detect returns the names of the registered features present in g, sorted. +func Detect(g *ir.Graph) []string { + s := scanGraph(g) + var names []string + for _, f := range registry { + if f.detect(s) { + names = append(names, f.name) + } + } + sort.Strings(names) + return names +} + +// Analyze returns the detected features and the resulting minimum Terraform +// version for g. +func Analyze(g *ir.Graph) (features []string, minVersion string) { + features = Detect(g) + required := "" + if g != nil && g.Terraform != nil { + required = g.Terraform.RequiredVersion + } + return features, MinVersion(features, required) +} + +// MinVersion returns the oldest Terraform release that accepts a configuration +// with the given features and required_version constraint. +// +// The result is the newest of: the OpenIaC baseline, the constraint's lower +// bound, and the introduction version of every reliable detected feature. +func MinVersion(features []string, requiredVersion string) string { + best := Baseline + + if c, err := ParseConstraint(requiredVersion); err == nil && c.LowerBound != "" { + best = maxVersion(best, c.LowerBound) + } + + byName := make(map[string]feature, len(registry)) + for _, f := range registry { + byName[f.name] = f + } + for _, name := range features { + f, ok := byName[name] + if !ok || !f.reliable { + continue + } + best = maxVersion(best, f.since) + } + return best +} + +// scan is a single pass over a graph, shared by every detector. +type scan struct { + preserved map[string][]ir.Block + resources []*ir.Resource + variables []*ir.Variable + outputs []*ir.Output + requiredProviders map[string]ir.Value + cloud bool +} + +func scanGraph(g *ir.Graph) *scan { + s := &scan{preserved: map[string][]ir.Block{}} + if g == nil { + return s + } + + for _, b := range g.Preserved { + s.preserved[b.Type] = append(s.preserved[b.Type], b) + } + + if tf := g.Terraform; tf != nil { + s.cloud = tf.Cloud != nil + s.requiredProviders = tf.RequiredProviders + } + + s.resources = g.Resources + s.variables = g.Variables + s.outputs = g.Outputs + + return s +} + +// resourceLifecycleField reports whether a resource's own lifecycle block sets +// the named argument. +// +// It looks at resources specifically: a lifecycle block inside a removed block +// also accepts destroy, but that form predates 1.16 and must not move +// min_version. +func resourceLifecycleField(resources []*ir.Resource, field string) bool { + for _, r := range resources { + for _, b := range r.Blocks { + if b.Type != "lifecycle" { + continue + } + if _, ok := b.Attributes[field]; ok { + return true + } + } + // JSON spells lifecycle as an object property. + if v, ok := r.Attributes["lifecycle"]; ok && v.Kind == ir.KindMap { + if _, ok := v.Fields[field]; ok { + return true + } + } + } + return false +} + +// hasConditions reports whether a resource or output declares a precondition +// or postcondition, as a nested block (native HCL) or as a flat property +// (.tf.json). +func hasConditions(s *scan) bool { + for _, r := range s.resources { + if conditionField(r.Attributes, r.Blocks) { + return true + } + } + for _, o := range s.outputs { + if conditionField(o.Attributes, o.Blocks) { + return true + } + } + return false +} + +func conditionField(attrs map[string]ir.Value, blocks []ir.Block) bool { + for _, name := range []string{"precondition", "postcondition"} { + if _, ok := attrs[name]; ok { + return true + } + for _, b := range blocks { + if b.Type == name { + return true + } + } + } + return false +} + +// removedProvisioners reports whether a removed block carries a provisioner. +func removedProvisioners(blocks []ir.Block) bool { + for _, b := range blocks { + if _, ok := b.Attributes["provisioner"]; ok { + return true + } + if hasBlockType(b.Blocks, "provisioner") { + return true + } + } + return false +} + +// blockSetsAny reports whether any block, at any depth, sets one of the named +// arguments. +func blockSetsAny(blocks []ir.Block, names ...string) bool { + for _, b := range blocks { + for _, name := range names { + if _, ok := b.Attributes[name]; ok { + return true + } + } + if blockSetsAny(b.Blocks, names...) { + return true + } + } + return false +} + +func anyPreserved(blocks []ir.Block, pred func(ir.Block) bool) bool { + for _, b := range blocks { + if pred(b) { + return true + } + } + return false +} + +func hasBlockType(blocks []ir.Block, blockType string) bool { + for _, b := range blocks { + if b.Type == blockType || hasBlockType(b.Blocks, blockType) { + return true + } + } + return false +} + +func hasRefs(v ir.Value) bool { + if len(v.Refs) > 0 { + return true + } + for _, item := range v.Items { + if hasRefs(item) { + return true + } + } + for _, field := range v.Fields { + if hasRefs(field) { + return true + } + } + return false +} + +// valueText renders a value the way Terraform addresses are written: literal +// strings as-is, expressions in their source form. +func valueText(v ir.Value) string { + if v.Expr != "" { + return v.Expr + } + if s, ok := v.Literal.(string); ok { + return s + } + if v.Literal != nil { + return fmt.Sprint(v.Literal) + } + return v.Raw +} + +// addressType returns the resource type of a Terraform address, approximated by +// the second-to-last segment. It is only used by an unreliable detector. +func addressType(address string) string { + address = strings.TrimSpace(address) + parts := strings.Split(address, ".") + if len(parts) < 2 { + return "" + } + return parts[len(parts)-2] +} diff --git a/pkg/tfversion/features_test.go b/pkg/tfversion/features_test.go new file mode 100644 index 0000000..2fb757a --- /dev/null +++ b/pkg/tfversion/features_test.go @@ -0,0 +1,179 @@ +package tfversion_test + +import ( + "testing" + + "github.com/be-thomas/openiac/pkg/ir" + "github.com/be-thomas/openiac/pkg/tfversion" +) + +func TestFeaturesRegistry(t *testing.T) { + features := tfversion.Features() + if len(features) == 0 { + t.Fatal("feature registry is empty") + } + + seen := map[string]bool{} + previous := "" + for _, f := range features { + if seen[f.Name] { + t.Errorf("duplicate feature %q", f.Name) + } + seen[f.Name] = true + if f.Name < previous { + t.Errorf("features are not sorted: %q after %q", f.Name, previous) + } + previous = f.Name + + if f.Description == "" { + t.Errorf("%s: empty description", f.Name) + } + if f.Detect == nil { + t.Errorf("%s: nil detector", f.Name) + } + if _, ok := tfversion.Canonical(f.Since); !ok { + t.Errorf("%s: invalid since %q", f.Name, f.Since) + } + if tfversion.Compare(f.Since, tfversion.Baseline) < 0 { + t.Errorf("%s: since %q predates the baseline", f.Name, f.Since) + } + if tfversion.Compare(f.Since, tfversion.Latest) > 0 { + t.Errorf("%s: since %q is newer than the latest known release", f.Name, f.Since) + } + } +} + +func TestDetectNilGraph(t *testing.T) { + if got := tfversion.Detect(nil); len(got) != 0 { + t.Errorf("Detect(nil) = %v, want none", got) + } + features, min := tfversion.Analyze(nil) + if len(features) != 0 || min != tfversion.Baseline { + t.Errorf("Analyze(nil) = (%v, %q)", features, min) + } +} + +func TestMinVersion(t *testing.T) { + cases := []struct { + features []string + required string + want string + }{ + {nil, "", "1.0.0"}, + {nil, ">= 0.12", "1.0.0"}, + {nil, ">= 1.6.2", "1.6.2"}, + {nil, ">= 1.6.2, < 2.0", "1.6.2"}, + {nil, "nonsense", "1.0.0"}, + {[]string{"check"}, "", "1.5.0"}, + {[]string{"check"}, ">= 1.6.0", "1.6.0"}, + {[]string{"action", "moved"}, ">= 1.0", "1.14.0"}, + {[]string{"unknown_feature"}, "", "1.0.0"}, + // Unreliable detectors never move the minimum. + {[]string{"moved_cross_type", "action_lifecycle_events"}, "", "1.0.0"}, + } + for _, c := range cases { + if got := tfversion.MinVersion(c.features, c.required); got != c.want { + t.Errorf("MinVersion(%v, %q) = %q, want %q", c.features, c.required, got, c.want) + } + } +} + +func TestDetectJSONFlatLifecycle(t *testing.T) { + graph := &ir.Graph{ + Version: ir.Version, + Resources: []*ir.Resource{{ + ID: "aws_vpc.main", + Kind: ir.KindResource, + Type: "aws_vpc", + Name: "main", + // .tf.json spells lifecycle as an object property. + Attributes: map[string]ir.Value{ + "lifecycle": { + Kind: ir.KindMap, + Fields: map[string]ir.Value{ + "destroy": {Kind: ir.KindBool, Literal: false}, + "replace_triggered_by": {Kind: ir.KindList}, + }, + }, + }, + }}, + } + features := tfversion.Detect(graph) + if !contains(features, "lifecycle_destroy") { + t.Errorf("features = %v, want lifecycle_destroy", features) + } + if !contains(features, "replace_triggered_by") { + t.Errorf("features = %v, want replace_triggered_by", features) + } + if got := tfversion.MinVersion(features, ""); got != "1.16.0" { + t.Errorf("min_version = %q, want 1.16.0", got) + } +} + +func TestDetectJSONFlatConditions(t *testing.T) { + graph := &ir.Graph{ + Version: ir.Version, + Outputs: []*ir.Output{{ + Name: "ip", + Attributes: map[string]ir.Value{ + "precondition": {Kind: ir.KindMap, Fields: map[string]ir.Value{ + "condition": {Kind: ir.KindString, Literal: "true"}, + }}, + }, + }}, + } + if features := tfversion.Detect(graph); !contains(features, "conditions") { + t.Errorf("features = %v, want conditions", features) + } +} + +func TestDetectIgnoresRemovedLifecycleDestroy(t *testing.T) { + // removed { lifecycle { destroy = false } } exists since 1.9, so it must not + // be reported as the 1.16 resource-level lifecycle destroy. + graph := &ir.Graph{ + Version: ir.Version, + Preserved: []ir.Block{{ + Type: "removed", + Blocks: []ir.Block{{ + Type: "lifecycle", + Attributes: map[string]ir.Value{"destroy": {Kind: ir.KindBool}}, + }}, + }}, + } + features := tfversion.Detect(graph) + if contains(features, "lifecycle_destroy") { + t.Errorf("features = %v, lifecycle_destroy must not fire for removed blocks", features) + } + if !contains(features, "removed") { + t.Errorf("features = %v, want removed", features) + } +} + +func TestDetectActionEventsDoNotUseProvisionerOnFailure(t *testing.T) { + // on_failure is also a provisioner argument, so it must only count inside an + // action block. + graph := &ir.Graph{ + Version: ir.Version, + Resources: []*ir.Resource{{ + ID: "aws_instance.web", + Kind: ir.KindResource, + Type: "aws_instance", + Name: "web", + Blocks: []ir.Block{{Type: "provisioner", Labels: []string{"local-exec"}, Attributes: map[string]ir.Value{ + "on_failure": {Kind: ir.KindString, Literal: "continue"}, + }}}, + }}, + } + if features := tfversion.Detect(graph); contains(features, "action_lifecycle_events") { + t.Errorf("features = %v, action_lifecycle_events must not fire", features) + } +} + +func contains(values []string, want string) bool { + for _, value := range values { + if value == want { + return true + } + } + return false +} diff --git a/pkg/tfversion/version.go b/pkg/tfversion/version.go new file mode 100644 index 0000000..b566238 --- /dev/null +++ b/pkg/tfversion/version.go @@ -0,0 +1,123 @@ +// Package tfversion maps the Terraform language features found in an IR graph +// to the oldest Terraform release that accepts the configuration. +// +// It is a pure package: it depends only on pkg/ir and golang.org/x/mod/semver, +// and it never fails the parse. A configuration whose required_version cannot +// be understood still parses; only MinVersion falls back to the detected +// feature set. +package tfversion + +import ( + "strings" + + "golang.org/x/mod/semver" +) + +const ( + // Baseline is the oldest Terraform release OpenIaC targets. A configuration + // that uses only Terraform 1.0 constructs reports this version even if it + // would also parse under 0.12. + Baseline = "1.0.0" + + // Latest is the newest Terraform release OpenIaC understands. Features + // introduced by later releases are preserved generically and do not move + // MinVersion past this value. + Latest = "1.17.0" +) + +// Canonical returns the canonical "MAJOR.MINOR.PATCH" form of a Terraform +// version string. It accepts one, two or three numeric components with the +// optional leading "v" that semver requires. Pre-release and build forms are +// rejected: they never appear in Terraform's own version numbers. +func Canonical(s string) (string, bool) { + s = strings.TrimSpace(s) + if s == "" { + return "", false + } + v := s + if !strings.HasPrefix(v, "v") { + v = "v" + s + } + // Reject pre-release and build metadata before semver normalizes them away. + if strings.ContainsAny(v, "-+") { + return "", false + } + if !semver.IsValid(v) { + return "", false + } + c := semver.Canonical(v) + if c == "" { + return "", false + } + return strings.TrimPrefix(c, "v"), true +} + +// Compare returns -1, 0 or 1 as a is older than, equal to or newer than b. +// Unparseable versions compare as older than any parseable one. +func Compare(a, b string) int { + ca, oka := Canonical(a) + cb, okb := Canonical(b) + switch { + case !oka && !okb: + return 0 + case !oka: + return -1 + case !okb: + return 1 + } + return semver.Compare("v"+ca, "v"+cb) +} + +// maxVersion returns the newer of two canonical versions. +func maxVersion(a, b string) string { + if Compare(a, b) >= 0 { + return a + } + return b +} + +// bumpPatch returns the smallest version strictly greater than a canonical +// version, which is what a strict ">" constraint lower-bounds. +func bumpPatch(canonical string) (string, bool) { + c, ok := Canonical(canonical) + if !ok { + return "", false + } + parts := strings.Split(c, ".") + if len(parts) != 3 { + return "", false + } + patch, ok := parseUint(parts[2]) + if !ok { + return "", false + } + return parts[0] + "." + parts[1] + "." + itoa(patch+1), true +} + +func parseUint(s string) (int, bool) { + if s == "" { + return 0, false + } + n := 0 + for _, r := range s { + if r < '0' || r > '9' { + return 0, false + } + n = n*10 + int(r-'0') + } + return n, true +} + +func itoa(n int) string { + if n == 0 { + return "0" + } + var buf [20]byte + i := len(buf) + for n > 0 { + i-- + buf[i] = byte('0' + n%10) + n /= 10 + } + return string(buf[i:]) +} diff --git a/pkg/tfversion/version_test.go b/pkg/tfversion/version_test.go new file mode 100644 index 0000000..f58fb37 --- /dev/null +++ b/pkg/tfversion/version_test.go @@ -0,0 +1,60 @@ +package tfversion_test + +import ( + "testing" + + "github.com/be-thomas/openiac/pkg/tfversion" +) + +func TestCanonical(t *testing.T) { + cases := []struct { + in string + want string + ok bool + }{ + {"1", "1.0.0", true}, + {"1.5", "1.5.0", true}, + {"1.5.2", "1.5.2", true}, + {"v1.6.0", "1.6.0", true}, + {" v1.10.3 ", "1.10.3", true}, + {"1.2.3-beta1", "", false}, + {"1.2.3+build.5", "", false}, + {"latest", "", false}, + {"", "", false}, + {"v", "", false}, + {"1..2", "", false}, + } + for _, c := range cases { + got, ok := tfversion.Canonical(c.in) + if got != c.want || ok != c.ok { + t.Errorf("Canonical(%q) = (%q, %v), want (%q, %v)", c.in, got, ok, c.want, c.ok) + } + } +} + +func TestCompare(t *testing.T) { + cases := []struct { + a, b string + want int + }{ + {"1.9", "1.10", -1}, + {"1.10", "1.9", 1}, + {"1.10.0", "1.10", 0}, + {"v1.5.0", "1.5.0", 0}, + {"1.0.0", "1.0.1", -1}, + {"nonsense", "1.0.0", -1}, + {"1.0.0", "nonsense", 1}, + {"nonsense", "also nonsense", 0}, + } + for _, c := range cases { + if got := tfversion.Compare(c.a, c.b); got != c.want { + t.Errorf("Compare(%q, %q) = %d, want %d", c.a, c.b, got, c.want) + } + } +} + +func TestBaselineWithinSupportedRange(t *testing.T) { + if tfversion.Compare(tfversion.Baseline, tfversion.Latest) >= 0 { + t.Fatalf("baseline %s must be older than latest %s", tfversion.Baseline, tfversion.Latest) + } +} From 5da16a57549c80577050272be6fa499354d6b253 Mon Sep 17 00:00:00 2001 From: Thomas Sudeep Benardo <36351384+be-thomas@users.noreply.github.com> Date: Mon, 26 Oct 2026 07:25:20 +0530 Subject: [PATCH 2/4] Fix .tf.json nested blocks, 1.17 detection and IR docs Recover JSON flat map and list attributes as nested blocks in both emitters whenever the mapping declares that block type, so .tf.json and native HCL generate the same TypeScript. Declare the Pulumi security group ingress and egress blocks so the two targets agree on the schema. Restrict provider_requirements_expressions to variable and local references. configuration_aliases writes a provider address such as aws.west, which has been valid since aliases existed and must not raise min_version to 1.17. Correct the Block.File doc comment and the HasNode rule in docs/IR.md, and state precisely how emitters recover flat JSON blocks. --- docs/IR.md | 12 ++- docs/TERRAFORM-VERSIONS.md | 4 +- pkg/emitters/awscdk/emitter.go | 28 ++++++- pkg/emitters/blocks.go | 89 ++++++++++++++++++++++ pkg/emitters/json_parity_test.go | 127 +++++++++++++++++++++++++++++++ pkg/emitters/pulumi/emitter.go | 33 +++++++- pkg/ir/types.go | 6 +- pkg/mappings/aws.json | 9 ++- pkg/tfversion/features.go | 19 +++-- pkg/tfversion/features_test.go | 39 ++++++++++ 10 files changed, 348 insertions(+), 18 deletions(-) create mode 100644 pkg/emitters/blocks.go create mode 100644 pkg/emitters/json_parity_test.go diff --git a/docs/IR.md b/docs/IR.md index c2d4bb4..e8a0eb2 100644 --- a/docs/IR.md +++ b/docs/IR.md @@ -307,8 +307,10 @@ Rules: - **Only resources and data sources produce edges.** An output reading `aws_vpc.main.id` does not create an edge, because outputs are not ordered. -- **An edge is only created when both ends are nodes.** `HasNode` filters - references to variables, locals and modules out of the resource graph. +- **An edge is only created when both ends name a node.** `HasNode` recognises + resource and data source addresses and the `var.`, `local.` and `module.` + forms, so those edges are kept; a reference such as `aws.west` or + `path.module` is dropped. - **Duplicates and self-edges are dropped.** `AddEdge` is idempotent; add them in any order. - **Preserved blocks never create edges.** A `moved` or `import` block mentions @@ -429,8 +431,10 @@ kind must treat it as "cannot convert" and warn, never as a literal. - **No imperative logic.** There are no conditionals or loops to render; a parser either resolves them or reports an expression. - **JSON bodies are flat below the top level.** HCL exposes no block structure in - a `.tf.json` body, so a nested block arrives as a `map` value. This is - documented rather than guessed. + a `.tf.json` body, so a nested block arrives as a `map` value. An emitter that + knows its block schema recovers the native shape with + `emitters.UnflattenBlocks`; otherwise the value stays flat. This is documented + rather than guessed. - **`line` is informational.** It is not stable across reformatting and must not be used for identity. diff --git a/docs/TERRAFORM-VERSIONS.md b/docs/TERRAFORM-VERSIONS.md index 240d49b..cf1efa8 100644 --- a/docs/TERRAFORM-VERSIONS.md +++ b/docs/TERRAFORM-VERSIONS.md @@ -191,7 +191,9 @@ Two differences matter to consumers: - **Bodies below the top level are flat.** HCL exposes no block structure inside a JSON body, so an object property becomes a `map` value rather than a nested `Block`. `lifecycle`, `default_tags`, `provisioner` and friends therefore - appear in `attributes`, not `blocks`. Every consumer must accept both shapes. + appear in `attributes`, not `blocks`. An emitter that knows its schema calls + `emitters.UnflattenBlocks` to recover them, so both syntaxes produce the same + TypeScript; a block type no mapping declares stays a flat value. Expressions keep working: a JSON string containing `${β¦}` or `%{β¦}` becomes an `expr` value with its references collected, and is normalised to a quoted HCL diff --git a/pkg/emitters/awscdk/emitter.go b/pkg/emitters/awscdk/emitter.go index bd4f25a..a49a94a 100644 --- a/pkg/emitters/awscdk/emitter.go +++ b/pkg/emitters/awscdk/emitter.go @@ -204,8 +204,23 @@ func (r *run) emitResources(body *strings.Builder, ordered []*ir.Resource, rewri func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.CDKMapping, rewriter *emitutil.RefRewriter) string { var lines []string + // .tf.json leaves nested blocks as flat map/list attributes; recover the + // shape native HCL would have produced before rendering either one. + var schema map[string]mappings.BlockMap + if mapping != nil { + schema = mapping.Blocks + } + flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema) + blocks := resource.Blocks + if len(flatBlocks) > 0 { + blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) + } + names := sortedKeys(resource.Attributes) for _, name := range names { + if consumed[name] { + continue + } if name == "count" || name == "for_each" { r.warnings.Addf("%s: %s is not supported yet; property skipped", resource.ID, name) continue @@ -222,7 +237,7 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.CDKMappi lines = append(lines, fmt.Sprintf(" %s: %s,", prop.Name, value)) } - order, grouped := emitters.GroupBlocks(resource.Blocks) + order, grouped := emitters.GroupBlocks(blocks) for _, blockType := range order { blockMap, ok := mapping.Blocks[blockType] if !ok { @@ -275,7 +290,16 @@ func (r *run) renderBlockGroup(blocks []ir.Block, blockMap mappings.BlockMap, re func (r *run) renderBlockObject(block ir.Block, blockMap mappings.BlockMap, rewriter *emitutil.RefRewriter, context string) (string, bool) { var parts []string + flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, blockMap.Blocks) + blocks := block.Blocks + if len(flatBlocks) > 0 { + blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) + } + for _, name := range sortedKeys(block.Attributes) { + if consumed[name] { + continue + } prop, ok := blockMap.Properties[name] if !ok { r.warnings.Addf("%s: block %q property %q has no CDK mapping; skipped", context, block.Type, name) @@ -288,7 +312,7 @@ func (r *run) renderBlockObject(block ir.Block, blockMap mappings.BlockMap, rewr parts = append(parts, fmt.Sprintf("%s: %s", prop.Name, value)) } - order, grouped := emitters.GroupBlocks(block.Blocks) + order, grouped := emitters.GroupBlocks(blocks) for _, nestedType := range order { nestedMap, ok := blockMap.Blocks[nestedType] if !ok { diff --git a/pkg/emitters/blocks.go b/pkg/emitters/blocks.go new file mode 100644 index 0000000..89e7102 --- /dev/null +++ b/pkg/emitters/blocks.go @@ -0,0 +1,89 @@ +package emitters + +import ( + "sort" + + "github.com/be-thomas/openiac/pkg/ir" + "github.com/be-thomas/openiac/pkg/mappings" +) + +// UnflattenBlocks recovers nested blocks from a flat .tf.json body. +// +// Terraform's JSON syntax has no way to spell a nested block below the top +// level, so the parser leaves e.g. "versioning": {"enabled": true} as a map +// attribute, while native HCL produces a block. An emitter that knows its +// schema passes it here: every attribute whose name is a registered block type +// is converted back into the blocks HCL would have produced, and reported in +// consumed so the caller does not also render it as a property. +// +// Values that do not fit a block shape (a scalar, a list of scalars) are left +// alone. Blocks are returned in sorted attribute-name order so output stays +// deterministic. +func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.BlockMap) (blocks []ir.Block, consumed map[string]bool) { + if len(attrs) == 0 || len(schema) == 0 { + return nil, nil + } + + names := make([]string, 0, len(attrs)) + for name := range attrs { + if _, ok := schema[name]; ok { + names = append(names, name) + } + } + if len(names) == 0 { + return nil, nil + } + sort.Strings(names) + + consumed = make(map[string]bool, len(names)) + for _, name := range names { + converted := blocksFromValue(name, attrs[name], schema[name]) + if len(converted) == 0 { + continue + } + consumed[name] = true + blocks = append(blocks, converted...) + } + return blocks, consumed +} + +// blocksFromValue converts one flat attribute into the blocks it represents: a +// single object is one block, an array of objects is one block per element. +func blocksFromValue(typ string, v ir.Value, blockMap mappings.BlockMap) []ir.Block { + if v.Kind == ir.KindList { + blocks := make([]ir.Block, 0, len(v.Items)) + for _, item := range v.Items { + if block, ok := blockFromMap(typ, item, blockMap); ok { + blocks = append(blocks, block) + } + } + return blocks + } + if block, ok := blockFromMap(typ, v, blockMap); ok { + return []ir.Block{block} + } + return nil +} + +func blockFromMap(typ string, v ir.Value, blockMap mappings.BlockMap) (ir.Block, bool) { + if v.Kind != ir.KindMap { + return ir.Block{}, false + } + + block := ir.Block{ + Type: typ, + Attributes: make(map[string]ir.Value, len(v.Fields)), + } + for name, value := range v.Fields { + block.Attributes[name] = value + } + + if len(blockMap.Blocks) > 0 { + nested, consumed := UnflattenBlocks(block.Attributes, blockMap.Blocks) + for name := range consumed { + delete(block.Attributes, name) + } + block.Blocks = nested + } + return block, true +} diff --git a/pkg/emitters/json_parity_test.go b/pkg/emitters/json_parity_test.go new file mode 100644 index 0000000..633bebe --- /dev/null +++ b/pkg/emitters/json_parity_test.go @@ -0,0 +1,127 @@ +package emitters_test + +import ( + "strings" + "testing" + + "github.com/be-thomas/openiac/pkg/emitters" + "github.com/be-thomas/openiac/pkg/emitters/awscdk" + "github.com/be-thomas/openiac/pkg/emitters/pulumi" + "github.com/be-thomas/openiac/pkg/ir" + "github.com/be-thomas/openiac/pkg/mappings" + hclparser "github.com/be-thomas/openiac/pkg/parsers/hcl" +) + +// Terraform's JSON syntax cannot spell a nested block below the top level, so +// the parser leaves it as a map or array attribute. Both syntaxes must still +// produce the same TypeScript. +const ( + nativeNested = ` +resource "aws_s3_bucket" "logs" { + bucket = "logs" + versioning { + enabled = true + } +} + +resource "aws_security_group" "web" { + name = "web" + ingress { + from_port = 80 + to_port = 80 + protocol = "tcp" + cidr_blocks = ["0.0.0.0/0"] + } +} +` + + jsonNested = `{ + "resource": { + "aws_s3_bucket": { + "logs": { + "bucket": "logs", + "versioning": { "enabled": true } + } + }, + "aws_security_group": { + "web": { + "name": "web", + "ingress": [ + { + "from_port": 80, + "to_port": 80, + "protocol": "tcp", + "cidr_blocks": ["0.0.0.0/0"] + } + ] + } + } + } +}` +) + +func parseSource(t *testing.T, src, filename string) *ir.Graph { + t.Helper() + graph, err := hclparser.ParseString(src, filename) + if err != nil { + t.Fatalf("ParseString(%s): %v", filename, err) + } + return graph +} + +func emitBoth(t *testing.T, graph *ir.Graph) map[string]*emitters.Result { + t.Helper() + cdk, err := awscdk.New().Emit(graph, emitters.Options{}) + if err != nil { + t.Fatalf("cdk Emit: %v", err) + } + pulumiOut, err := pulumi.New().Emit(graph, emitters.Options{}) + if err != nil { + t.Fatalf("pulumi Emit: %v", err) + } + return map[string]*emitters.Result{"cdk": cdk, "pulumi": pulumiOut} +} + +func TestJSONNestedBlocksMatchNativeOutput(t *testing.T) { + native := emitBoth(t, parseSource(t, nativeNested, "main.tf")) + jsonSyntax := emitBoth(t, parseSource(t, jsonNested, "main.tf.json")) + + for target := range native { + nativeFiles := native[target].Files + jsonFiles := jsonSyntax[target].Files + if len(nativeFiles) != len(jsonFiles) { + t.Fatalf("%s: files = %d vs %d", target, len(nativeFiles), len(jsonFiles)) + } + for i := range nativeFiles { + want := nativeFiles[i].Content + got := strings.ReplaceAll(jsonFiles[i].Content, "main.tf.json", "main.tf") + if got != want { + t.Errorf("%s: %s differs between native HCL and .tf.json\n--- native\n%s\n--- json\n%s", + target, nativeFiles[i].Path, want, got) + } + } + } +} + +func TestJSONNestedBlocksDoNotWarn(t *testing.T) { + for target, result := range emitBoth(t, parseSource(t, jsonNested, "main.tf.json")) { + for _, warning := range result.Warnings { + if strings.Contains(warning, "versioning") || strings.Contains(warning, "ingress") { + t.Errorf("%s: nested block reported as unconverted: %s", target, warning) + } + } + } +} + +func TestUnflattenBlocksIgnoresScalars(t *testing.T) { + blocks, consumed := emitters.UnflattenBlocks( + map[string]ir.Value{ + "versioning": {Kind: ir.KindBool, Literal: true}, + "bucket": {Kind: ir.KindString, Literal: "logs"}, + }, + map[string]mappings.BlockMap{"versioning": {Property: "versioned"}}, + ) + if len(blocks) != 0 || len(consumed) != 0 { + t.Fatalf("blocks=%v consumed=%v, want nothing", blocks, consumed) + } +} diff --git a/pkg/emitters/pulumi/emitter.go b/pkg/emitters/pulumi/emitter.go index 7c2c5fc..b2cc006 100644 --- a/pkg/emitters/pulumi/emitter.go +++ b/pkg/emitters/pulumi/emitter.go @@ -216,7 +216,22 @@ func (r *run) emitResources(body *strings.Builder, ordered []*ir.Resource, rewri func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.PulumiMapping, rewriter *emitutil.RefRewriter) string { var lines []string + // .tf.json leaves nested blocks as flat map/list attributes; recover the + // shape native HCL would have produced before rendering either one. + var schema map[string]mappings.BlockMap + if mapping != nil { + schema = mapping.Blocks + } + flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema) + blocks := resource.Blocks + if len(flatBlocks) > 0 { + blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) + } + for _, name := range sortedKeys(resource.Attributes) { + if consumed[name] { + continue + } if name == "count" || name == "for_each" { r.warnings.Addf("%s: %s is not supported yet; property skipped", resource.ID, name) continue @@ -231,7 +246,7 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.PulumiMa lines = append(lines, fmt.Sprintf(" %s: %s,", property, value)) } - order, grouped := emitters.GroupBlocks(resource.Blocks) + order, grouped := emitters.GroupBlocks(blocks) for _, blockType := range order { var blockMap *mappings.BlockMap if mapping != nil { @@ -291,7 +306,21 @@ func (r *run) renderBlockGroup(blocks []ir.Block, blockMap *mappings.BlockMap, r func (r *run) renderBlockObject(block ir.Block, blockMap *mappings.BlockMap, rewriter *emitutil.RefRewriter, context string) (string, bool) { var parts []string + + var schema map[string]mappings.BlockMap + if blockMap != nil { + schema = blockMap.Blocks + } + flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, schema) + blocks := block.Blocks + if len(flatBlocks) > 0 { + blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) + } + for _, name := range sortedKeys(block.Attributes) { + if consumed[name] { + continue + } property := emitutil.CamelCase(name) if blockMap != nil { if override, ok := blockMap.Properties[name]; ok { @@ -301,7 +330,7 @@ func (r *run) renderBlockObject(block ir.Block, blockMap *mappings.BlockMap, rew parts = append(parts, fmt.Sprintf("%s: %s", property, emitutil.RenderValue(block.Attributes[name], rewriter))) } - order, grouped := emitters.GroupBlocks(block.Blocks) + order, grouped := emitters.GroupBlocks(blocks) for _, nestedType := range order { var nestedMap *mappings.BlockMap if blockMap != nil { diff --git a/pkg/ir/types.go b/pkg/ir/types.go index 0dd57c5..bf84fcb 100644 --- a/pkg/ir/types.go +++ b/pkg/ir/types.go @@ -108,8 +108,10 @@ type Block struct { // properties of a .tf.json document; native HCL always fills Attributes and // Blocks. Body *Value `json:"body,omitempty"` - // File is set for top-level blocks. Nested blocks inherit their parent's - // file and leave this empty. + // File and Line locate the block. Top-level and native nested blocks carry + // both. A block derived from a flat .tf.json body carries the enclosing + // file and no line, because JSON has no per-block position below the top + // level. File string `json:"file,omitempty"` Line int `json:"line,omitempty"` } diff --git a/pkg/mappings/aws.json b/pkg/mappings/aws.json index 188f2b5..8fc9108 100644 --- a/pkg/mappings/aws.json +++ b/pkg/mappings/aws.json @@ -121,7 +121,14 @@ "id": "attrGroupId" } }, - "pulumi": { "module": "ec2", "class": "SecurityGroup" } + "pulumi": { + "module": "ec2", + "class": "SecurityGroup", + "blocks": { + "ingress": { "property": "ingress", "shape": "array" }, + "egress": { "property": "egress", "shape": "array" } + } + } }, "aws_internet_gateway": { "cdk": { diff --git a/pkg/tfversion/features.go b/pkg/tfversion/features.go index 31a73c6..872f989 100644 --- a/pkg/tfversion/features.go +++ b/pkg/tfversion/features.go @@ -215,7 +215,7 @@ var registry = []feature{ description: "variables and locals in provider requirements", detect: func(s *scan) bool { for _, v := range s.requiredProviders { - if hasRefs(v) { + if hasVariableOrLocalRef(v) { return true } } @@ -476,17 +476,24 @@ func hasBlockType(blocks []ir.Block, blockType string) bool { return false } -func hasRefs(v ir.Value) bool { - if len(v.Refs) > 0 { - return true +// hasVariableOrLocalRef reports whether a required_providers declaration reads +// a variable or a local, which is what Terraform 1.17 added. Other references +// are not a version signal: configuration_aliases writes a provider address +// such as aws.west, and that form has been valid since providers gained +// aliases. +func hasVariableOrLocalRef(v ir.Value) bool { + for _, ref := range v.Refs { + if strings.HasPrefix(ref, "var.") || strings.HasPrefix(ref, "local.") { + return true + } } for _, item := range v.Items { - if hasRefs(item) { + if hasVariableOrLocalRef(item) { return true } } for _, field := range v.Fields { - if hasRefs(field) { + if hasVariableOrLocalRef(field) { return true } } diff --git a/pkg/tfversion/features_test.go b/pkg/tfversion/features_test.go index 2fb757a..e29bab7 100644 --- a/pkg/tfversion/features_test.go +++ b/pkg/tfversion/features_test.go @@ -169,6 +169,45 @@ func TestDetectActionEventsDoNotUseProvisionerOnFailure(t *testing.T) { } } +func TestDetectProviderRequirementsOnlyForVariablesAndLocals(t *testing.T) { + // configuration_aliases writes a provider address (aws.west), which has + // been valid since providers gained aliases. Only a variable or local in + // the requirement is the 1.17 feature. + aliased := &ir.Graph{ + Version: ir.Version, + Terraform: &ir.Terraform{RequiredProviders: map[string]ir.Value{ + "aws": {Kind: ir.KindMap, Fields: map[string]ir.Value{ + "source": {Kind: ir.KindString, Literal: "hashicorp/aws"}, + "configuration_aliases": {Kind: ir.KindList, Items: []ir.Value{ + {Kind: ir.KindExpr, Expr: "aws.west", Refs: []string{"aws.west"}}, + }}, + }}, + }}, + } + if features := tfversion.Detect(aliased); contains(features, "provider_requirements_expressions") { + t.Errorf("features = %v, configuration_aliases must not fire the detector", features) + } + if _, min := tfversion.Analyze(aliased); min != tfversion.Baseline { + t.Errorf("min_version = %q, want %q", min, tfversion.Baseline) + } + + withVariable := &ir.Graph{ + Version: ir.Version, + Terraform: &ir.Terraform{RequiredProviders: map[string]ir.Value{ + "aws": {Kind: ir.KindMap, Fields: map[string]ir.Value{ + "version": {Kind: ir.KindExpr, Expr: "var.aws_version", Refs: []string{"var.aws_version"}}, + }}, + }}, + } + features, min := tfversion.Analyze(withVariable) + if !contains(features, "provider_requirements_expressions") { + t.Errorf("features = %v, want provider_requirements_expressions", features) + } + if min != "1.17.0" { + t.Errorf("min_version = %q, want 1.17.0", min) + } +} + func contains(values []string, want string) bool { for _, value := range values { if value == want { From 636ff1c98d1fc95147a9ea5a1502ae40c6aca133 Mon Sep 17 00:00:00 2001 From: Thomas Sudeep Benardo <36351384+be-thomas@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:16:25 +0530 Subject: [PATCH 3/4] Handle JSON interpolations, empty block arrays and duplicate blocks A .tf.json string that is exactly one interpolation, such as "${var.port}", is evaluated by Terraform to the inner expression's value and type, not to a string. The parser now keeps the bare expression, so a recovered block renders the same TypeScript as the native form instead of wrapping it in a string template. UnflattenBlocks now treats an empty array as an absent block, matching native HCL with no such block, and leaves an attribute alone when a block of the same type already exists natively, so invalid input is reported rather than rendered twice. Docs describe the interpolation rule. --- docs/TERRAFORM-VERSIONS.md | 7 ++- pkg/emitters/awscdk/emitter.go | 4 +- pkg/emitters/blocks.go | 65 +++++++++++++++++-------- pkg/emitters/json_parity_test.go | 82 +++++++++++++++++++++++++++++++- pkg/emitters/pulumi/emitter.go | 4 +- pkg/parsers/hcl/json.go | 38 +++++++++++++++ pkg/parsers/hcl/json_test.go | 17 +++++-- 7 files changed, 184 insertions(+), 33 deletions(-) diff --git a/docs/TERRAFORM-VERSIONS.md b/docs/TERRAFORM-VERSIONS.md index cf1efa8..0d5c6af 100644 --- a/docs/TERRAFORM-VERSIONS.md +++ b/docs/TERRAFORM-VERSIONS.md @@ -196,8 +196,11 @@ Two differences matter to consumers: TypeScript; a block type no mapping declares stays a flat value. Expressions keep working: a JSON string containing `${β¦}` or `%{β¦}` becomes an -`expr` value with its references collected, and is normalised to a quoted HCL -template so the emitters render identical TypeScript for both syntaxes. +`expr` value with its references collected. A string that is exactly one +interpolation, such as `"${var.port}"`, keeps the bare inner expression, +because Terraform evaluates it to that expression's value and type; any other +template is normalised to a quoted HCL template. Either way both syntaxes render +identical TypeScript. ## Out of scope diff --git a/pkg/emitters/awscdk/emitter.go b/pkg/emitters/awscdk/emitter.go index a49a94a..ced56b6 100644 --- a/pkg/emitters/awscdk/emitter.go +++ b/pkg/emitters/awscdk/emitter.go @@ -210,7 +210,7 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.CDKMappi if mapping != nil { schema = mapping.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema) + flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) blocks := resource.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) @@ -290,7 +290,7 @@ func (r *run) renderBlockGroup(blocks []ir.Block, blockMap mappings.BlockMap, re func (r *run) renderBlockObject(block ir.Block, blockMap mappings.BlockMap, rewriter *emitutil.RefRewriter, context string) (string, bool) { var parts []string - flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, blockMap.Blocks) + flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, blockMap.Blocks, block.Blocks) blocks := block.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) diff --git a/pkg/emitters/blocks.go b/pkg/emitters/blocks.go index 89e7102..7c2d55c 100644 --- a/pkg/emitters/blocks.go +++ b/pkg/emitters/blocks.go @@ -16,17 +16,27 @@ import ( // is converted back into the blocks HCL would have produced, and reported in // consumed so the caller does not also render it as a property. // -// Values that do not fit a block shape (a scalar, a list of scalars) are left -// alone. Blocks are returned in sorted attribute-name order so output stays -// deterministic. -func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.BlockMap) (blocks []ir.Block, consumed map[string]bool) { +// existing lists the blocks the caller already has. A type that is present +// there is left alone, so an attribute that duplicates a native block is still +// reported as an unsupported property rather than rendered a second time. +// +// Values that do not fit a block shape (a scalar, a list holding a scalar) are +// left alone. An empty array counts as a block shape: it means the block is +// absent, which is what native HCL with no such block means. Blocks are +// returned in sorted attribute-name order so output stays deterministic. +func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.BlockMap, existing []ir.Block) (blocks []ir.Block, consumed map[string]bool) { if len(attrs) == 0 || len(schema) == 0 { return nil, nil } + native := make(map[string]bool, len(existing)) + for _, block := range existing { + native[block.Type] = true + } + names := make([]string, 0, len(attrs)) - for name := range attrs { - if _, ok := schema[name]; ok { + for name, value := range attrs { + if _, ok := schema[name]; ok && !native[name] && blockShape(value) { names = append(names, name) } } @@ -37,32 +47,45 @@ func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.Block consumed = make(map[string]bool, len(names)) for _, name := range names { - converted := blocksFromValue(name, attrs[name], schema[name]) - if len(converted) == 0 { - continue - } consumed[name] = true - blocks = append(blocks, converted...) + blocks = append(blocks, blocksFromValue(name, attrs[name], schema[name])...) } return blocks, consumed } -// blocksFromValue converts one flat attribute into the blocks it represents: a -// single object is one block, an array of objects is one block per element. +// blockShape reports whether a flat JSON value has the shape of nested blocks: +// one object, or an array of objects. An empty array is included, because it +// says the block is absent rather than that it is an attribute. +func blockShape(v ir.Value) bool { + switch v.Kind { + case ir.KindMap: + return true + case ir.KindList: + for _, item := range v.Items { + if item.Kind != ir.KindMap { + return false + } + } + return true + default: + return false + } +} + +// blocksFromValue converts a value that blockShape accepted into the blocks it +// represents: a single object is one block, an array of objects is one block +// per element. func blocksFromValue(typ string, v ir.Value, blockMap mappings.BlockMap) []ir.Block { if v.Kind == ir.KindList { blocks := make([]ir.Block, 0, len(v.Items)) for _, item := range v.Items { - if block, ok := blockFromMap(typ, item, blockMap); ok { - blocks = append(blocks, block) - } + block, _ := blockFromMap(typ, item, blockMap) + blocks = append(blocks, block) } return blocks } - if block, ok := blockFromMap(typ, v, blockMap); ok { - return []ir.Block{block} - } - return nil + block, _ := blockFromMap(typ, v, blockMap) + return []ir.Block{block} } func blockFromMap(typ string, v ir.Value, blockMap mappings.BlockMap) (ir.Block, bool) { @@ -79,7 +102,7 @@ func blockFromMap(typ string, v ir.Value, blockMap mappings.BlockMap) (ir.Block, } if len(blockMap.Blocks) > 0 { - nested, consumed := UnflattenBlocks(block.Attributes, blockMap.Blocks) + nested, consumed := UnflattenBlocks(block.Attributes, blockMap.Blocks, nil) for name := range consumed { delete(block.Attributes, name) } diff --git a/pkg/emitters/json_parity_test.go b/pkg/emitters/json_parity_test.go index 633bebe..968f2ac 100644 --- a/pkg/emitters/json_parity_test.go +++ b/pkg/emitters/json_parity_test.go @@ -17,6 +17,10 @@ import ( // produce the same TypeScript. const ( nativeNested = ` +variable "port" { + type = number +} + resource "aws_s3_bucket" "logs" { bucket = "logs" versioning { @@ -27,7 +31,7 @@ resource "aws_s3_bucket" "logs" { resource "aws_security_group" "web" { name = "web" ingress { - from_port = 80 + from_port = var.port to_port = 80 protocol = "tcp" cidr_blocks = ["0.0.0.0/0"] @@ -36,6 +40,9 @@ resource "aws_security_group" "web" { ` jsonNested = `{ + "variable": { + "port": { "type": "number" } + }, "resource": { "aws_s3_bucket": { "logs": { @@ -48,7 +55,7 @@ resource "aws_security_group" "web" { "name": "web", "ingress": [ { - "from_port": 80, + "from_port": "${var.port}", "to_port": 80, "protocol": "tcp", "cidr_blocks": ["0.0.0.0/0"] @@ -120,8 +127,79 @@ func TestUnflattenBlocksIgnoresScalars(t *testing.T) { "bucket": {Kind: ir.KindString, Literal: "logs"}, }, map[string]mappings.BlockMap{"versioning": {Property: "versioned"}}, + nil, + ) + if len(blocks) != 0 || len(consumed) != 0 { + t.Fatalf("blocks=%v consumed=%v, want nothing", blocks, consumed) + } +} + +func TestUnflattenBlocksConsumesEmptyArray(t *testing.T) { + // "ingress": [] means there are no ingress blocks, which is what native HCL + // with no ingress block means. It must not fall through as a property. + blocks, consumed := emitters.UnflattenBlocks( + map[string]ir.Value{"ingress": {Kind: ir.KindList}}, + map[string]mappings.BlockMap{"ingress": {Property: "ingress", Shape: "array"}}, + nil, + ) + if len(blocks) != 0 { + t.Fatalf("blocks=%v, want none", blocks) + } + if !consumed["ingress"] { + t.Fatalf("consumed=%v, want ingress consumed", consumed) + } +} + +func TestUnflattenBlocksLeavesNativeBlocksAlone(t *testing.T) { + // An attribute that duplicates a native block is invalid Terraform. It must + // stay an attribute so the emitter reports it, not render a second block. + blocks, consumed := emitters.UnflattenBlocks( + map[string]ir.Value{"ingress": {Kind: ir.KindMap, Fields: map[string]ir.Value{ + "from_port": {Kind: ir.KindNumber, Literal: 80}, + }}}, + map[string]mappings.BlockMap{"ingress": {Property: "ingress", Shape: "array"}}, + []ir.Block{{Type: "ingress"}}, ) if len(blocks) != 0 || len(consumed) != 0 { t.Fatalf("blocks=%v consumed=%v, want nothing", blocks, consumed) } } + +func TestJSONEmptyBlockArrayMatchesNativeOutput(t *testing.T) { + native := emitBoth(t, parseSource(t, ` +resource "aws_security_group" "web" { + name = "web" +} +`, "main.tf")) + jsonSyntax := emitBoth(t, parseSource(t, `{ + "resource": { + "aws_security_group": { + "web": { + "name": "web", + "ingress": [] + } + } + } +}`, "main.tf.json")) + + for target := range native { + nativeFiles := native[target].Files + jsonFiles := jsonSyntax[target].Files + if len(nativeFiles) != len(jsonFiles) { + t.Fatalf("%s: files = %d vs %d", target, len(nativeFiles), len(jsonFiles)) + } + for i := range nativeFiles { + want := nativeFiles[i].Content + got := strings.ReplaceAll(jsonFiles[i].Content, "main.tf.json", "main.tf") + if got != want { + t.Errorf("%s: %s differs with an empty block array\n--- native\n%s\n--- json\n%s", + target, nativeFiles[i].Path, want, got) + } + } + for _, warning := range jsonSyntax[target].Warnings { + if strings.Contains(warning, "ingress") { + t.Errorf("%s: empty ingress array reported as unconverted: %s", target, warning) + } + } + } +} diff --git a/pkg/emitters/pulumi/emitter.go b/pkg/emitters/pulumi/emitter.go index b2cc006..64f4938 100644 --- a/pkg/emitters/pulumi/emitter.go +++ b/pkg/emitters/pulumi/emitter.go @@ -222,7 +222,7 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.PulumiMa if mapping != nil { schema = mapping.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema) + flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) blocks := resource.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) @@ -311,7 +311,7 @@ func (r *run) renderBlockObject(block ir.Block, blockMap *mappings.BlockMap, rew if blockMap != nil { schema = blockMap.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, schema) + flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, schema, block.Blocks) blocks := block.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) diff --git a/pkg/parsers/hcl/json.go b/pkg/parsers/hcl/json.go index 29cfcc4..63d5831 100644 --- a/pkg/parsers/hcl/json.go +++ b/pkg/parsers/hcl/json.go @@ -5,6 +5,7 @@ import ( "strings" "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/zclconf/go-cty/cty" "github.com/be-thomas/openiac/pkg/ir" @@ -39,6 +40,18 @@ func parseJSONExpr(expr hcl.Expression, src []byte) ir.Value { if value, ok := literalValue(expr); ok { text, isString := value.Literal.(string) if value.Kind == ir.KindString && isString && isTemplateText(text) { + if inner, ok := singleInterpolation(text); ok { + // Terraform evaluates "${expr}" to the expression's own value + // and type, so keep the bare expression: this renders exactly + // like the native HCL form instead of wrapping it in a string + // template. + return ir.Value{ + Kind: ir.KindExpr, + Expr: inner, + Raw: inner, + Refs: collectRefs(expr), + } + } // Rendering the decoded text back as an HCL template keeps the // emitters' existing template handling working unchanged. quoted := hclQuoteTemplate(text) @@ -107,6 +120,31 @@ func isTemplateText(s string) bool { return strings.Contains(s, "${") || strings.Contains(s, "%{") } +// singleInterpolation returns the HCL source of the expression inside a JSON +// string that is nothing but one interpolation, for example "${var.port}". +// +// Terraform evaluates such a string to the wrapped expression's value and +// type, not to a string, so it must be kept as the bare expression. Only a +// string that cannot be recognised as a single interpolation falls back to the +// general template handling. +func singleInterpolation(s string) (string, bool) { + if !strings.HasPrefix(s, "${") || !strings.HasSuffix(s, "}") { + return "", false + } + parsed, diags := hclsyntax.ParseTemplate([]byte(s), "json", hcl.Pos{Line: 1, Column: 1}) + if diags.HasErrors() { + return "", false + } + if _, ok := parsed.(*hclsyntax.TemplateWrapExpr); !ok { + return "", false + } + inner := strings.TrimSpace(s[2 : len(s)-1]) + if inner == "" { + return "", false + } + return inner, true +} + // hclQuoteTemplate renders text as an HCL quoted template. // // strconv.Quote cannot be used: HCL does not accept every JSON escape, and the diff --git a/pkg/parsers/hcl/json_test.go b/pkg/parsers/hcl/json_test.go index b6e6360..133f709 100644 --- a/pkg/parsers/hcl/json_test.go +++ b/pkg/parsers/hcl/json_test.go @@ -143,11 +143,20 @@ func TestJSONInterpolationBecomesExpression(t *testing.T) { if !contains(env.Refs, "var.environment") { t.Errorf("refs = %v, want var.environment", env.Refs) } - if !strings.Contains(env.Expr, "var.environment") { - t.Errorf("expr = %q, want a template with var.environment", env.Expr) + // "${var.environment}" is one interpolation and nothing else, so Terraform + // evaluates it to the expression's value and type. It must not become a + // string template. + if env.Expr != "var.environment" { + t.Errorf("expr = %q, want the bare expression var.environment", env.Expr) } - if !strings.HasPrefix(env.Expr, `"`) { - t.Errorf("expr = %q, want an HCL quoted template", env.Expr) + + // Text around an interpolation is a real template and stays quoted. + name := tags.Fields["Name"] + if name.Kind != ir.KindExpr { + t.Fatalf("tags.Name kind = %q, want expr", name.Kind) + } + if !strings.HasPrefix(name.Expr, `"`) || !strings.Contains(name.Expr, "var.environment") { + t.Errorf("expr = %q, want an HCL quoted template", name.Expr) } } From 71fcbd31333898c5ed876a8c1941af563ddce880 Mon Sep 17 00:00:00 2001 From: Thomas Sudeep Benardo <36351384+be-thomas@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:32:36 +0530 Subject: [PATCH 4/4] Warn about duplicate block attributes, document empty block lists A body that gives the same name as both a block and an attribute is invalid Terraform. UnflattenBlocks now consumes the attribute instead of leaving it for the emitter to render, so Pulumi no longer emits a duplicate object key, and reports the name so both emitters warn about it. An empty array for a block type means the block is absent in either syntax. That rule now applies to native HCL as well, since the IR cannot tell a native attribute from a recovered JSON one, and it is documented alongside the JSON block recovery. --- docs/IR.md | 3 +- docs/TERRAFORM-VERSIONS.md | 4 +- pkg/emitters/awscdk/emitter.go | 10 +++- pkg/emitters/blocks.go | 35 +++++++----- pkg/emitters/json_parity_test.go | 97 ++++++++++++++++++++++++++++---- pkg/emitters/pulumi/emitter.go | 10 +++- 6 files changed, 129 insertions(+), 30 deletions(-) diff --git a/docs/IR.md b/docs/IR.md index e8a0eb2..28715ad 100644 --- a/docs/IR.md +++ b/docs/IR.md @@ -433,7 +433,8 @@ kind must treat it as "cannot convert" and warn, never as a literal. - **JSON bodies are flat below the top level.** HCL exposes no block structure in a `.tf.json` body, so a nested block arrives as a `map` value. An emitter that knows its block schema recovers the native shape with - `emitters.UnflattenBlocks`; otherwise the value stays flat. This is documented + `emitters.UnflattenBlocks`; otherwise the value stays flat. An empty array for + a block type means the block is absent, in either syntax. This is documented rather than guessed. - **`line` is informational.** It is not stable across reformatting and must not be used for identity. diff --git a/docs/TERRAFORM-VERSIONS.md b/docs/TERRAFORM-VERSIONS.md index 0d5c6af..ae4b360 100644 --- a/docs/TERRAFORM-VERSIONS.md +++ b/docs/TERRAFORM-VERSIONS.md @@ -193,7 +193,9 @@ Two differences matter to consumers: `Block`. `lifecycle`, `default_tags`, `provisioner` and friends therefore appear in `attributes`, not `blocks`. An emitter that knows its schema calls `emitters.UnflattenBlocks` to recover them, so both syntaxes produce the same - TypeScript; a block type no mapping declares stays a flat value. + TypeScript; a block type no mapping declares stays a flat value. An empty + array for a block type means the block is absent, in either syntax, so + `"ingress": []` and `ingress = []` both convert to no ingress rules. Expressions keep working: a JSON string containing `${β¦}` or `%{β¦}` becomes an `expr` value with its references collected. A string that is exactly one diff --git a/pkg/emitters/awscdk/emitter.go b/pkg/emitters/awscdk/emitter.go index ced56b6..5b21904 100644 --- a/pkg/emitters/awscdk/emitter.go +++ b/pkg/emitters/awscdk/emitter.go @@ -210,11 +210,14 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.CDKMappi if mapping != nil { schema = mapping.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) + flatBlocks, consumed, conflicts := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) blocks := resource.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) } + for _, name := range conflicts { + r.warnings.Addf("%s: %s is given as both a block and an attribute; the attribute is ignored", resource.ID, name) + } names := sortedKeys(resource.Attributes) for _, name := range names { @@ -290,11 +293,14 @@ func (r *run) renderBlockGroup(blocks []ir.Block, blockMap mappings.BlockMap, re func (r *run) renderBlockObject(block ir.Block, blockMap mappings.BlockMap, rewriter *emitutil.RefRewriter, context string) (string, bool) { var parts []string - flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, blockMap.Blocks, block.Blocks) + flatBlocks, consumed, conflicts := emitters.UnflattenBlocks(block.Attributes, blockMap.Blocks, block.Blocks) blocks := block.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) } + for _, name := range conflicts { + r.warnings.Addf("%s: %s is given as both a block and an attribute; the attribute is ignored", context, name) + } for _, name := range sortedKeys(block.Attributes) { if consumed[name] { diff --git a/pkg/emitters/blocks.go b/pkg/emitters/blocks.go index 7c2d55c..92f31b3 100644 --- a/pkg/emitters/blocks.go +++ b/pkg/emitters/blocks.go @@ -7,7 +7,7 @@ import ( "github.com/be-thomas/openiac/pkg/mappings" ) -// UnflattenBlocks recovers nested blocks from a flat .tf.json body. +// UnflattenBlocks recovers nested blocks from a flat body. // // Terraform's JSON syntax has no way to spell a nested block below the top // level, so the parser leaves e.g. "versioning": {"enabled": true} as a map @@ -16,17 +16,20 @@ import ( // is converted back into the blocks HCL would have produced, and reported in // consumed so the caller does not also render it as a property. // -// existing lists the blocks the caller already has. A type that is present -// there is left alone, so an attribute that duplicates a native block is still -// reported as an unsupported property rather than rendered a second time. +// An empty array counts as a block shape: it means the block is absent, which +// is what native HCL with no such block means. Values that do not fit a block +// shape (a scalar, a list holding a scalar) are left alone. // -// Values that do not fit a block shape (a scalar, a list holding a scalar) are -// left alone. An empty array counts as a block shape: it means the block is -// absent, which is what native HCL with no such block means. Blocks are -// returned in sorted attribute-name order so output stays deterministic. -func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.BlockMap, existing []ir.Block) (blocks []ir.Block, consumed map[string]bool) { +// existing lists the blocks the caller already has. A type that also appears +// there is ambiguous, because Terraform does not allow a block and an argument +// of the same name. The attribute is consumed so it cannot be rendered twice, +// and the name is returned in conflicts so the caller can warn about it. +// +// Blocks are returned in sorted attribute-name order so output stays +// deterministic. +func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.BlockMap, existing []ir.Block) (blocks []ir.Block, consumed map[string]bool, conflicts []string) { if len(attrs) == 0 || len(schema) == 0 { - return nil, nil + return nil, nil, nil } native := make(map[string]bool, len(existing)) @@ -36,21 +39,25 @@ func UnflattenBlocks(attrs map[string]ir.Value, schema map[string]mappings.Block names := make([]string, 0, len(attrs)) for name, value := range attrs { - if _, ok := schema[name]; ok && !native[name] && blockShape(value) { + if _, ok := schema[name]; ok && blockShape(value) { names = append(names, name) } } if len(names) == 0 { - return nil, nil + return nil, nil, nil } sort.Strings(names) consumed = make(map[string]bool, len(names)) for _, name := range names { consumed[name] = true + if native[name] { + conflicts = append(conflicts, name) + continue + } blocks = append(blocks, blocksFromValue(name, attrs[name], schema[name])...) } - return blocks, consumed + return blocks, consumed, conflicts } // blockShape reports whether a flat JSON value has the shape of nested blocks: @@ -102,7 +109,7 @@ func blockFromMap(typ string, v ir.Value, blockMap mappings.BlockMap) (ir.Block, } if len(blockMap.Blocks) > 0 { - nested, consumed := UnflattenBlocks(block.Attributes, blockMap.Blocks, nil) + nested, consumed, _ := UnflattenBlocks(block.Attributes, blockMap.Blocks, nil) for name := range consumed { delete(block.Attributes, name) } diff --git a/pkg/emitters/json_parity_test.go b/pkg/emitters/json_parity_test.go index 968f2ac..7dd4bbe 100644 --- a/pkg/emitters/json_parity_test.go +++ b/pkg/emitters/json_parity_test.go @@ -121,7 +121,7 @@ func TestJSONNestedBlocksDoNotWarn(t *testing.T) { } func TestUnflattenBlocksIgnoresScalars(t *testing.T) { - blocks, consumed := emitters.UnflattenBlocks( + blocks, consumed, conflicts := emitters.UnflattenBlocks( map[string]ir.Value{ "versioning": {Kind: ir.KindBool, Literal: true}, "bucket": {Kind: ir.KindString, Literal: "logs"}, @@ -129,15 +129,15 @@ func TestUnflattenBlocksIgnoresScalars(t *testing.T) { map[string]mappings.BlockMap{"versioning": {Property: "versioned"}}, nil, ) - if len(blocks) != 0 || len(consumed) != 0 { - t.Fatalf("blocks=%v consumed=%v, want nothing", blocks, consumed) + if len(blocks) != 0 || len(consumed) != 0 || len(conflicts) != 0 { + t.Fatalf("blocks=%v consumed=%v conflicts=%v, want nothing", blocks, consumed, conflicts) } } func TestUnflattenBlocksConsumesEmptyArray(t *testing.T) { // "ingress": [] means there are no ingress blocks, which is what native HCL // with no ingress block means. It must not fall through as a property. - blocks, consumed := emitters.UnflattenBlocks( + blocks, consumed, _ := emitters.UnflattenBlocks( map[string]ir.Value{"ingress": {Kind: ir.KindList}}, map[string]mappings.BlockMap{"ingress": {Property: "ingress", Shape: "array"}}, nil, @@ -150,18 +150,95 @@ func TestUnflattenBlocksConsumesEmptyArray(t *testing.T) { } } -func TestUnflattenBlocksLeavesNativeBlocksAlone(t *testing.T) { - // An attribute that duplicates a native block is invalid Terraform. It must - // stay an attribute so the emitter reports it, not render a second block. - blocks, consumed := emitters.UnflattenBlocks( +func TestUnflattenBlocksReportsDuplicateAttribute(t *testing.T) { + // An attribute that duplicates a native block is invalid Terraform. The + // attribute must be consumed, or two blocks are rendered, and reported so + // the emitter can warn about it. + blocks, consumed, conflicts := emitters.UnflattenBlocks( map[string]ir.Value{"ingress": {Kind: ir.KindMap, Fields: map[string]ir.Value{ "from_port": {Kind: ir.KindNumber, Literal: 80}, }}}, map[string]mappings.BlockMap{"ingress": {Property: "ingress", Shape: "array"}}, []ir.Block{{Type: "ingress"}}, ) - if len(blocks) != 0 || len(consumed) != 0 { - t.Fatalf("blocks=%v consumed=%v, want nothing", blocks, consumed) + if len(blocks) != 0 { + t.Fatalf("blocks=%v, want none", blocks) + } + if !consumed["ingress"] { + t.Fatalf("consumed=%v, want ingress consumed", consumed) + } + if len(conflicts) != 1 || conflicts[0] != "ingress" { + t.Fatalf("conflicts=%v, want [ingress]", conflicts) + } +} + +// A body that carries both a block and an attribute of the same name is +// invalid Terraform, but it must never produce duplicate object keys or two +// blocks; the attribute is dropped and the conflict is reported. +func TestDuplicateBlockAndAttributeWarnsAndEmitsOnce(t *testing.T) { + graph := parseSource(t, ` +resource "aws_security_group" "web" { + name = "web" + ingress { + from_port = 80 + to_port = 80 + protocol = "tcp" + } + ingress = [{ + from_port = 443 + to_port = 443 + protocol = "tcp" + }] +} +`, "main.tf") + + for target, result := range emitBoth(t, graph) { + content := result.Files[0].Content + key := "ingress:" + if target == "cdk" { + key = "SecurityGroupIngress: [" + } + if got := strings.Count(content, key); got != 1 { + t.Errorf("%s: %q appears %d times, want once\n%s", target, key, got, content) + } + if strings.Contains(content, "443") { + t.Errorf("%s: duplicate attribute rendered\n%s", target, content) + } + warned := false + for _, warning := range result.Warnings { + if strings.Contains(warning, "both a block and an attribute") { + warned = true + } + } + if !warned { + t.Errorf("%s: no conflict warning; warnings=%v", target, result.Warnings) + } + } +} + +// An empty block list means the block is absent, whichever syntax spells it. +// The IR cannot tell a native attribute from a recovered JSON one, so the rule +// applies to both and native HCL with "ingress = []" matches native HCL with +// no ingress block. +func TestEmptyBlockArrayIsAbsentInNativeHCL(t *testing.T) { + absent := emitBoth(t, parseSource(t, ` +resource "aws_security_group" "web" { + name = "web" +} +`, "main.tf")) + empty := emitBoth(t, parseSource(t, ` +resource "aws_security_group" "web" { + name = "web" + ingress = [] +} +`, "main.tf")) + + for target := range absent { + want := absent[target].Files[0].Content + got := empty[target].Files[0].Content + if got != want { + t.Errorf("%s: ingress = [] differs from no ingress block\n--- absent\n%s\n--- empty\n%s", target, want, got) + } } } diff --git a/pkg/emitters/pulumi/emitter.go b/pkg/emitters/pulumi/emitter.go index 64f4938..9225b66 100644 --- a/pkg/emitters/pulumi/emitter.go +++ b/pkg/emitters/pulumi/emitter.go @@ -222,11 +222,14 @@ func (r *run) renderProperties(resource *ir.Resource, mapping *mappings.PulumiMa if mapping != nil { schema = mapping.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) + flatBlocks, consumed, conflicts := emitters.UnflattenBlocks(resource.Attributes, schema, resource.Blocks) blocks := resource.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), resource.Blocks...), flatBlocks...) } + for _, name := range conflicts { + r.warnings.Addf("%s: %s is given as both a block and an attribute; the attribute is ignored", resource.ID, name) + } for _, name := range sortedKeys(resource.Attributes) { if consumed[name] { @@ -311,11 +314,14 @@ func (r *run) renderBlockObject(block ir.Block, blockMap *mappings.BlockMap, rew if blockMap != nil { schema = blockMap.Blocks } - flatBlocks, consumed := emitters.UnflattenBlocks(block.Attributes, schema, block.Blocks) + flatBlocks, consumed, conflicts := emitters.UnflattenBlocks(block.Attributes, schema, block.Blocks) blocks := block.Blocks if len(flatBlocks) > 0 { blocks = append(append([]ir.Block(nil), block.Blocks...), flatBlocks...) } + for _, name := range conflicts { + r.warnings.Addf("%s: %s is given as both a block and an attribute; the attribute is ignored", context, name) + } for _, name := range sortedKeys(block.Attributes) { if consumed[name] {