pax_global_header00006660000000000000000000000064151163615700014517gustar00rootroot0000000000000052 comment=dc8fb47b458aa3084210b21174d1688f63b0abf5 hashicorp-go-cty-funcs-dc8fb47/000077500000000000000000000000001511636157000165165ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/.github/000077500000000000000000000000001511636157000200565ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/.github/dependabot.yml000066400000000000000000000003201511636157000227010ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" - package-ecosystem: "gomod" directory: "/" schedule: interval: "weekly" hashicorp-go-cty-funcs-dc8fb47/.github/pull_request_template.md000066400000000000000000000004651511636157000250240ustar00rootroot00000000000000 - [ ] If a change needs to be reverted, we will roll out an update to the code within 7 days. ## Changes to Security Controls Are there any changes to security controls (access controls, encryption, logging) in this pull request? If so, explain. hashicorp-go-cty-funcs-dc8fb47/.github/workflows/000077500000000000000000000000001511636157000221135ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/.github/workflows/actionlint.yml000066400000000000000000000005651511636157000250100ustar00rootroot00000000000000name: Lint GitHub Actions Workflows on: push: permissions: contents: read jobs: actionlint: runs-on: ubuntu-latest steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - name: "Check workflow files" uses: docker://docker.mirror.hashicorp.services/rhysd/actionlint:latest with: args: -color hashicorp-go-cty-funcs-dc8fb47/.github/workflows/check-code.yml000066400000000000000000000006151511636157000246250ustar00rootroot00000000000000name: Check Code on: push: permissions: contents: read jobs: check-fmt: runs-on: ubuntu-latest steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 with: go-version-file: go.mod - run: | go fmt ./... git diff --exit-code hashicorp-go-cty-funcs-dc8fb47/.github/workflows/test.yml000066400000000000000000000015271511636157000236220ustar00rootroot00000000000000name: Go Tests on: push: permissions: contents: read jobs: define-runners: runs-on: ubuntu-latest outputs: runners: '{"linux":"ubuntu-latest", "macos":"macos-latest", "windows":"windows-latest"}' steps: - run: true # no-op test: needs: [define-runners] strategy: matrix: go-version: - '1.24' # oldest supported; named in go.mod - 'oldstable' - 'stable' os: - 'linux' - 'macos' - 'windows' runs-on: ${{ fromJSON(needs.define-runners.outputs.runners)[ matrix.os ] }} steps: - uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1 - uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 with: go-version: ${{ matrix.go-version }} - run: go test ./... hashicorp-go-cty-funcs-dc8fb47/.test.sh000077500000000000000000000004251511636157000201130ustar00rootroot00000000000000# Copyright IBM Corp. 2020, 2025 # SPDX-License-Identifier: MPL-2.0 set -e clear go fmt ./... goimports -w */*.go for f in */ do pushd $f > /dev/null go mod tidy go test . popd > /dev/null done git diff --exit-code --ignore-space-change --ignore-space-at-eol hashicorp-go-cty-funcs-dc8fb47/CODEOWNERS000066400000000000000000000001451511636157000201110ustar00rootroot00000000000000# codeowner default * @hashicorp/github-nomad-core @hashicorp/nomad-eng hashicorp-go-cty-funcs-dc8fb47/LICENSE000066400000000000000000000372111511636157000175270ustar00rootroot00000000000000Copyright IBM Corp. 2020, 2025 Mozilla Public License, version 2.0 1. Definitions 1.1. “Contributor” means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. “Contributor Version” means the combination of the Contributions of others (if any) used by a Contributor and that particular Contributor’s Contribution. 1.3. “Contribution” means Covered Software of a particular Contributor. 1.4. “Covered Software” means Source Code Form to which the initial Contributor has attached the notice in Exhibit A, the Executable Form of such Source Code Form, and Modifications of such Source Code Form, in each case including portions thereof. 1.5. “Incompatible With Secondary Licenses” means a. that the initial Contributor has attached the notice described in Exhibit B to the Covered Software; or b. that the Covered Software was made available under the terms of version 1.1 or earlier of the License, but not also under the terms of a Secondary License. 1.6. “Executable Form” means any form of the work other than Source Code Form. 1.7. “Larger Work” means a work that combines Covered Software with other material, in a separate file or files, that is not Covered Software. 1.8. “License” means this document. 1.9. “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently, any and all of the rights conveyed by this License. 1.10. “Modifications” means any of the following: a. any file in Source Code Form that results from an addition to, deletion from, or modification of the contents of Covered Software; or b. any new file in Source Code Form that contains any Covered Software. 1.11. “Patent Claims” of a Contributor means any patent claim(s), including without limitation, method, process, and apparatus claims, in any patent Licensable by such Contributor that would be infringed, but for the grant of the License, by the making, using, selling, offering for sale, having made, import, or transfer of either its Contributions or its Contributor Version. 1.12. “Secondary License” means either the GNU General Public License, Version 2.0, the GNU Lesser General Public License, Version 2.1, the GNU Affero General Public License, Version 3.0, or any later versions of those licenses. 1.13. “Source Code Form” means the form of the work preferred for making modifications. 1.14. “You” (or “Your”) means an individual or a legal entity exercising rights under this License. For legal entities, “You” includes any entity that controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. 2. License Grants and Conditions 2.1. Grants Each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: a. under intellectual property rights (other than patent or trademark) Licensable by such Contributor to use, reproduce, make available, modify, display, perform, distribute, and otherwise exploit its Contributions, either on an unmodified basis, with Modifications, or as part of a Larger Work; and b. under Patent Claims of such Contributor to make, use, sell, offer for sale, have made, import, and otherwise transfer either its Contributions or its Contributor Version. 2.2. Effective Date The licenses granted in Section 2.1 with respect to any Contribution become effective for each Contribution on the date the Contributor first distributes such Contribution. 2.3. Limitations on Grant Scope The licenses granted in this Section 2 are the only rights granted under this License. No additional rights or licenses will be implied from the distribution or licensing of Covered Software under this License. Notwithstanding Section 2.1(b) above, no patent license is granted by a Contributor: a. for any code that a Contributor has removed from Covered Software; or b. for infringements caused by: (i) Your and any other third party’s modifications of Covered Software, or (ii) the combination of its Contributions with other software (except as part of its Contributor Version); or c. under Patent Claims infringed by Covered Software in the absence of its Contributions. This License does not grant any rights in the trademarks, service marks, or logos of any Contributor (except as may be necessary to comply with the notice requirements in Section 3.4). 2.4. Subsequent Licenses No Contributor makes additional grants as a result of Your choice to distribute the Covered Software under a subsequent version of this License (see Section 10.2) or under the terms of a Secondary License (if permitted under the terms of Section 3.3). 2.5. Representation Each Contributor represents that the Contributor believes its Contributions are its original creation(s) or it has sufficient rights to grant the rights to its Contributions conveyed by this License. 2.6. Fair Use This License is not intended to limit any rights You have under applicable copyright doctrines of fair use, fair dealing, or other equivalents. 2.7. Conditions Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in Section 2.1. 3. Responsibilities 3.1. Distribution of Source Form All distribution of Covered Software in Source Code Form, including any Modifications that You create or to which You contribute, must be under the terms of this License. You must inform recipients that the Source Code Form of the Covered Software is governed by the terms of this License, and how they can obtain a copy of this License. You may not attempt to alter or restrict the recipients’ rights in the Source Code Form. 3.2. Distribution of Executable Form If You distribute Covered Software in Executable Form then: a. such Covered Software must also be made available in Source Code Form, as described in Section 3.1, and You must inform recipients of the Executable Form how they can obtain a copy of such Source Code Form by reasonable means in a timely manner, at a charge no more than the cost of distribution to the recipient; and b. You may distribute such Executable Form under the terms of this License, or sublicense it under different terms, provided that the license for the Executable Form does not attempt to limit or alter the recipients’ rights in the Source Code Form under this License. 3.3. Distribution of a Larger Work You may create and distribute a Larger Work under terms of Your choice, provided that You also comply with the requirements of this License for the Covered Software. If the Larger Work is a combination of Covered Software with a work governed by one or more Secondary Licenses, and the Covered Software is not Incompatible With Secondary Licenses, this License permits You to additionally distribute such Covered Software under the terms of such Secondary License(s), so that the recipient of the Larger Work may, at their option, further distribute the Covered Software under the terms of either this License or such Secondary License(s). 3.4. Notices You may not remove or alter the substance of any license notices (including copyright notices, patent notices, disclaimers of warranty, or limitations of liability) contained within the Source Code Form of the Covered Software, except that You may alter any license notices to the extent required to remedy known factual inaccuracies. 3.5. Application of Additional Terms You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, You may do so only on Your own behalf, and not on behalf of any Contributor. You must make it absolutely clear that any such warranty, support, indemnity, or liability obligation is offered by You alone, and You hereby agree to indemnify every Contributor for any liability incurred by such Contributor as a result of warranty, support, indemnity or liability terms You offer. You may include additional disclaimers of warranty and limitations of liability specific to any jurisdiction. 4. Inability to Comply Due to Statute or Regulation If it is impossible for You to comply with any of the terms of this License with respect to some or all of the Covered Software due to statute, judicial order, or regulation then You must: (a) comply with the terms of this License to the maximum extent possible; and (b) describe the limitations and the code they affect. Such description must be placed in a text file included with all distributions of the Covered Software under this License. Except to the extent prohibited by statute or regulation, such description must be sufficiently detailed for a recipient of ordinary skill to be able to understand it. 5. Termination 5.1. The rights granted under this License will terminate automatically if You fail to comply with any of its terms. However, if You become compliant, then the rights granted under this License from a particular Contributor are reinstated (a) provisionally, unless and until such Contributor explicitly and finally terminates Your grants, and (b) on an ongoing basis, if such Contributor fails to notify You of the non-compliance by some reasonable means prior to 60 days after You have come back into compliance. Moreover, Your grants from a particular Contributor are reinstated on an ongoing basis if such Contributor notifies You of the non-compliance by some reasonable means, this is the first time You have received notice of non-compliance with this License from such Contributor, and You become compliant prior to 30 days after Your receipt of the notice. 5.2. If You initiate litigation against any entity by asserting a patent infringement claim (excluding declaratory judgment actions, counter-claims, and cross-claims) alleging that a Contributor Version directly or indirectly infringes any patent, then the rights granted to You by any and all Contributors for the Covered Software under Section 2.1 of this License shall terminate. 5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user license agreements (excluding distributors and resellers) which have been validly granted by You or Your distributors under this License prior to termination shall survive termination. 6. Disclaimer of Warranty Covered Software is provided under this License on an “as is” basis, without warranty of any kind, either expressed, implied, or statutory, including, without limitation, warranties that the Covered Software is free of defects, merchantable, fit for a particular purpose or non-infringing. The entire risk as to the quality and performance of the Covered Software is with You. Should any Covered Software prove defective in any respect, You (not any Contributor) assume the cost of any necessary servicing, repair, or correction. This disclaimer of warranty constitutes an essential part of this License. No use of any Covered Software is authorized under this License except under this disclaimer. 7. Limitation of Liability Under no circumstances and under no legal theory, whether tort (including negligence), contract, or otherwise, shall any Contributor, or anyone who distributes Covered Software as permitted above, be liable to You for any direct, indirect, special, incidental, or consequential damages of any character including, without limitation, damages for lost profits, loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses, even if such party shall have been informed of the possibility of such damages. This limitation of liability shall not apply to liability for death or personal injury resulting from such party’s negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You. 8. Litigation Any litigation relating to this License may be brought only in the courts of a jurisdiction where the defendant maintains its principal place of business and such litigation shall be governed by laws of that jurisdiction, without reference to its conflict-of-law provisions. Nothing in this Section shall prevent a party’s ability to bring cross-claims or counter-claims. 9. Miscellaneous This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not be used to construe this License against a Contributor. 10. Versions of the License 10.1. New Versions Mozilla Foundation is the license steward. Except as provided in Section 10.3, no one other than the license steward has the right to modify or publish new versions of this License. Each version will be given a distinguishing version number. 10.2. Effect of New Versions You may distribute the Covered Software under the terms of the version of the License under which You originally received the Covered Software, or under the terms of any subsequent version published by the license steward. 10.3. Modified Versions If you create software not governed by this License, and you want to create a new license for such software, you may create and use a modified version of this License if you rename the license and remove any references to the name of the license steward (except to note that such modified license differs from this License). 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses If You choose to distribute Source Code Form that is Incompatible With Secondary Licenses under the terms of this version of the License, the notice described in Exhibit B of this License must be attached. Exhibit A - Source Code Form License Notice This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. If it is not possible or desirable to put the notice in a particular file, then You may include the notice in a location (such as a LICENSE file in a relevant directory) where a recipient would be likely to look for such a notice. You may add additional accurate notices of copyright ownership. Exhibit B - “Incompatible With Secondary Licenses” Notice This Source Code Form is “Incompatible With Secondary Licenses”, as defined by the Mozilla Public License, v. 2.0. hashicorp-go-cty-funcs-dc8fb47/README.md000066400000000000000000000000011511636157000177640ustar00rootroot00000000000000 hashicorp-go-cty-funcs-dc8fb47/cidr/000077500000000000000000000000001511636157000174375ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/cidr/host.go000066400000000000000000000024511511636157000207450ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "net" "github.com/apparentlymart/go-cidr/cidr" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" "github.com/zclconf/go-cty/cty/gocty" ) // HostFunc is a function that calculates a full host IP address within a given // IP network address prefix. var HostFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, { Name: "hostnum", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var hostNum int if err := gocty.FromCtyValue(args[1], &hostNum); err != nil { return cty.UnknownVal(cty.String), err } _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } ip, err := cidr.Host(network, hostNum) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(ip.String()), nil }, }) // Host calculates a full host IP address within a given IP network address prefix. func Host(prefix, hostnum cty.Value) (cty.Value, error) { return HostFunc.Call([]cty.Value{prefix, hostnum}) } hashicorp-go-cty-funcs-dc8fb47/cidr/host_test.go000066400000000000000000000031321511636157000220010ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestHost(t *testing.T) { tests := []struct { Prefix cty.Value Hostnum cty.Value Want cty.Value Err bool }{ { cty.StringVal("192.168.1.0/24"), cty.NumberIntVal(5), cty.StringVal("192.168.1.5"), false, }, { cty.StringVal("192.168.1.0/24"), cty.NumberIntVal(-5), cty.StringVal("192.168.1.251"), false, }, { cty.StringVal("192.168.1.0/24"), cty.NumberIntVal(-256), cty.StringVal("192.168.1.0"), false, }, { cty.StringVal("192.168.1.0/30"), cty.NumberIntVal(255), cty.UnknownVal(cty.String), true, // 255 doesn't fit in two bits }, { cty.StringVal("192.168.1.0/30"), cty.NumberIntVal(-255), cty.UnknownVal(cty.String), true, // 255 doesn't fit in two bits }, { cty.StringVal("not-a-cidr"), cty.NumberIntVal(6), cty.UnknownVal(cty.String), true, // not a valid CIDR mask }, { cty.StringVal("10.256.0.0/8"), cty.NumberIntVal(6), cty.UnknownVal(cty.String), true, // can't have an octet >255 }, } for _, test := range tests { t.Run(fmt.Sprintf("cidrhost(%#v, %#v)", test.Prefix, test.Hostnum), func(t *testing.T) { got, err := Host(test.Prefix, test.Hostnum) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/cidr/netmask.go000066400000000000000000000017311511636157000214320ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "net" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) // NetmaskFunc is a function that converts an IPv4 address prefix given in CIDR // notation into a subnet mask address. var NetmaskFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } return cty.StringVal(net.IP(network.Mask).String()), nil }, }) // Netmask converts an IPv4 address prefix given in CIDR notation into a subnet mask address. func Netmask(prefix cty.Value) (cty.Value, error) { return NetmaskFunc.Call([]cty.Value{prefix}) } hashicorp-go-cty-funcs-dc8fb47/cidr/netmask_test.go000066400000000000000000000023501511636157000224670ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestNetmask(t *testing.T) { tests := []struct { Prefix cty.Value Want cty.Value Err bool }{ { cty.StringVal("192.168.1.0/24"), cty.StringVal("255.255.255.0"), false, }, { cty.StringVal("192.168.1.0/32"), cty.StringVal("255.255.255.255"), false, }, { cty.StringVal("0.0.0.0/0"), cty.StringVal("0.0.0.0"), false, }, { cty.StringVal("1::/64"), cty.StringVal("ffff:ffff:ffff:ffff::"), false, }, { cty.StringVal("not-a-cidr"), cty.UnknownVal(cty.String), true, // not a valid CIDR mask }, { cty.StringVal("110.256.0.0/8"), cty.UnknownVal(cty.String), true, // can't have an octet >255 }, } for _, test := range tests { t.Run(fmt.Sprintf("cidrnetmask(%#v)", test.Prefix), func(t *testing.T) { got, err := Netmask(test.Prefix) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/cidr/subnet.go000066400000000000000000000035511511636157000212720ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "net" "github.com/apparentlymart/go-cidr/cidr" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" "github.com/zclconf/go-cty/cty/gocty" ) // SubnetFunc is a function that calculates a subnet address within a given // IP network address prefix. var SubnetFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, { Name: "newbits", Type: cty.Number, }, { Name: "netnum", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var newbits int if err := gocty.FromCtyValue(args[1], &newbits); err != nil { return cty.UnknownVal(cty.String), err } var netnum int if err := gocty.FromCtyValue(args[2], &netnum); err != nil { return cty.UnknownVal(cty.String), err } _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } // For portability with 32-bit systems where the subnet number will be // a 32-bit int, we only allow extension of 32 bits in one call even if // we're running on a 64-bit machine. (Of course, this is significant // only for IPv6.) if newbits > 32 { return cty.UnknownVal(cty.String), fmt.Errorf("may not extend prefix by more than 32 bits") } newNetwork, err := cidr.Subnet(network, newbits, netnum) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(newNetwork.String()), nil }, }) // Subnet calculates a subnet address within a given IP network address prefix. func Subnet(prefix, newbits, netnum cty.Value) (cty.Value, error) { return SubnetFunc.Call([]cty.Value{prefix, newbits, netnum}) } hashicorp-go-cty-funcs-dc8fb47/cidr/subnet_test.go000066400000000000000000000036001511636157000223240ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestSubnet(t *testing.T) { tests := []struct { Prefix cty.Value Newbits cty.Value Netnum cty.Value Want cty.Value Err bool }{ { cty.StringVal("192.168.2.0/20"), cty.NumberIntVal(4), cty.NumberIntVal(6), cty.StringVal("192.168.6.0/24"), false, }, { cty.StringVal("fe80::/48"), cty.NumberIntVal(16), cty.NumberIntVal(6), cty.StringVal("fe80:0:0:6::/64"), false, }, { // IPv4 address encoded in IPv6 syntax gets normalized cty.StringVal("::ffff:192.168.0.0/112"), cty.NumberIntVal(8), cty.NumberIntVal(6), cty.StringVal("192.168.6.0/24"), false, }, { // not enough bits left cty.StringVal("192.168.0.0/30"), cty.NumberIntVal(4), cty.NumberIntVal(6), cty.UnknownVal(cty.String), true, }, { // can't encode 16 in 2 bits cty.StringVal("192.168.0.0/168"), cty.NumberIntVal(2), cty.NumberIntVal(16), cty.StringVal("fe80:0:0:6::/64"), true, }, { // not a valid CIDR mask cty.StringVal("not-a-cidr"), cty.NumberIntVal(4), cty.NumberIntVal(6), cty.StringVal("fe80:0:0:6::/64"), true, }, { // can't have an octet >255 cty.StringVal("10.256.0.0/8"), cty.NumberIntVal(4), cty.NumberIntVal(6), cty.StringVal("fe80:0:0:6::/64"), true, }, } for _, test := range tests { t.Run(fmt.Sprintf("cidrsubnet(%#v, %#v, %#v)", test.Prefix, test.Newbits, test.Netnum), func(t *testing.T) { got, err := Subnet(test.Prefix, test.Newbits, test.Netnum) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/cidr/subnets.go000066400000000000000000000065631511636157000214630ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "net" "github.com/apparentlymart/go-cidr/cidr" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" "github.com/zclconf/go-cty/cty/gocty" ) // SubnetsFunc is similar to SubnetFunc but calculates many consecutive subnet // addresses at once, rather than just a single subnet extension. var SubnetsFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "newbits", Type: cty.Number, }, Type: function.StaticReturnType(cty.List(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), function.NewArgErrorf(0, "invalid CIDR expression: %s", err) } startPrefixLen, _ := network.Mask.Size() prefixLengthArgs := args[1:] if len(prefixLengthArgs) == 0 { return cty.ListValEmpty(cty.String), nil } var firstLength int if err := gocty.FromCtyValue(prefixLengthArgs[0], &firstLength); err != nil { return cty.UnknownVal(cty.String), function.NewArgError(1, err) } firstLength += startPrefixLen retVals := make([]cty.Value, len(prefixLengthArgs)) current, _ := cidr.PreviousSubnet(network, firstLength) for i, lengthArg := range prefixLengthArgs { var length int if err := gocty.FromCtyValue(lengthArg, &length); err != nil { return cty.UnknownVal(cty.String), function.NewArgError(i+1, err) } if length < 1 { return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "must extend prefix by at least one bit") } // For portability with 32-bit systems where the subnet number // will be a 32-bit int, we only allow extension of 32 bits in // one call even if we're running on a 64-bit machine. // (Of course, this is significant only for IPv6.) if length > 32 { return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "may not extend prefix by more than 32 bits") } length += startPrefixLen if length > (len(network.IP) * 8) { protocol := "IP" switch len(network.IP) * 8 { case 32: protocol = "IPv4" case 128: protocol = "IPv6" } return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "would extend prefix to %d bits, which is too long for an %s address", length, protocol) } next, rollover := cidr.NextSubnet(current, length) if rollover || !network.Contains(next.IP) { // If we run out of suffix bits in the base CIDR prefix then // NextSubnet will start incrementing the prefix bits, which // we don't allow because it would then allocate addresses // outside of the caller's given prefix. return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "not enough remaining address space for a subnet with a prefix of %d bits after %s", length, current.String()) } current = next retVals[i] = cty.StringVal(current.String()) } return cty.ListVal(retVals), nil }, }) // Subnets calculates a sequence of consecutive subnet prefixes that may be of // different prefix lengths under a common base prefix. func Subnets(prefix cty.Value, newbits ...cty.Value) (cty.Value, error) { args := make([]cty.Value, len(newbits)+1) args[0] = prefix copy(args[1:], newbits) return SubnetsFunc.Call(args) } hashicorp-go-cty-funcs-dc8fb47/cidr/subnets_test.go000066400000000000000000000051231511636157000225110ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package cidr import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestSubnets(t *testing.T) { tests := []struct { Prefix cty.Value Newbits []cty.Value Want cty.Value Err string }{ { cty.StringVal("10.0.0.0/21"), []cty.Value{ cty.NumberIntVal(3), cty.NumberIntVal(3), cty.NumberIntVal(3), cty.NumberIntVal(4), cty.NumberIntVal(4), cty.NumberIntVal(4), cty.NumberIntVal(7), cty.NumberIntVal(7), cty.NumberIntVal(7), }, cty.ListVal([]cty.Value{ cty.StringVal("10.0.0.0/24"), cty.StringVal("10.0.1.0/24"), cty.StringVal("10.0.2.0/24"), cty.StringVal("10.0.3.0/25"), cty.StringVal("10.0.3.128/25"), cty.StringVal("10.0.4.0/25"), cty.StringVal("10.0.4.128/28"), cty.StringVal("10.0.4.144/28"), cty.StringVal("10.0.4.160/28"), }), ``, }, { cty.StringVal("10.0.0.0/30"), []cty.Value{ cty.NumberIntVal(1), cty.NumberIntVal(3), }, cty.UnknownVal(cty.List(cty.String)), `would extend prefix to 33 bits, which is too long for an IPv4 address`, }, { cty.StringVal("10.0.0.0/8"), []cty.Value{ cty.NumberIntVal(1), cty.NumberIntVal(1), cty.NumberIntVal(1), }, cty.UnknownVal(cty.List(cty.String)), `not enough remaining address space for a subnet with a prefix of 9 bits after 10.128.0.0/9`, }, { cty.StringVal("10.0.0.0/8"), []cty.Value{ cty.NumberIntVal(1), cty.NumberIntVal(0), }, cty.UnknownVal(cty.List(cty.String)), `must extend prefix by at least one bit`, }, { cty.StringVal("10.0.0.0/8"), []cty.Value{ cty.NumberIntVal(1), cty.NumberIntVal(-1), }, cty.UnknownVal(cty.List(cty.String)), `must extend prefix by at least one bit`, }, { cty.StringVal("fe80::/48"), []cty.Value{ cty.NumberIntVal(1), cty.NumberIntVal(33), }, cty.UnknownVal(cty.List(cty.String)), `may not extend prefix by more than 32 bits`, }, } for _, test := range tests { t.Run(fmt.Sprintf("cidrsubnets(%#v, %#v)", test.Prefix, test.Newbits), func(t *testing.T) { got, err := Subnets(test.Prefix, test.Newbits...) wantErr := test.Err != "" if wantErr { if err == nil { t.Fatal("succeeded; want error") } if err.Error() != test.Err { t.Fatalf("wrong error\ngot: %s\nwant: %s", err.Error(), test.Err) } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/collection/000077500000000000000000000000001511636157000206515ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/collection/coalesce.go000066400000000000000000000035151511636157000227620ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package collection import ( "errors" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/convert" "github.com/zclconf/go-cty/cty/function" ) // Coalesce takes any number of arguments and returns the first one that isn't // empty. func Coalesce(args ...cty.Value) (cty.Value, error) { return CoalesceFunc.Call(args) } // CoalesceFunc constructs a function that takes any number of arguments and // returns the first one that isn't empty. This function was copied from go-cty // stdlib and modified so that it returns the first *non-empty* non-null // element from a sequence, instead of merely the first non-null. var CoalesceFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "vals", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { argTypes := make([]cty.Type, len(args)) for i, val := range args { argTypes[i] = val.Type() } retType, _ := convert.UnifyUnsafe(argTypes) if retType == cty.NilType { return cty.NilType, errors.New("all arguments must have the same type") } return retType, nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { for _, argVal := range args { // We already know this will succeed because of the checks in our // Type func above argVal, _ = convert.Convert(argVal, retType) if !argVal.IsKnown() { return cty.UnknownVal(retType), nil } if argVal.IsNull() { continue } if retType == cty.String && argVal.RawEquals(cty.StringVal("")) { continue } return argVal, nil } return cty.NilVal, errors.New("no non-null, non-empty-string arguments") }, }) hashicorp-go-cty-funcs-dc8fb47/collection/coalesce_test.go000066400000000000000000000034771511636157000240300ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package collection import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestCoalesce(t *testing.T) { tests := []struct { Values []cty.Value Want cty.Value Err bool }{ { []cty.Value{cty.StringVal("first"), cty.StringVal("second"), cty.StringVal("third")}, cty.StringVal("first"), false, }, { []cty.Value{cty.StringVal(""), cty.StringVal("second"), cty.StringVal("third")}, cty.StringVal("second"), false, }, { []cty.Value{cty.StringVal(""), cty.StringVal("")}, cty.NilVal, true, }, { []cty.Value{cty.True}, cty.True, false, }, { []cty.Value{cty.NullVal(cty.Bool), cty.True}, cty.True, false, }, { []cty.Value{cty.NullVal(cty.Bool), cty.False}, cty.False, false, }, { []cty.Value{cty.NullVal(cty.Bool), cty.False, cty.StringVal("hello")}, cty.StringVal("false"), false, }, { []cty.Value{cty.True, cty.UnknownVal(cty.Bool)}, cty.True, false, }, { []cty.Value{cty.UnknownVal(cty.Bool), cty.True}, cty.UnknownVal(cty.Bool), false, }, { []cty.Value{cty.UnknownVal(cty.Bool), cty.StringVal("hello")}, cty.UnknownVal(cty.String), false, }, { []cty.Value{cty.DynamicVal, cty.True}, cty.UnknownVal(cty.Bool), false, }, { []cty.Value{cty.DynamicVal}, cty.DynamicVal, false, }, } for _, test := range tests { t.Run(fmt.Sprintf("Coalesce(%#v...)", test.Values), func(t *testing.T) { got, err := Coalesce(test.Values...) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/crypto/000077500000000000000000000000001511636157000200365ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/crypto/bcrypt.go000066400000000000000000000031331511636157000216700ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "fmt" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" "github.com/zclconf/go-cty/cty/gocty" "golang.org/x/crypto/bcrypt" ) // BcryptFunc is a function that computes a hash of the given string using the // Blowfish cipher. var BcryptFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "cost", Type: cty.Number, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { defaultCost := 10 if len(args) > 1 { var val int if err := gocty.FromCtyValue(args[1], &val); err != nil { return cty.UnknownVal(cty.String), err } defaultCost = val } if len(args) > 2 { return cty.UnknownVal(cty.String), fmt.Errorf("bcrypt() takes no more than two arguments") } input := args[0].AsString() out, err := bcrypt.GenerateFromPassword([]byte(input), defaultCost) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("error occured generating password %s", err.Error()) } return cty.StringVal(string(out)), nil }, }) // Bcrypt computes a hash of the given string using the Blowfish cipher, // returning a string in the Modular Crypt Format usually expected in the // shadow password file on many Unix systems. func Bcrypt(str cty.Value, cost ...cty.Value) (cty.Value, error) { args := make([]cty.Value, len(cost)+1) args[0] = str copy(args[1:], cost) return BcryptFunc.Call(args) } hashicorp-go-cty-funcs-dc8fb47/crypto/bcrypt_test.go000066400000000000000000000016731511636157000227360ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "testing" "github.com/zclconf/go-cty/cty" "golang.org/x/crypto/bcrypt" ) func TestBcrypt(t *testing.T) { // single variable test p, err := Bcrypt(cty.StringVal("test")) if err != nil { t.Fatalf("err: %s", err) } err = bcrypt.CompareHashAndPassword([]byte(p.AsString()), []byte("test")) if err != nil { t.Fatalf("Error comparing hash and password: %s", err) } // testing with two parameters p, err = Bcrypt(cty.StringVal("test"), cty.NumberIntVal(5)) if err != nil { t.Fatalf("err: %s", err) } err = bcrypt.CompareHashAndPassword([]byte(p.AsString()), []byte("test")) if err != nil { t.Fatalf("Error comparing hash and password: %s", err) } // Negative test for more than two parameters _, err = Bcrypt(cty.StringVal("test"), cty.NumberIntVal(10), cty.NumberIntVal(11)) if err == nil { t.Fatal("succeeded; want error") } } hashicorp-go-cty-funcs-dc8fb47/crypto/hash.go000066400000000000000000000012211511636157000213040ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "hash" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) func makeStringHashFunction(hf func() hash.Hash, enc func([]byte) string) function.Function { return function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { s := args[0].AsString() h := hf() h.Write([]byte(s)) rv := enc(h.Sum(nil)) return cty.StringVal(rv), nil }, }) } hashicorp-go-cty-funcs-dc8fb47/crypto/hash_test.go000066400000000000000000000074151511636157000223560ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto const ( CipherBase64 = "eczGaDhXDbOFRZGhjx2etVzWbRqWDlmq0bvNt284JHVbwCgObiuyX9uV0LSAMY707IEgMkExJqXmsB4OWKxvB7epRB9G/3+F+pcrQpODlDuL9oDUAsa65zEpYF0Wbn7Oh7nrMQncyUPpyr9WUlALl0gRWytOA23S+y5joa4M34KFpawFgoqTu/2EEH4Xl1zo+0fy73fEto+nfkUY+meuyGZ1nUx/+DljP7ZqxHBFSlLODmtuTMdswUbHbXbWneW51D7Jm7xB8nSdiA2JQNK5+Sg5x8aNfgvFTt/m2w2+qpsyFa5Wjeu6fZmXSl840CA07aXbk9vN4I81WmJyblD/ZA==" PrivateKey = ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAgUElV5mwqkloIrM8ZNZ72gSCcnSJt7+/Usa5G+D15YQUAdf9 c1zEekTfHgDP+04nw/uFNFaE5v1RbHaPxhZYVg5ZErNCa/hzn+x10xzcepeS3KPV Xcxae4MR0BEegvqZqJzN9loXsNL/c3H/B+2Gle3hTxjlWFb3F5qLgR+4Mf4ruhER 1v6eHQa/nchi03MBpT4UeJ7MrL92hTJYLdpSyCqmr8yjxkKJDVC2uRrr+sTSxfh7 r6v24u/vp/QTmBIAlNPgadVAZw17iNNb7vjV7Gwl/5gHXonCUKURaV++dBNLrHIZ pqcAM8wHRph8mD1EfL9hsz77pHewxolBATV+7QIDAQABAoIBAC1rK+kFW3vrAYm3 +8/fQnQQw5nec4o6+crng6JVQXLeH32qXShNf8kLLG/Jj0vaYcTPPDZw9JCKkTMQ 0mKj9XR/5DLbBMsV6eNXXuvJJ3x4iKW5eD9WkLD4FKlNarBRyO7j8sfPTqXW7uat NxWdFH7YsSRvNh/9pyQHLWA5OituidMrYbc3EUx8B1GPNyJ9W8Q8znNYLfwYOjU4 Wv1SLE6qGQQH9Q0WzA2WUf8jklCYyMYTIywAjGb8kbAJlKhmj2t2Igjmqtwt1PYc pGlqbtQBDUiWXt5S4YX/1maIQ/49yeNUajjpbJiH3DbhJbHwFTzP3pZ9P9GHOzlG kYR+wSECgYEAw/Xida8kSv8n86V3qSY/I+fYQ5V+jDtXIE+JhRnS8xzbOzz3v0WS Oo5H+o4nJx5eL3Ghb3Gcm0Jn46dHrxinHbm+3RjXv/X6tlbxIYjRSQfHOTSMCTvd qcliF5vC6RCLXuc7R+IWR1Ky6eDEZGtrvt3DyeYABsp9fRUFR/6NluUCgYEAqNsw 1aSl7WJa27F0DoJdlU9LWerpXcazlJcIdOz/S9QDmSK3RDQTdqfTxRmrxiYI9LEs mkOkvzlnnOBMpnZ3ZOU5qIRfprecRIi37KDAOHWGnlC0EWGgl46YLb7/jXiWf0AG Y+DfJJNd9i6TbIDWu8254/erAS6bKMhW/3q7f2kCgYAZ7Id/BiKJAWRpqTRBXlvw BhXoKvjI2HjYP21z/EyZ+PFPzur/lNaZhIUlMnUfibbwE9pFggQzzf8scM7c7Sf+ mLoVSdoQ/Rujz7CqvQzi2nKSsM7t0curUIb3lJWee5/UeEaxZcmIufoNUrzohAWH BJOIPDM4ssUTLRq7wYM9uQKBgHCBau5OP8gE6mjKuXsZXWUoahpFLKwwwmJUp2vQ pOFPJ/6WZOlqkTVT6QPAcPUbTohKrF80hsZqZyDdSfT3peFx4ZLocBrS56m6NmHR UYHMvJ8rQm76T1fryHVidz85g3zRmfBeWg8yqT5oFg4LYgfLsPm1gRjOhs8LfPvI OLlRAoGBAIZ5Uv4Z3s8O7WKXXUe/lq6j7vfiVkR1NW/Z/WLKXZpnmvJ7FgxN4e56 RXT7GwNQHIY8eDjDnsHxzrxd+raOxOZeKcMHj3XyjCX3NHfTscnsBPAGYpY/Wxzh T8UYnFu6RzkixElTf2rseEav7rkdKkI3LAeIZy7B0HulKKsmqVQ7 -----END RSA PRIVATE KEY----- ` WrongPrivateKey = ` -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAlrCgnEVgmNKCq7KPc+zUU5IrxPu1ClMNJS7RTsTPEkbwe5SB p+6V6WtCbD/X/lDRRGbOENChh1Phulb7lViqgrdpHydgsrKoS5ah3DfSIxLFLE00 9Yo4TCYwgw6+s59j16ZAFVinaQ9l6Kmrb2ll136hMrz8QKh+qw+onOLd38WFgm+W ZtUqSXf2LANzfzzy4OWFNyFqKaCAolSkPdTS9Nz+svtScvp002DQp8OdP1AgPO+l o5N3M38Fftapwg0pCtJ5Zq0NRWIXEonXiTEMA6zy3gEZVOmDxoIFUWnmrqlMJLFy 5S6LDrHSdqJhCxDK6WRZj43X9j8spktk3eGhMwIDAQABAoIBAAem8ID/BOi9x+Tw LFi2rhGQWqimH4tmrEQ3HGnjlKBY+d1MrUjZ1MMFr1nP5CgF8pqGnfA8p/c3Sz8r K5tp5T6+EZiDZ2WrrOApxg5ox0MAsQKO6SGO40z6o3wEQ6rbbTaGOrraxaWQIpyu AQanU4Sd6ZGqByVBaS1GnklZO+shCHqw73b7g1cpLEmFzcYnKHYHlUUIsstMe8E1 BaCY0CH7JbWBjcbiTnBVwIRZuu+EjGiQuhTilYL2OWqoMVg1WU0L2IFpR8lkf/2W SBx5J6xhwbBGASOpM+qidiN580GdPzGhWYSqKGroHEzBm6xPSmV1tadNA26WFG4p pthLiAECgYEA5BsPRpNYJAQLu5B0N7mj9eEp0HABVEgL/MpwiImjaKdAwp78HM64 IuPvJxs7r+xESiIz4JyjR8zrQjYOCKJsARYkmNlEuAz0SkHabCw1BdEBwUhjUGVB efoERK6GxfAoNqmSDwsOvHFOtsmDIlbHmg7G2rUxNVpeou415BSB0B8CgYEAqR4J YHKk2Ibr9rU+rBU33TcdTGw0aAkFNAVeqM9j0haWuFXmV3RArgoy09lH+2Ha6z/g fTX2xSDAWV7QUlLOlBRIhurPAo2jO2yCrGHPZcWiugstrR2hTTInigaSnCmK3i7F 6sYmL3S7K01IcVNxSlWvGijtClT92Cl2WUCTfG0CgYAiEjyk4QtQTd5mxLvnOu5X oqs5PBGmwiAwQRiv/EcRMbJFn7Oupd3xMDSflbzDmTnWDOfMy/jDl8MoH6TW+1PA kcsjnYhbKWwvz0hN0giVdtOZSDO1ZXpzOrn6fEsbM7T9/TQY1SD9WrtUKCNTNL0Z sM1ZC6lu+7GZCpW4HKwLJwKBgQCRT0yxQXBg1/UxwuO5ynV4rx2Oh76z0WRWIXMH S0MyxdP1SWGkrS/SGtM3cg/GcHtA/V6vV0nUcWK0p6IJyjrTw2XZ/zGluPuTWJYi 9dvVT26Vunshrz7kbH7KuwEICy3V4IyQQHeY+QzFlR70uMS0IVFWAepCoWqHbIDT CYhwNQKBgGPcLXmjpGtkZvggl0aZr9LsvCTckllSCFSI861kivL/rijdNoCHGxZv dfDkLTLcz9Gk41rD9Gxn/3sqodnTAc3Z2PxFnzg1Q/u3+x6YAgBwI/g/jE2xutGW H7CurtMwALQ/n/6LUKFmjRZjqbKX9SO2QSaC3grd6sY9Tu+bZjLe -----END RSA PRIVATE KEY----- ` ) hashicorp-go-cty-funcs-dc8fb47/crypto/md5.go000066400000000000000000000010071511636157000210500ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "crypto/md5" "encoding/hex" "github.com/zclconf/go-cty/cty" ) // Md5Func is a function that computes the MD5 hash of a given string and // encodes it with hexadecimal digits. var Md5Func = makeStringHashFunction(md5.New, hex.EncodeToString) // Md5 computes the MD5 hash of a given string and encodes it with hexadecimal // digits. func Md5(str cty.Value) (cty.Value, error) { return Md5Func.Call([]cty.Value{str}) } hashicorp-go-cty-funcs-dc8fb47/crypto/md5_test.go000066400000000000000000000020311511636157000221050ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestMd5(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("tada"), cty.StringVal("ce47d07243bb6eaf5e1322c81baf9bbf"), false, }, { // Confirm that we're not trimming any whitespaces cty.StringVal(" tada "), cty.StringVal("aadf191a583e53062de2d02c008141c4"), false, }, { // We accept empty string too cty.StringVal(""), cty.StringVal("d41d8cd98f00b204e9800998ecf8427e"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("md5(%#v)", test.String), func(t *testing.T) { got, err := Md5(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/crypto/rsa.go000066400000000000000000000033421511636157000211540ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) // RsaDecryptFunc is a function that decrypts an RSA-encrypted ciphertext. var RsaDecryptFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "ciphertext", Type: cty.String, }, { Name: "privatekey", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { s := args[0].AsString() key := args[1].AsString() b, err := base64.StdEncoding.DecodeString(s) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode input %q: cipher text must be base64-encoded", s) } block, _ := pem.Decode([]byte(key)) if block == nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to parse key: no key found") } if block.Headers["Proc-Type"] == "4,ENCRYPTED" { return cty.UnknownVal(cty.String), fmt.Errorf( "failed to parse key: password protected keys are not supported. Please decrypt the key prior to use", ) } x509Key, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return cty.UnknownVal(cty.String), err } out, err := rsa.DecryptPKCS1v15(nil, x509Key, b) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(string(out)), nil }, }) // RsaDecrypt decrypts an RSA-encrypted ciphertext, returning the corresponding // cleartext. func RsaDecrypt(ciphertext, privatekey cty.Value) (cty.Value, error) { return RsaDecryptFunc.Call([]cty.Value{ciphertext, privatekey}) } hashicorp-go-cty-funcs-dc8fb47/crypto/rsa_test.go000066400000000000000000000030161511636157000222110ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestRsaDecrypt(t *testing.T) { tests := []struct { Ciphertext cty.Value Privatekey cty.Value Want cty.Value Err bool }{ // Base-64 encoded cipher decrypts correctly { cty.StringVal(CipherBase64), cty.StringVal(PrivateKey), cty.StringVal("message"), false, }, // Wrong key { cty.StringVal(CipherBase64), cty.StringVal(WrongPrivateKey), cty.UnknownVal(cty.String), true, }, // Bad key { cty.StringVal(CipherBase64), cty.StringVal("bad key"), cty.UnknownVal(cty.String), true, }, // Empty key { cty.StringVal(CipherBase64), cty.StringVal(""), cty.UnknownVal(cty.String), true, }, // Bad cipher { cty.StringVal("bad cipher"), cty.StringVal(PrivateKey), cty.UnknownVal(cty.String), true, }, // Empty cipher { cty.StringVal(""), cty.StringVal(PrivateKey), cty.UnknownVal(cty.String), true, }, } for _, test := range tests { t.Run(fmt.Sprintf("RsaDecrypt(%#v, %#v)", test.Ciphertext, test.Privatekey), func(t *testing.T) { got, err := RsaDecrypt(test.Ciphertext, test.Privatekey) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/crypto/sha.go000066400000000000000000000024541511636157000211450ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "crypto/sha1" "crypto/sha256" "crypto/sha512" "encoding/hex" "github.com/zclconf/go-cty/cty" ) // Sha1Func is a function that computes the SHA1 hash of a given string and // encodes it with hexadecimal digits. var Sha1Func = makeStringHashFunction(sha1.New, hex.EncodeToString) // Sha256Func is a function that computes the SHA256 hash of a given string and // encodes it with hexadecimal digits. var Sha256Func = makeStringHashFunction(sha256.New, hex.EncodeToString) // Sha512Func is a function that computes the SHA512 hash of a given string and // encodes it with hexadecimal digits. var Sha512Func = makeStringHashFunction(sha512.New, hex.EncodeToString) // Sha1 computes the SHA1 hash of a given string and encodes it with // hexadecimal digits. func Sha1(str cty.Value) (cty.Value, error) { return Sha1Func.Call([]cty.Value{str}) } // Sha256 computes the SHA256 hash of a given string and encodes it with // hexadecimal digits. func Sha256(str cty.Value) (cty.Value, error) { return Sha256Func.Call([]cty.Value{str}) } // Sha512 computes the SHA512 hash of a given string and encodes it with // hexadecimal digits. func Sha512(str cty.Value) (cty.Value, error) { return Sha512Func.Call([]cty.Value{str}) } hashicorp-go-cty-funcs-dc8fb47/crypto/sha_test.go000066400000000000000000000041751511636157000222060ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package crypto import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestSha1(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("test"), cty.StringVal("a94a8fe5ccb19ba61c4c0873d391e987982fbbd3"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("sha1(%#v)", test.String), func(t *testing.T) { got, err := Sha1(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestSha256(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("test"), cty.StringVal("9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("sha256(%#v)", test.String), func(t *testing.T) { got, err := Sha256(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestSha512(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("test"), cty.StringVal("ee26b0dd4af7e749aa1a8ee3c10ae9923f618980772e473f8819a5d4940e0db27ac185f8a0e1d5f84f88bc887fd67b143732c304cc5fa9ad8e6f57f50028a8ff"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("sha512(%#v)", test.String), func(t *testing.T) { got, err := Sha512(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/crypto/testdata/000077500000000000000000000000001511636157000216475ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/crypto/testdata/hello.txt000066400000000000000000000000131511636157000235050ustar00rootroot00000000000000Hello Worldhashicorp-go-cty-funcs-dc8fb47/crypto/testdata/icon.png000066400000000000000000000014461511636157000233120ustar00rootroot00000000000000PNG  IHDR(-SgAMA a cHRMz&u0`:pQ<PLTE\N^Q\N\N\O[I\N]OII\O\N@@@@\N\N\RAA??@@ZN\O\NFC@@UU\N\NFD^Q[M\N??^M[L\M@@AA@@ZP\M[O\N@@@@]NGG`P`P\N]M]OYN\N@@>a6tRNS&7w_7Acl{Fk0kݻ, BkybKGDH pHYstIMEMLIDAT}PB D̞yFGs$ SwQL9BȢi(+ѫ>zVv^^`c@0 0 8(L|6_,Wkv-tqFJrMpS_,%tEXtdate:create2017-04-05T18:16:15+02:00U%tEXtdate:modify2017-04-05T18:16:15+02:00stEXtSoftwarewww.inkscape.org< tEXtTitleGroup"WzTXtRaw profile type iptcx qV((OIR# .c #K D4d#T ˀHJ.tB5IENDB`hashicorp-go-cty-funcs-dc8fb47/encoding/000077500000000000000000000000001511636157000203045ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/encoding/base64.go000066400000000000000000000046341511636157000217260ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package encoding import ( "encoding/base64" "fmt" "log" "unicode/utf8" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) // Base64DecodeFunc is a function that decodes a string containing a base64 sequence. var Base64DecodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { s := args[0].AsString() sDec, err := base64.StdEncoding.DecodeString(s) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode base64 data '%s'", s) } if !utf8.Valid([]byte(sDec)) { log.Printf("[DEBUG] the result of decoding the the provided string is not valid UTF-8: %s", sDec) return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the the provided string is not valid UTF-8") } return cty.StringVal(string(sDec)), nil }, }) // Base64EncodeFunc is a function that encodes a string to a base64 sequence. var Base64EncodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(base64.StdEncoding.EncodeToString([]byte(args[0].AsString()))), nil }, }) // Base64Decode decodes a string containing a base64 sequence. // // Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. // // Strings in the Terraform language are sequences of unicode characters rather // than bytes, so this function will also interpret the resulting bytes as // UTF-8. If the bytes after Base64 decoding are _not_ valid UTF-8, this function // produces an error. func Base64Decode(str cty.Value) (cty.Value, error) { return Base64DecodeFunc.Call([]cty.Value{str}) } // Base64Encode applies Base64 encoding to a string. // // Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4. // // Strings in the Terraform language are sequences of unicode characters rather // than bytes, so this function will first encode the characters from the string // as UTF-8, and then apply Base64 encoding to the result. func Base64Encode(str cty.Value) (cty.Value, error) { return Base64EncodeFunc.Call([]cty.Value{str}) } hashicorp-go-cty-funcs-dc8fb47/encoding/base64_test.go000066400000000000000000000032331511636157000227570ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package encoding import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestBase64Decode(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("YWJjMTIzIT8kKiYoKSctPUB+"), cty.StringVal("abc123!?$*&()'-=@~"), false, }, { // Invalid base64 data decoding cty.StringVal("this-is-an-invalid-base64-data"), cty.UnknownVal(cty.String), true, }, { // Invalid utf-8 cty.StringVal("\xc3\x28"), cty.UnknownVal(cty.String), true, }, } for _, test := range tests { t.Run(fmt.Sprintf("base64decode(%#v)", test.String), func(t *testing.T) { got, err := Base64Decode(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestBase64Encode(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("abc123!?$*&()'-=@~"), cty.StringVal("YWJjMTIzIT8kKiYoKSctPUB+"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("base64encode(%#v)", test.String), func(t *testing.T) { got, err := Base64Encode(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/encoding/url.go000066400000000000000000000021121511636157000214310ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package encoding import ( "net/url" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) // URLEncodeFunc is a function that applies URL encoding to a given string. var URLEncodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(url.QueryEscape(args[0].AsString())), nil }, }) // URLEncode applies URL encoding to a given string. // // This function identifies characters in the given string that would have a // special meaning when included as a query string argument in a URL and // escapes them using RFC 3986 "percent encoding". // // If the given string contains non-ASCII characters, these are first encoded as // UTF-8 and then percent encoding is applied separately to each UTF-8 byte. func URLEncode(str cty.Value) (cty.Value, error) { return URLEncodeFunc.Call([]cty.Value{str}) } hashicorp-go-cty-funcs-dc8fb47/encoding/url_test.go000066400000000000000000000021711511636157000224750ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package encoding import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestURLEncode(t *testing.T) { tests := []struct { String cty.Value Want cty.Value Err bool }{ { cty.StringVal("abc123-_"), cty.StringVal("abc123-_"), false, }, { cty.StringVal("foo:bar@localhost?foo=bar&bar=baz"), cty.StringVal("foo%3Abar%40localhost%3Ffoo%3Dbar%26bar%3Dbaz"), false, }, { cty.StringVal("mailto:email?subject=this+is+my+subject"), cty.StringVal("mailto%3Aemail%3Fsubject%3Dthis%2Bis%2Bmy%2Bsubject"), false, }, { cty.StringVal("foo/bar"), cty.StringVal("foo%2Fbar"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("urlencode(%#v)", test.String), func(t *testing.T) { got, err := URLEncode(test.String) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/filesystem/000077500000000000000000000000001511636157000207025ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/filesystem/filesystem.go000066400000000000000000000232071511636157000234210ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package filesystem import ( "encoding/base64" "fmt" "io/ioutil" "os" "path/filepath" "unicode/utf8" "github.com/bmatcuk/doublestar" homedir "github.com/mitchellh/go-homedir" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) // MakeFileFunc constructs a function that takes a file path and returns the // contents of that file, either directly as a string (where valid UTF-8 is // required) or as a string containing base64 bytes. func MakeFileFunc(baseDir string, encBase64 bool) function.Function { return function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { path := args[0].AsString() src, err := readFileBytes(baseDir, path) if err != nil { return cty.UnknownVal(cty.String), err } switch { case encBase64: enc := base64.StdEncoding.EncodeToString(src) return cty.StringVal(enc), nil default: if !utf8.Valid(src) { return cty.UnknownVal(cty.String), fmt.Errorf("contents of %s are not valid UTF-8; use the filebase64 function to obtain the Base64 encoded contents or the other file functions (e.g. filemd5, filesha256) to obtain file hashing results instead", path) } return cty.StringVal(string(src)), nil } }, }) } // MakeFileExistsFunc is a function that takes a path and determines whether a // file exists at that path. // // MakeFileExistsFunc will try to expand a path starting with a '~' to the home // folder using github.com/mitchellh/go-homedir func MakeFileExistsFunc(baseDir string) function.Function { return function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.Bool), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { path := args[0].AsString() path, err := homedir.Expand(path) if err != nil { return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to expand ~: %s", err) } if !filepath.IsAbs(path) { path = filepath.Join(baseDir, path) } // Ensure that the path is canonical for the host OS path = filepath.Clean(path) fi, err := os.Stat(path) if err != nil { if os.IsNotExist(err) { return cty.False, nil } return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to stat %s", path) } if fi.Mode().IsRegular() { return cty.True, nil } return cty.False, fmt.Errorf("%s is not a regular file, but %q", path, fi.Mode().String()) }, }) } // MakeFileSetFunc is a function that takes a glob pattern // and enumerates a file set from that pattern func MakeFileSetFunc(baseDir string) function.Function { return function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, { Name: "pattern", Type: cty.String, }, }, Type: function.StaticReturnType(cty.Set(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { path := args[0].AsString() pattern := args[1].AsString() if !filepath.IsAbs(path) { path = filepath.Join(baseDir, path) } // Join the path to the glob pattern, while ensuring the full // pattern is canonical for the host OS. The joined path is // automatically cleaned during this operation. pattern = filepath.Join(path, pattern) matches, err := doublestar.Glob(pattern) if err != nil { return cty.UnknownVal(cty.Set(cty.String)), fmt.Errorf("failed to glob pattern (%s): %s", pattern, err) } var matchVals []cty.Value for _, match := range matches { fi, err := os.Stat(match) if err != nil { return cty.UnknownVal(cty.Set(cty.String)), fmt.Errorf("failed to stat (%s): %s", match, err) } if !fi.Mode().IsRegular() { continue } // Remove the path and file separator from matches. match, err = filepath.Rel(path, match) if err != nil { return cty.UnknownVal(cty.Set(cty.String)), fmt.Errorf("failed to trim path of match (%s): %s", match, err) } // Replace any remaining file separators with forward slash (/) // separators for cross-system compatibility. match = filepath.ToSlash(match) matchVals = append(matchVals, cty.StringVal(match)) } if len(matchVals) == 0 { return cty.SetValEmpty(cty.String), nil } return cty.SetVal(matchVals), nil }, }) } // BasenameFunc is a function that takes a string containing a filesystem path // and removes all except the last portion from it. var BasenameFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(filepath.Base(args[0].AsString())), nil }, }) // DirnameFunc is a function that takes a string containing a filesystem path // and removes the last portion from it. var DirnameFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(filepath.Dir(args[0].AsString())), nil }, }) // AbsPathFunc is a function that converts a filesystem path to an absolute path var AbsPathFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { absPath, err := filepath.Abs(args[0].AsString()) return cty.StringVal(filepath.ToSlash(absPath)), err }, }) // PathExpandFunc is a function that expands a leading ~ character to the current user's home directory. var PathExpandFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { homePath, err := homedir.Expand(args[0].AsString()) return cty.StringVal(homePath), err }, }) func readFileBytes(baseDir, path string) ([]byte, error) { path, err := homedir.Expand(path) if err != nil { return nil, fmt.Errorf("failed to expand ~: %s", err) } if !filepath.IsAbs(path) { path = filepath.Join(baseDir, path) } // Ensure that the path is canonical for the host OS path = filepath.Clean(path) src, err := ioutil.ReadFile(path) if err != nil { // ReadFile does not return Terraform-user-friendly error // messages, so we'll provide our own. if os.IsNotExist(err) { return nil, fmt.Errorf("no file exists at %s", path) } return nil, fmt.Errorf("failed to read %s", path) } return src, nil } // File reads the contents of the file at the given path. // // The file must contain valid UTF-8 bytes, or this function will return an error. // // The underlying function implementation works relative to a particular base // directory, so this wrapper takes a base directory string and uses it to // construct the underlying function before calling it. func File(baseDir string, path cty.Value) (cty.Value, error) { fn := MakeFileFunc(baseDir, false) return fn.Call([]cty.Value{path}) } // FileExists determines whether a file exists at the given path. // // The underlying function implementation works relative to a particular base // directory, so this wrapper takes a base directory string and uses it to // construct the underlying function before calling it. func FileExists(baseDir string, path cty.Value) (cty.Value, error) { fn := MakeFileExistsFunc(baseDir) return fn.Call([]cty.Value{path}) } // FileSet enumerates a set of files given a glob pattern // // The underlying function implementation works relative to a particular base // directory, so this wrapper takes a base directory string and uses it to // construct the underlying function before calling it. func FileSet(baseDir string, path, pattern cty.Value) (cty.Value, error) { fn := MakeFileSetFunc(baseDir) return fn.Call([]cty.Value{path, pattern}) } // Basename takes a string containing a filesystem path and removes all except the last portion from it. // // The underlying function implementation works only with the path string and does not access the filesystem itself. // It is therefore unable to take into account filesystem features such as symlinks. // // If the path is empty then the result is ".", representing the current working directory. func Basename(path cty.Value) (cty.Value, error) { return BasenameFunc.Call([]cty.Value{path}) } // Dirname takes a string containing a filesystem path and removes the last portion from it. // // The underlying function implementation works only with the path string and does not access the filesystem itself. // It is therefore unable to take into account filesystem features such as symlinks. // // If the path is empty then the result is ".", representing the current working directory. func Dirname(path cty.Value) (cty.Value, error) { return DirnameFunc.Call([]cty.Value{path}) } // Pathexpand takes a string that might begin with a `~` segment, and if so it replaces that segment with // the current user's home directory path. // // The underlying function implementation works only with the path string and does not access the filesystem itself. // It is therefore unable to take into account filesystem features such as symlinks. // // If the leading segment in the path is not `~` then the given path is returned unmodified. func Pathexpand(path cty.Value) (cty.Value, error) { return PathExpandFunc.Call([]cty.Value{path}) } hashicorp-go-cty-funcs-dc8fb47/filesystem/filesystem_test.go000066400000000000000000000202321511636157000244530ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package filesystem import ( "fmt" "path/filepath" "runtime" "testing" homedir "github.com/mitchellh/go-homedir" "github.com/zclconf/go-cty/cty" ) func TestFileExists(t *testing.T) { tests := []struct { Path cty.Value Want cty.Value Err bool }{ { cty.StringVal("testdata/hello.txt"), cty.BoolVal(true), false, }, { cty.StringVal(""), // empty path cty.BoolVal(false), true, }, { cty.StringVal("testdata/missing"), cty.BoolVal(false), false, // no file exists }, } for _, test := range tests { t.Run(fmt.Sprintf("FileExists(\".\", %#v)", test.Path), func(t *testing.T) { got, err := FileExists(".", test.Path) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestFileSet(t *testing.T) { type testCase struct { Path cty.Value Pattern cty.Value Want cty.Value Err bool } tests := []testCase{ { cty.StringVal("."), cty.StringVal("testdata*"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("testdata"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("{testdata,missing}"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("testdata/missing"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("testdata/missing*"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("*/missing"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("**/missing"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("."), cty.StringVal("testdata/*.txt"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("testdata/hello.txt"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("testdata/hello.???"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("testdata/hello*"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.tmpl"), cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("testdata/hello.{tmpl,txt}"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.tmpl"), cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("*/hello.txt"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("*/*.txt"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("*/hello*"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.tmpl"), cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("**/hello*"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.tmpl"), cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("**/hello.{tmpl,txt}"), cty.SetVal([]cty.Value{ cty.StringVal("testdata/hello.tmpl"), cty.StringVal("testdata/hello.txt"), }), false, }, { cty.StringVal("."), cty.StringVal("["), cty.SetValEmpty(cty.String), true, }, { cty.StringVal("testdata"), cty.StringVal("missing"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("testdata"), cty.StringVal("missing*"), cty.SetValEmpty(cty.String), false, }, { cty.StringVal("testdata"), cty.StringVal("*.txt"), cty.SetVal([]cty.Value{ cty.StringVal("hello.txt"), }), false, }, { cty.StringVal("testdata"), cty.StringVal("hello.txt"), cty.SetVal([]cty.Value{ cty.StringVal("hello.txt"), }), false, }, { cty.StringVal("testdata"), cty.StringVal("hello.???"), cty.SetVal([]cty.Value{ cty.StringVal("hello.txt"), }), false, }, { cty.StringVal("testdata"), cty.StringVal("hello*"), cty.SetVal([]cty.Value{ cty.StringVal("hello.tmpl"), cty.StringVal("hello.txt"), }), false, }, } switch runtime.GOOS { case "windows": tests = append(tests, []testCase{ { cty.StringVal("."), cty.StringVal("//"), cty.SetValEmpty(cty.String), false, }, }..., ) default: tests = append(tests, []testCase{ { cty.StringVal("."), cty.StringVal("\\"), cty.SetValEmpty(cty.String), false, }, }..., ) } for _, test := range tests { t.Run(fmt.Sprintf("FileSet(\".\", %#v, %#v)", test.Path, test.Pattern), func(t *testing.T) { got, err := FileSet(".", test.Path, test.Pattern) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestBasename(t *testing.T) { tests := []struct { Path cty.Value Want cty.Value Err bool }{ { cty.StringVal("testdata/hello.txt"), cty.StringVal("hello.txt"), false, }, { cty.StringVal("hello.txt"), cty.StringVal("hello.txt"), false, }, { cty.StringVal(""), cty.StringVal("."), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("Basename(%#v)", test.Path), func(t *testing.T) { got, err := Basename(test.Path) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestDirname(t *testing.T) { type testCase struct { Path cty.Value Want cty.Value Err bool } tests := []testCase{ { cty.StringVal("testdata/hello.txt"), cty.StringVal("testdata"), false, }, { cty.StringVal("hello.txt"), cty.StringVal("."), false, }, { cty.StringVal(""), cty.StringVal("."), false, }, } switch runtime.GOOS { case "windows": tests = append(tests, []testCase{ { cty.StringVal("testdata/foo/hello.txt"), cty.StringVal("testdata\\foo"), false, }, }..., ) default: tests = append(tests, []testCase{ { cty.StringVal("testdata/foo/hello.txt"), cty.StringVal("testdata/foo"), false, }, }..., ) } for _, test := range tests { t.Run(fmt.Sprintf("Dirname(%#v)", test.Path), func(t *testing.T) { got, err := Dirname(test.Path) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } func TestPathExpand(t *testing.T) { homePath, err := homedir.Dir() if err != nil { t.Fatalf("Error getting home directory: %v", err) } tests := []struct { Path cty.Value Want cty.Value Err bool }{ { cty.StringVal("~/test-file"), cty.StringVal(filepath.Join(homePath, "test-file")), false, }, { cty.StringVal("~/another/test/file"), cty.StringVal(filepath.Join(homePath, "another/test/file")), false, }, { cty.StringVal("/root/file"), cty.StringVal("/root/file"), false, }, { cty.StringVal("/"), cty.StringVal("/"), false, }, } for _, test := range tests { t.Run(fmt.Sprintf("Dirname(%#v)", test.Path), func(t *testing.T) { got, err := Pathexpand(test.Path) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } } hashicorp-go-cty-funcs-dc8fb47/filesystem/testdata/000077500000000000000000000000001511636157000225135ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/filesystem/testdata/hello.tmpl000066400000000000000000000000001511636157000245020ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/filesystem/testdata/hello.txt000066400000000000000000000000131511636157000243510ustar00rootroot00000000000000Hello Worldhashicorp-go-cty-funcs-dc8fb47/go.mod000066400000000000000000000006121511636157000176230ustar00rootroot00000000000000module github.com/hashicorp/go-cty-funcs go 1.24.0 require ( github.com/apparentlymart/go-cidr v1.1.0 github.com/bmatcuk/doublestar v1.3.4 github.com/google/uuid v1.6.0 github.com/mitchellh/go-homedir v1.1.0 github.com/zclconf/go-cty v1.17.0 golang.org/x/crypto v0.45.0 ) require ( github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect golang.org/x/text v0.31.0 // indirect ) hashicorp-go-cty-funcs-dc8fb47/go.sum000066400000000000000000000030271511636157000176530ustar00rootroot00000000000000github.com/apparentlymart/go-cidr v1.1.0 h1:2mAhrMoF+nhXqxTzSZMUzDHkLjmIHC+Zzn4tdgBZjnU= github.com/apparentlymart/go-cidr v1.1.0/go.mod h1:EBcsNrHc3zQeuaeCeCtQruQm+n9/YjEn/vI25Lg7Gwc= github.com/apparentlymart/go-textseg/v15 v15.0.0 h1:uYvfpb3DyLSCGWnctWKGj857c6ew1u1fNQOlOtuGxQY= github.com/apparentlymart/go-textseg/v15 v15.0.0/go.mod h1:K8XmNZdhEBkdlyDdvbmmsvpAG721bKi0joRfFdHIWJ4= github.com/bmatcuk/doublestar v1.3.4 h1:gPypJ5xD31uhX6Tf54sDPUOBXTqKH4c9aPY66CyQrS0= github.com/bmatcuk/doublestar v1.3.4/go.mod h1:wiQtGV+rzVYxB7WIlirSN++5HPtPlXEo9MEoZQC/PmE= github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y= github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= github.com/zclconf/go-cty v1.17.0 h1:seZvECve6XX4tmnvRzWtJNHdscMtYEx5R7bnnVyd/d0= github.com/zclconf/go-cty v1.17.0/go.mod h1:wqFzcImaLTI6A5HfsRwB0nj5n0MRZFwmey8YoFPPs3U= golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q= golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4= golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM= golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM= hashicorp-go-cty-funcs-dc8fb47/uuid/000077500000000000000000000000001511636157000174645ustar00rootroot00000000000000hashicorp-go-cty-funcs-dc8fb47/uuid/uuid_v4.go000066400000000000000000000014161511636157000213740ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package uuid import ( "github.com/google/uuid" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) var V4Func = function.New(&function.Spec{ Params: []function.Parameter{}, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { uuid, err := uuid.NewRandom() if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(uuid.String()), nil }, }) // V4 generates and returns a Type-4 UUID in the standard hexadecimal string // format. // // This is not a "pure" function: it will generate a different result for each // call. func V4() (cty.Value, error) { return V4Func.Call(nil) } hashicorp-go-cty-funcs-dc8fb47/uuid/uuid_v4_test.go000066400000000000000000000005221511636157000224300ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package uuid import ( "testing" ) func TestV4(t *testing.T) { result, err := V4() if err != nil { t.Fatal(err) } resultStr := result.AsString() if got, want := len(resultStr), 36; got != want { t.Errorf("wrong result length %d; want %d", got, want) } } hashicorp-go-cty-funcs-dc8fb47/uuid/uuid_v5.go000066400000000000000000000026621511636157000214010ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package uuid import ( "fmt" uuidv5 "github.com/google/uuid" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/function" ) var V5Func = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "namespace", Type: cty.String, }, { Name: "name", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var namespace uuidv5.UUID switch { case args[0].AsString() == "dns": namespace = uuidv5.NameSpaceDNS case args[0].AsString() == "url": namespace = uuidv5.NameSpaceURL case args[0].AsString() == "oid": namespace = uuidv5.NameSpaceOID case args[0].AsString() == "x500": namespace = uuidv5.NameSpaceX500 default: if namespace, err = uuidv5.Parse(args[0].AsString()); err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("uuidv5() doesn't support namespace %s (%v)", args[0].AsString(), err) } } val := args[1].AsString() return cty.StringVal(uuidv5.NewSHA1(namespace, []byte(val)).String()), nil }, }) // V5 generates and returns a Type-5 UUID in the standard hexadecimal // string format. // // This is not a "pure" function: it will generate a different result for each // call. func V5(namespace cty.Value, name cty.Value) (cty.Value, error) { return V5Func.Call([]cty.Value{namespace, name}) } hashicorp-go-cty-funcs-dc8fb47/uuid/uuid_v5_test.go000066400000000000000000000027471511636157000224440ustar00rootroot00000000000000// Copyright IBM Corp. 2020, 2025 // SPDX-License-Identifier: MPL-2.0 package uuid import ( "fmt" "testing" "github.com/zclconf/go-cty/cty" ) func TestV5(t *testing.T) { tests := []struct { Namespace cty.Value Name cty.Value Want cty.Value Err bool }{ { cty.StringVal("dns"), cty.StringVal("tada"), cty.StringVal("faa898db-9b9d-5b75-86a9-149e7bb8e3b8"), false, }, { cty.StringVal("url"), cty.StringVal("tada"), cty.StringVal("2c1ff6b4-211f-577e-94de-d978b0caa16e"), false, }, { cty.StringVal("oid"), cty.StringVal("tada"), cty.StringVal("61eeea26-5176-5288-87fc-232d6ed30d2f"), false, }, { cty.StringVal("x500"), cty.StringVal("tada"), cty.StringVal("7e12415e-f7c9-57c3-9e43-52dc9950d264"), false, }, { cty.StringVal("6ba7b810-9dad-11d1-80b4-00c04fd430c8"), cty.StringVal("tada"), cty.StringVal("faa898db-9b9d-5b75-86a9-149e7bb8e3b8"), false, }, { cty.StringVal("tada"), cty.StringVal("tada"), cty.UnknownVal(cty.String), true, }, } for _, test := range tests { t.Run(fmt.Sprintf("uuidv5(%#v, %#v)", test.Namespace, test.Name), func(t *testing.T) { got, err := V5(test.Namespace, test.Name) if test.Err { if err == nil { t.Fatal("succeeded; want error") } return } else if err != nil { t.Fatalf("unexpected error: %s", err) } if !got.RawEquals(test.Want) { t.Errorf("wrong result\ngot: %#v\nwant: %#v", got, test.Want) } }) } }