pax_global_header00006660000000000000000000000064140162036130014506gustar00rootroot0000000000000052 comment=447e7f0eaa48d0b5cb8a406eb740b736323be387 go-slug-0.7.0/000077500000000000000000000000001401620361300130675ustar00rootroot00000000000000go-slug-0.7.0/.circleci/000077500000000000000000000000001401620361300147225ustar00rootroot00000000000000go-slug-0.7.0/.circleci/config.yml000066400000000000000000000003401401620361300167070ustar00rootroot00000000000000version: 2 workflows: version: 2 build: jobs: - test jobs: test: docker: - image: docker.mirror.hashicorp.services/cimg/go:1.15 steps: - checkout - run: go test -race ./... go-slug-0.7.0/.github/000077500000000000000000000000001401620361300144275ustar00rootroot00000000000000go-slug-0.7.0/.github/workflows/000077500000000000000000000000001401620361300164645ustar00rootroot00000000000000go-slug-0.7.0/.github/workflows/codeql-analysis.yml000066400000000000000000000030171401620361300223000ustar00rootroot00000000000000name: "Code scanning - scheduled (weekly) or on-demand" on: schedule: - cron: '0 15 * * 0' workflow_dispatch: jobs: CodeQL-Build: runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v2 with: # We must fetch at least the immediate parents so that if this is # a pull request then we can checkout the head. fetch-depth: 2 # If this run was triggered by a pull request event, then checkout # the head of the pull request instead of the merge commit. - run: git checkout HEAD^2 if: ${{ github.event_name == 'pull_request' }} # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v1 # Override language selection by uncommenting this and choosing your languages with: languages: go # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) # - name: Autobuild # uses: github/codeql-action/autobuild@v1 # ℹ️ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 go-slug-0.7.0/.gitignore000066400000000000000000000003001401620361300150500ustar00rootroot00000000000000# Binaries for programs and plugins *.exe *.exe~ *.dll *.so *.dylib # Test binary, build with `go test -c` *.test # Output of the go coverage tool, specifically when used with LiteIDE *.out go-slug-0.7.0/LICENSE000066400000000000000000000405251401620361300141020ustar00rootroot00000000000000Mozilla 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. go-slug-0.7.0/README.md000066400000000000000000000043051401620361300143500ustar00rootroot00000000000000# go-slug [![Build Status](https://circleci.com/gh/hashicorp/go-slug.svg?style=shield)](https://app.circleci.com/pipelines/github/hashicorp/go-slug) [![GitHub license](https://img.shields.io/github/license/hashicorp/go-slug.svg)](https://github.com/hashicorp/go-slug/blob/master/LICENSE) [![GoDoc](https://godoc.org/github.com/hashicorp/go-slug?status.svg)](https://godoc.org/github.com/hashicorp/go-slug) [![Go Report Card](https://goreportcard.com/badge/github.com/hashicorp/go-slug)](https://goreportcard.com/report/github.com/hashicorp/go-slug) [![GitHub issues](https://img.shields.io/github/issues/hashicorp/go-slug.svg)](https://github.com/hashicorp/go-slug/issues) Package `go-slug` offers functions for packing and unpacking Terraform Enterprise compatible slugs. Slugs are gzip compressed tar files containing Terraform configuration files. ## Installation Installation can be done with a normal `go get`: ``` go get -u github.com/hashicorp/go-slug ``` ## Documentation For the complete usage of `go-slug`, see the full [package docs](https://godoc.org/github.com/hashicorp/go-slug). ## Example Packing or unpacking a slug is pretty straight forward as shown in the following example: ```go package main import ( "bytes" "io/ioutil" "log" "os" slug "github.com/hashicorp/go-slug" ) func main() { // First create a buffer for storing the slug. buf := bytes.NewBuffer(nil) // Then call the Pack function with a directory path containing the // configuration files and an io.Writer to write the slug to. if _, err := slug.Pack("testdata/archive-dir", buf, false); err != nil { log.Fatal(err) } // Create a directory to unpack the slug contents into. dst, err := ioutil.TempDir("", "slug") if err != nil { log.Fatal(err) } defer os.RemoveAll(dst) // Unpacking a slug is done by calling the Unpack function with an // io.Reader to read the slug from and a directory path of an existing // directory to store the unpacked configuration files. if err := slug.Unpack(buf, dst); err != nil { log.Fatal(err) } } ``` ## Issues and Contributing If you find an issue with this package, please report an issue. If you'd like, we welcome any contributions. Fork this repository and submit a pull request. go-slug-0.7.0/go.mod000066400000000000000000000000551401620361300141750ustar00rootroot00000000000000module github.com/hashicorp/go-slug go 1.15 go-slug-0.7.0/slug.go000066400000000000000000000305251401620361300143750ustar00rootroot00000000000000package slug import ( "archive/tar" "compress/gzip" "fmt" "io" "os" "path/filepath" "strings" ) // Meta provides detailed information about a slug. type Meta struct { // The list of files contained in the slug. Files []string // Total size of the slug in bytes. Size int64 } // IllegalSlugError indicates the provided slug (io.Writer for Pack, io.Reader // for Unpack) violates a rule about its contents. For example, an absolute or // external symlink. It implements the error interface. type IllegalSlugError struct { Err error } func (e *IllegalSlugError) Error() string { return fmt.Sprintf("illegal slug error: %v", e.Err) } // Unwrap returns the underlying issue with the provided Slug into the error // chain. func (e *IllegalSlugError) Unwrap() error { return e.Err } // PackerOption is a functional option that can configure non-default Packers. type PackerOption func(*Packer) error // ApplyTerraformIgnore is a PackerOption that will apply the .terraformignore // rules and skip packing files it specifies. func ApplyTerraformIgnore() PackerOption { return func(p *Packer) error { p.applyTerraformIgnore = true return nil } } // DereferenceSymlinks is a PackerOption that will allow symlinks that // reference a target outside of the src directory. func DereferenceSymlinks() PackerOption { return func(p *Packer) error { p.dereference = true return nil } } // Packer holds options for the Pack function. type Packer struct { dereference bool applyTerraformIgnore bool } // NewPacker is a constructor for Packer. func NewPacker(options ...PackerOption) (*Packer, error) { p := &Packer{ dereference: false, applyTerraformIgnore: false, } for _, opt := range options { if err := opt(p); err != nil { return nil, fmt.Errorf("option failed: %w", err) } } return p, nil } // Pack at the package level is used to maintain compatibility with existing // code that relies on this function signature. New options related to packing // slugs should be added to the Packer struct instead. func Pack(src string, w io.Writer, dereference bool) (*Meta, error) { p := Packer{ dereference: dereference, // This defaults to false in NewPacker, but is true here. This matches // the old behavior of Pack, which always used .terraformignore. applyTerraformIgnore: true, } return p.Pack(src, w) } // Pack creates a slug from a src directory, and writes the new slug // to w. Returns metadata about the slug and any errors. // // When dereference is set to true, symlinks with a target outside of // the src directory will be dereferenced. When dereference is set to // false symlinks with a target outside the src directory are omitted // from the slug. func (p *Packer) Pack(src string, w io.Writer) (*Meta, error) { // Gzip compress all the output data. gzipW := gzip.NewWriter(w) // Tar the file contents. tarW := tar.NewWriter(gzipW) // Load the ignore rule configuration, which will use // defaults if no .terraformignore is configured var ignoreRules []rule if p.applyTerraformIgnore { ignoreRules = parseIgnoreFile(src) } // Track the metadata details as we go. meta := &Meta{} // Walk the tree of files. err := filepath.Walk(src, packWalkFn(src, src, src, tarW, meta, p.dereference, ignoreRules)) if err != nil { return nil, err } // Flush the tar writer. if err := tarW.Close(); err != nil { return nil, fmt.Errorf("failed to close the tar archive: %w", err) } // Flush the gzip writer. if err := gzipW.Close(); err != nil { return nil, fmt.Errorf("failed to close the gzip writer: %w", err) } return meta, nil } func packWalkFn(root, src, dst string, tarW *tar.Writer, meta *Meta, dereference bool, ignoreRules []rule) filepath.WalkFunc { return func(path string, info os.FileInfo, err error) error { if err != nil { return err } // Get the relative path from the current src directory. subpath, err := filepath.Rel(src, path) if err != nil { return fmt.Errorf("failed to get relative path for file %q: %w", path, err) } if subpath == "." { return nil } if m := matchIgnoreRule(subpath, ignoreRules); m { return nil } // Catch directories so we don't end up with empty directories, // the files are ignored correctly if info.IsDir() { if m := matchIgnoreRule(subpath+string(os.PathSeparator), ignoreRules); m { return nil } } // Get the relative path from the initial root directory. subpath, err = filepath.Rel(root, strings.Replace(path, src, dst, 1)) if err != nil { return fmt.Errorf("failed to get relative path for file %q: %w", path, err) } if subpath == "." { return nil } // Check the file type and if we need to write the body. keepFile, writeBody := checkFileMode(info.Mode()) if !keepFile { return nil } fm := info.Mode() header := &tar.Header{ Name: filepath.ToSlash(subpath), ModTime: info.ModTime(), Mode: int64(fm.Perm()), } switch { case info.IsDir(): header.Typeflag = tar.TypeDir header.Name += "/" case fm.IsRegular(): header.Typeflag = tar.TypeReg header.Size = info.Size() case fm&os.ModeSymlink != 0: target, err := filepath.EvalSymlinks(path) if err != nil { return fmt.Errorf("failed to get symbolic link destination for %q: %w", path, err) } // If the target is within the current source, we // create the symlink using a relative path. if strings.HasPrefix(target, src) { link, err := filepath.Rel(filepath.Dir(path), target) if err != nil { return fmt.Errorf("failed to get relative path for symlink destination %q: %w", target, err) } header.Typeflag = tar.TypeSymlink header.Linkname = filepath.ToSlash(link) // Break out of the case as a symlink // doesn't need any additional config. break } if !dereference { // Return early as the symlink has a target outside of the // src directory and we don't want to dereference symlinks. return nil } // Get the file info for the target. info, err = os.Lstat(target) if err != nil { return fmt.Errorf("failed to get file info from file %q: %w", target, err) } // If the target is a directory we can recurse into the target // directory by calling the packWalkFn with updated arguments. if info.IsDir() { return filepath.Walk(target, packWalkFn(root, target, path, tarW, meta, dereference, ignoreRules)) } // Dereference this symlink by updating the header with the target file // details and set writeBody to true so the body will be written. header.Typeflag = tar.TypeReg header.ModTime = info.ModTime() header.Mode = int64(info.Mode().Perm()) header.Size = info.Size() writeBody = true default: return fmt.Errorf("unexpected file mode %v", fm) } // Write the header first to the archive. if err := tarW.WriteHeader(header); err != nil { return fmt.Errorf("failed writing archive header for file %q: %w", path, err) } // Account for the file in the list. meta.Files = append(meta.Files, header.Name) // Skip writing file data for certain file types (above). if !writeBody { return nil } f, err := os.Open(path) if err != nil { return fmt.Errorf("failed opening file %q for archiving: %w", path, err) } defer f.Close() size, err := io.Copy(tarW, f) if err != nil { return fmt.Errorf("failed copying file %q to archive: %w", path, err) } // Add the size we copied to the body. meta.Size += size return nil } } // Unpack is used to read and extract the contents of a slug to the dst // directory. Symlinks within the slug are supported, provided their targets // are relative and point to paths within the destination directory. func Unpack(r io.Reader, dst string) error { // Decompress as we read. uncompressed, err := gzip.NewReader(r) if err != nil { return fmt.Errorf("failed to uncompress slug: %w", err) } // Untar as we read. untar := tar.NewReader(uncompressed) // Unpackage all the contents into the directory. for { header, err := untar.Next() if err == io.EOF { break } if err != nil { return fmt.Errorf("failed to untar slug: %w", err) } // Get rid of absolute paths. path := header.Name if path[0] == '/' { path = path[1:] } path = filepath.Join(dst, path) // Check for paths outside our directory, they are forbidden target := filepath.Clean(path) if !strings.HasPrefix(target, dst) { return &IllegalSlugError{ Err: fmt.Errorf("invalid filename, traversal with \"..\" outside of current directory"), } } // Ensure the destination is not through any symlinks. This prevents // any files from being deployed through symlinks defined in the slug. // There are malicious cases where this could be used to escape the // slug's boundaries (zipslip), and any legitimate use is questionable // and likely indicates a hand-crafted tar file, which we are not in // the business of supporting here. // // The strategy is to Lstat each path component from dst up to the // immediate parent directory of the file name in the tarball, checking // the mode on each to ensure we wouldn't be passing through any // symlinks. currentPath := dst // Start at the root of the unpacked tarball. components := strings.Split(header.Name, "/") for i := 0; i < len(components)-1; i++ { currentPath = filepath.Join(currentPath, components[i]) fi, err := os.Lstat(currentPath) if os.IsNotExist(err) { // Parent directory structure is incomplete. Technically this // means from here upward cannot be a symlink, so we cancel the // remaining path tests. break } if err != nil { return fmt.Errorf("failed to evaluate path %q: %w", header.Name, err) } if fi.Mode()&os.ModeSymlink != 0 { return &IllegalSlugError{ Err: fmt.Errorf("cannot extract %q through symlink", header.Name), } } } // Make the directories to the path. dir := filepath.Dir(path) if err := os.MkdirAll(dir, 0755); err != nil { return fmt.Errorf("failed to create directory %q: %w", dir, err) } // Handle symlinks. if header.Typeflag == tar.TypeSymlink { // Disallow absolute targets. if filepath.IsAbs(header.Linkname) { return &IllegalSlugError{ Err: fmt.Errorf( "invalid symlink (%q -> %q) has absolute target", header.Name, header.Linkname, ), } } // Ensure the link target is within the destination directory. This // disallows providing symlinks to external files and directories. target := filepath.Join(dir, header.Linkname) if !strings.HasPrefix(target, dst) { return &IllegalSlugError{ Err: fmt.Errorf( "invalid symlink (%q -> %q) has external target", header.Name, header.Linkname, ), } } // Create the symlink. if err := os.Symlink(header.Linkname, path); err != nil { return fmt.Errorf("failed creating symlink (%q -> %q): %w", header.Name, header.Linkname, err) } continue } // Only unpack regular files from this point on. if header.Typeflag == tar.TypeDir { continue } else if header.Typeflag != tar.TypeReg && header.Typeflag != tar.TypeRegA { return fmt.Errorf("failed creating %q: unsupported type %c", path, header.Typeflag) } // Open a handle to the destination. fh, err := os.Create(path) if err != nil { // This mimics tar's behavior wrt the tar file containing duplicate files // and it allowing later ones to clobber earlier ones even if the file // has perms that don't allow overwriting. if os.IsPermission(err) { os.Chmod(path, 0600) fh, err = os.Create(path) } if err != nil { return fmt.Errorf("failed creating file %q: %w", path, err) } } // Copy the contents. _, err = io.Copy(fh, untar) fh.Close() if err != nil { return fmt.Errorf("failed to copy slug file %q: %w", path, err) } // Restore the file mode. We have to do this after writing the file, // since it is possible we have a read-only mode. mode := header.FileInfo().Mode() if err := os.Chmod(path, mode); err != nil { return fmt.Errorf("failed setting permissions on %q: %w", path, err) } } return nil } // checkFileMode is used to examine an os.FileMode and determine if it should // be included in the archive, and if it has a data body which needs writing. func checkFileMode(m os.FileMode) (keep, body bool) { switch { case m.IsDir(): return true, false case m.IsRegular(): return true, true case m&os.ModeSymlink != 0: return true, false } return false, false } go-slug-0.7.0/slug_test.go000066400000000000000000000423441401620361300154360ustar00rootroot00000000000000package slug import ( "archive/tar" "bytes" "compress/gzip" "errors" "io" "io/ioutil" "os" "path/filepath" "reflect" "strings" "testing" ) func TestPack(t *testing.T) { slug := bytes.NewBuffer(nil) meta, err := Pack("testdata/archive-dir", slug, true) if err != nil { t.Fatalf("err: %v", err) } gzipR, err := gzip.NewReader(slug) if err != nil { t.Fatalf("err: %v", err) } tarR := tar.NewReader(gzipR) var ( symFound bool fileList []string slugSize int64 ) for { hdr, err := tarR.Next() if err == io.EOF { break } if err != nil { t.Fatalf("err: %v", err) } fileList = append(fileList, hdr.Name) if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA { slugSize += hdr.Size } if hdr.Name == "sub/bar.txt" { if hdr.Typeflag != tar.TypeSymlink { t.Fatalf("expect symlink for file 'sub/bar.txt'") } if hdr.Linkname != "../bar.txt" { t.Fatalf("expect target of '../bar.txt', got %q", hdr.Linkname) } symFound = true } } // Make sure we saw and handled a symlink if !symFound { t.Fatal("expected to find symlink") } // Make sure the .git directory is ignored for _, file := range fileList { if strings.Contains(file, ".git") { t.Fatalf("unexpected .git content: %s", file) } } // Make sure the .terraform directory is ignored, // except for the .terraform/modules subdirectory. for _, file := range fileList { if strings.HasPrefix(file, ".terraform"+string(filepath.Separator)) && !strings.HasPrefix(file, filepath.Clean(".terraform/modules")) { t.Fatalf("unexpected .terraform content: %s", file) } } // Make sure .terraform/modules is included. moduleDir := false for _, file := range fileList { if strings.HasPrefix(file, filepath.Clean(".terraform/modules")) { moduleDir = true break } } if !moduleDir { t.Fatal("expected to include .terraform/modules") } // Make sure .terraformrc is included. terraformrc := false for _, file := range fileList { if file == ".terraformrc" { terraformrc = true break } } if !terraformrc { t.Fatal("expected to include .terraformrc") } // Make sure foo.terraform/bar.txt is included. fooTerraformDir := false for _, file := range fileList { if file == filepath.Clean("foo.terraform/bar.txt") { fooTerraformDir = true break } } if !fooTerraformDir { t.Fatal("expected to include foo.terraform/bar.txt") } // Make sure baz.txt is excluded. bazTxt := false for _, file := range fileList { if file == filepath.Clean("baz.txt") { bazTxt = true break } } if bazTxt { t.Fatal("should not include baz.txt") } // Check the metadata expect := &Meta{ Files: fileList, Size: slugSize, } if !reflect.DeepEqual(meta, expect) { t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", expect, meta) } } func TestPackWithDereferencing(t *testing.T) { slug := bytes.NewBuffer(nil) meta, err := Pack("testdata/archive-dir", slug, true) if err != nil { t.Fatalf("err: %v", err) } gzipR, err := gzip.NewReader(slug) if err != nil { t.Fatalf("err: %v", err) } tarR := tar.NewReader(gzipR) var ( fileList []string slugSize int64 ) for { hdr, err := tarR.Next() if err == io.EOF { break } if err != nil { t.Fatalf("err: %v", err) } fileList = append(fileList, hdr.Name) if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA { slugSize += hdr.Size } if hdr.Name == "foo.txt" { if hdr.Typeflag != tar.TypeReg { t.Fatalf("expect symlink 'foo.txt' to be dereferenced") } } } // Check the metadata expect := &Meta{ Files: fileList, Size: slugSize, } if !reflect.DeepEqual(meta, expect) { t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", expect, meta) } } func TestPackWithoutDereferencing(t *testing.T) { slug := bytes.NewBuffer(nil) meta, err := Pack("testdata/archive-dir", slug, false) if err != nil { t.Fatalf("err: %v", err) } gzipR, err := gzip.NewReader(slug) if err != nil { t.Fatalf("err: %v", err) } tarR := tar.NewReader(gzipR) var ( fileList []string slugSize int64 ) for { hdr, err := tarR.Next() if err == io.EOF { break } if err != nil { t.Fatalf("err: %v", err) } fileList = append(fileList, hdr.Name) if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA { slugSize += hdr.Size } } // Make sure the the foo.txt symlink is not dereferenced // but is indeed ignored and not added to the archive. for _, file := range fileList { if file == "foo.txt" { t.Fatalf("unexpected dereferenced symlink: %s", file) } } // Check the metadata expect := &Meta{ Files: fileList, Size: slugSize, } if !reflect.DeepEqual(meta, expect) { t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", expect, meta) } } func TestPackWithoutIgnoring(t *testing.T) { slug := bytes.NewBuffer(nil) // By default NewPacker() creates a Packer that does not use // .terraformignore or dereference symlinks. p, err := NewPacker() if err != nil { t.Fatalf("err: %v", err) } meta, err := p.Pack("testdata/archive-dir", slug) if err != nil { t.Fatalf("err: %v", err) } gzipR, err := gzip.NewReader(slug) if err != nil { t.Fatalf("err: %v", err) } tarR := tar.NewReader(gzipR) var ( fileList []string slugSize int64 ) for { hdr, err := tarR.Next() if err == io.EOF { break } if err != nil { t.Fatalf("err: %v", err) } fileList = append(fileList, hdr.Name) if hdr.Typeflag == tar.TypeReg || hdr.Typeflag == tar.TypeRegA { slugSize += hdr.Size } } // baz.txt would normally be ignored, but should not be var bazFound bool for _, file := range fileList { if file == "baz.txt" { bazFound = true } } if !bazFound { t.Fatal("expected file baz.txt to be present, but not found") } // .terraform/file.txt would normally be ignored, but should not be var dotTerraformFileFound bool for _, file := range fileList { if file == ".terraform/file.txt" { dotTerraformFileFound = true } } if !dotTerraformFileFound { t.Fatal("expected file .terraform/file.txt to be present, but not found") } // Check the metadata expect := &Meta{ Files: fileList, Size: slugSize, } if !reflect.DeepEqual(meta, expect) { t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", expect, meta) } } func TestUnpack(t *testing.T) { // First create the slug file so we can try to unpack it. slug := bytes.NewBuffer(nil) if _, err := Pack("testdata/archive-dir", slug, true); err != nil { t.Fatalf("err: %v", err) } // Create a dir to unpack into. dst, err := ioutil.TempDir("", "slug") if err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dst) // Now try unpacking it. if err := Unpack(slug, dst); err != nil { t.Fatalf("err: %v", err) } // Verify all the files verifyFile(t, filepath.Join(dst, "foo.txt"), 0, "foo\n") verifyFile(t, filepath.Join(dst, "bar.txt"), 0, "bar\n") verifyFile(t, filepath.Join(dst, "sub", "bar.txt"), os.ModeSymlink, "../bar.txt") verifyFile(t, filepath.Join(dst, "sub", "zip.txt"), 0, "zip\n") // Check that we can set permissions properly verifyPerms(t, filepath.Join(dst, "foo.txt"), 0644) verifyPerms(t, filepath.Join(dst, "bar.txt"), 0644) verifyPerms(t, filepath.Join(dst, "sub", "zip.txt"), 0644) verifyPerms(t, filepath.Join(dst, "sub", "bar.txt"), 0644) verifyPerms(t, filepath.Join(dst, "exe"), 0755) } func TestUnpackDuplicateNoWritePerm(t *testing.T) { dir, err := ioutil.TempDir("", "slug") if err != nil { t.Fatalf("err:%v", err) } defer os.RemoveAll(dir) in := filepath.Join(dir, "slug.tar.gz") // Create the output file wfh, err := os.Create(in) if err != nil { t.Fatalf("err: %v", err) } // Gzip compress all the output data gzipW := gzip.NewWriter(wfh) // Tar the file contents tarW := tar.NewWriter(gzipW) var hdr tar.Header data := "this is a\n" hdr.Name = "a" hdr.Mode = 0100000 | 0400 hdr.Size = int64(len(data)) tarW.WriteHeader(&hdr) tarW.Write([]byte(data)) // write it twice tarW.WriteHeader(&hdr) tarW.Write([]byte(data)) tarW.Close() gzipW.Close() wfh.Close() // Open the slug file for reading. fh, err := os.Open(in) if err != nil { t.Fatalf("err: %v", err) } // Create a dir to unpack into. dst, err := ioutil.TempDir(dir, "") if err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dst) // Now try unpacking it. if err := Unpack(fh, dst); err != nil { t.Fatalf("err: %v", err) } // Verify all the files verifyFile(t, filepath.Join(dst, "a"), 0, "this is a\n") // Check that we can set permissions properly verifyPerms(t, filepath.Join(dst, "a"), 0400) } // ensure Unpack returns an error when an unsupported file type is encountered // in an archive, rather than silently discarding the data. func TestUnpackErrorOnUnhandledType(t *testing.T) { dir, err := ioutil.TempDir("", "slug") if err != nil { t.Fatalf("err:%v", err) } defer os.RemoveAll(dir) in := filepath.Join(dir, "slug.tar.gz") // Create the output file wfh, err := os.Create(in) if err != nil { t.Fatalf("err: %v", err) } // Gzip compress all the output data gzipW := gzip.NewWriter(wfh) // Tar the file contents tarW := tar.NewWriter(gzipW) var hdr tar.Header hdr.Typeflag = tar.TypeFifo // we're unlikely to support FIFOs :-) hdr.Name = "l" hdr.Size = int64(0) tarW.WriteHeader(&hdr) tarW.Close() gzipW.Close() wfh.Close() // Open the slug file for reading. fh, err := os.Open(in) if err != nil { t.Fatalf("err: %v", err) } // Create a dir to unpack into. dst, err := ioutil.TempDir(dir, "") if err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dst) // Now try unpacking it, which should fail if err := Unpack(fh, dst); err == nil { t.Fatalf("should have gotten error unpacking slug with fifo, got none") } } func TestUnpackMaliciousSymlinks(t *testing.T) { tcases := []struct { desc string headers []*tar.Header err string }{ { desc: "symlink with absolute path", headers: []*tar.Header{ &tar.Header{ Name: "l", Linkname: "/etc/shadow", Typeflag: tar.TypeSymlink, }, }, err: "has absolute target", }, { desc: "symlink with external target", headers: []*tar.Header{ &tar.Header{ Name: "l", Linkname: "../../../../../etc/shadow", Typeflag: tar.TypeSymlink, }, }, err: "has external target", }, { desc: "symlink with nested external target", headers: []*tar.Header{ &tar.Header{ Name: "l", Linkname: "foo/bar/baz/../../../../../../../../etc/shadow", Typeflag: tar.TypeSymlink, }, }, err: "has external target", }, { desc: "zipslip vulnerability", headers: []*tar.Header{ &tar.Header{ Name: "subdir/parent", Linkname: "..", Typeflag: tar.TypeSymlink, }, &tar.Header{ Name: "subdir/parent/escapes", Linkname: "..", Typeflag: tar.TypeSymlink, }, }, err: `cannot extract "subdir/parent/escapes" through symlink`, }, { desc: "nested symlinks within symlinked dir", headers: []*tar.Header{ &tar.Header{ Name: "subdir/parent", Linkname: "..", Typeflag: tar.TypeSymlink, }, &tar.Header{ Name: "subdir/parent/otherdir/escapes", Linkname: "../..", Typeflag: tar.TypeSymlink, }, }, err: `cannot extract "subdir/parent/otherdir/escapes" through symlink`, }, { desc: "regular file through symlink", headers: []*tar.Header{ &tar.Header{ Name: "subdir/parent", Linkname: "..", Typeflag: tar.TypeSymlink, }, &tar.Header{ Name: "subdir/parent/file", Typeflag: tar.TypeReg, }, }, err: `cannot extract "subdir/parent/file" through symlink`, }, { desc: "directory through symlink", headers: []*tar.Header{ &tar.Header{ Name: "subdir/parent", Linkname: "..", Typeflag: tar.TypeSymlink, }, &tar.Header{ Name: "subdir/parent/dir", Typeflag: tar.TypeDir, }, }, err: `cannot extract "subdir/parent/dir" through symlink`, }, } for _, tc := range tcases { t.Run(tc.desc, func(t *testing.T) { dir, err := ioutil.TempDir("", "slug") if err != nil { t.Fatalf("err:%v", err) } defer os.RemoveAll(dir) in := filepath.Join(dir, "slug.tar.gz") // Create the output file wfh, err := os.Create(in) if err != nil { t.Fatalf("err: %v", err) } // Gzip compress all the output data gzipW := gzip.NewWriter(wfh) // Tar the file contents tarW := tar.NewWriter(gzipW) for _, hdr := range tc.headers { tarW.WriteHeader(hdr) } tarW.Close() gzipW.Close() wfh.Close() // Open the slug file for reading. fh, err := os.Open(in) if err != nil { t.Fatalf("err: %v", err) } // Create a dir to unpack into. dst, err := ioutil.TempDir(dir, "") if err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dst) // Now try unpacking it, which should fail var e *IllegalSlugError err = Unpack(fh, dst) if err == nil || !errors.As(err, &e) || !strings.Contains(err.Error(), tc.err) { t.Fatalf("expected *IllegalSlugError %v, got %T %v", tc.err, err, err) } }) } } func TestUnpackMaliciousFiles(t *testing.T) { tcases := []struct { desc string name string err string }{ { desc: "filename containing path traversal", name: "../../../../../../../../tmp/test", err: "invalid filename, traversal with \"..\" outside of current directory", }, { desc: "should fail before attempting to create directories", name: "../../../../../../../../Users/root", err: "invalid filename, traversal with \"..\" outside of current directory", }, } for _, tc := range tcases { t.Run(tc.desc, func(t *testing.T) { dir, err := ioutil.TempDir("", "slug") if err != nil { t.Fatalf("err:%v", err) } defer os.RemoveAll(dir) in := filepath.Join(dir, "slug.tar.gz") // Create the output file wfh, err := os.Create(in) if err != nil { t.Fatalf("err: %v", err) } // Gzip compress all the output data gzipW := gzip.NewWriter(wfh) // Tar the file contents tarW := tar.NewWriter(gzipW) hdr := &tar.Header{ Name: tc.name, Mode: 0600, Size: int64(0), } if err := tarW.WriteHeader(hdr); err != nil { t.Fatalf("err: %v", err) } if _, err := tarW.Write([]byte{}); err != nil { t.Fatalf("err: %v", err) } tarW.Close() gzipW.Close() wfh.Close() // Open the slug file for reading. fh, err := os.Open(in) if err != nil { t.Fatalf("err: %v", err) } // Create a dir to unpack into. dst, err := ioutil.TempDir(dir, "") if err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dst) // Now try unpacking it, which should fail var e *IllegalSlugError err = Unpack(fh, dst) if err == nil || !errors.As(err, &e) || !strings.Contains(err.Error(), tc.err) { t.Fatalf("expected *IllegalSlugError %v, got %T %v", tc.err, err, err) } }) } } func TestCheckFileMode(t *testing.T) { for _, tc := range []struct { desc string mode os.FileMode keep bool body bool }{ {"includes regular files", 0, true, true}, {"includes directories", os.ModeDir, true, false}, {"includes symlinks", os.ModeSymlink, true, false}, {"excludes unrecognized modes", os.ModeDevice, false, false}, } { t.Run(tc.desc, func(t *testing.T) { keep, body := checkFileMode(tc.mode) if keep != tc.keep || body != tc.body { t.Fatalf("expect (%v, %v), got (%v, %v)", tc.keep, tc.body, keep, body) } }) } } func TestNewPacker(t *testing.T) { for _, tc := range []struct { desc string options []PackerOption expect *Packer }{ { desc: "defaults", expect: &Packer{ dereference: false, applyTerraformIgnore: false, }, }, { desc: "enable dereferencing", options: []PackerOption{DereferenceSymlinks()}, expect: &Packer{ dereference: true, }, }, { desc: "apply .terraformignore", options: []PackerOption{ApplyTerraformIgnore()}, expect: &Packer{ applyTerraformIgnore: true, }, }, { desc: "multiple options", options: []PackerOption{ApplyTerraformIgnore(), DereferenceSymlinks()}, expect: &Packer{ dereference: true, applyTerraformIgnore: true, }, }, } { t.Run(tc.desc, func(t *testing.T) { p, err := NewPacker(tc.options...) if err != nil { t.Fatalf("err: %v", err) } if !reflect.DeepEqual(p, tc.expect) { t.Fatalf("\nexpect:\n%#v\n\nactual:\n%#v", p, tc.expect) } }) } } func verifyFile(t *testing.T, path string, mode os.FileMode, expect string) { fh, err := os.Open(path) if err != nil { t.Fatal(err) } defer fh.Close() info, err := fh.Stat() if err != nil { t.Fatal(err) } if !((mode == 0 && info.Mode().IsRegular()) || info.Mode()&mode == 0) { t.Fatalf("wrong file mode for %q", path) } if mode == os.ModeSymlink { if target, _ := os.Readlink(path); target != expect { t.Fatalf("expect link target %q, got %q", expect, target) } return } raw := make([]byte, info.Size()) if _, err := fh.Read(raw); err != nil { t.Fatal(err) } if result := string(raw); result != expect { t.Fatalf("bad content in file %q\n\nexpect:\n%#v\n\nactual:\n%#v", path, expect, result) } } func verifyPerms(t *testing.T, path string, expect os.FileMode) { fi, err := os.Stat(path) if err != nil { t.Fatal(err) } if perm := fi.Mode().Perm(); perm != expect { t.Fatalf("expect perms %o, got %o", expect, perm) } } go-slug-0.7.0/terraformignore.go000066400000000000000000000120201401620361300166160ustar00rootroot00000000000000package slug import ( "bufio" "fmt" "io" "os" "path/filepath" "regexp" "strings" "text/scanner" ) func parseIgnoreFile(rootPath string) []rule { // Look for .terraformignore at our root path/src file, err := os.Open(filepath.Join(rootPath, ".terraformignore")) defer file.Close() // If there's any kind of file error, punt and use the default ignore patterns if err != nil { // Only show the error debug if an error *other* than IsNotExist if !os.IsNotExist(err) { fmt.Fprintf(os.Stderr, "Error reading .terraformignore, default exclusions will apply: %v \n", err) } return defaultExclusions } return readRules(file) } func readRules(input io.Reader) []rule { rules := defaultExclusions scanner := bufio.NewScanner(input) scanner.Split(bufio.ScanLines) for scanner.Scan() { pattern := scanner.Text() // Ignore blank lines if len(pattern) == 0 { continue } // Trim spaces pattern = strings.TrimSpace(pattern) // Ignore comments if pattern[0] == '#' { continue } // New rule structure rule := rule{} // Exclusions if pattern[0] == '!' { rule.excluded = true pattern = pattern[1:] } // If it is a directory, add ** so we catch descendants if pattern[len(pattern)-1] == os.PathSeparator { pattern = pattern + "**" } // If it starts with /, it is absolute if pattern[0] == os.PathSeparator { pattern = pattern[1:] } else { // Otherwise prepend **/ pattern = "**" + string(os.PathSeparator) + pattern } rule.val = pattern rule.dirs = strings.Split(pattern, string(os.PathSeparator)) rules = append(rules, rule) } if err := scanner.Err(); err != nil { fmt.Fprintf(os.Stderr, "Error reading .terraformignore, default exclusions will apply: %v \n", err) return defaultExclusions } return rules } func matchIgnoreRule(path string, rules []rule) bool { matched := false path = filepath.FromSlash(path) for _, rule := range rules { match, _ := rule.match(path) if match { matched = !rule.excluded } } if matched { debug(true, path, "Skipping excluded path:", path) } return matched } type rule struct { val string // the value of the rule itself excluded bool // ! is present, an exclusion rule dirs []string // directories of the rule regex *regexp.Regexp // regular expression to match for the rule } func (r *rule) match(path string) (bool, error) { if r.regex == nil { if err := r.compile(); err != nil { return false, filepath.ErrBadPattern } } b := r.regex.MatchString(path) debug(false, path, path, r.regex, b) return b, nil } func (r *rule) compile() error { regStr := "^" pattern := r.val // Go through the pattern and convert it to a regexp. // Use a scanner to support utf-8 chars. var scan scanner.Scanner scan.Init(strings.NewReader(pattern)) sl := string(os.PathSeparator) escSL := sl if sl == `\` { escSL += `\` } for scan.Peek() != scanner.EOF { ch := scan.Next() if ch == '*' { if scan.Peek() == '*' { // is some flavor of "**" scan.Next() // Treat **/ as ** so eat the "/" if string(scan.Peek()) == sl { scan.Next() } if scan.Peek() == scanner.EOF { // is "**EOF" - to align with .gitignore just accept all regStr += ".*" } else { // is "**" // Note that this allows for any # of /'s (even 0) because // the .* will eat everything, even /'s regStr += "(.*" + escSL + ")?" } } else { // is "*" so map it to anything but "/" regStr += "[^" + escSL + "]*" } } else if ch == '?' { // "?" is any char except "/" regStr += "[^" + escSL + "]" } else if ch == '.' || ch == '$' { // Escape some regexp special chars that have no meaning // in golang's filepath.Match regStr += `\` + string(ch) } else if ch == '\\' { // escape next char. Note that a trailing \ in the pattern // will be left alone (but need to escape it) if sl == `\` { // On windows map "\" to "\\", meaning an escaped backslash, // and then just continue because filepath.Match on // Windows doesn't allow escaping at all regStr += escSL continue } if scan.Peek() != scanner.EOF { regStr += `\` + string(scan.Next()) } else { regStr += `\` } } else { regStr += string(ch) } } regStr += "$" re, err := regexp.Compile(regStr) if err != nil { return err } r.regex = re return nil } /* Default rules as they would appear in .terraformignore: .git/ .terraform/ !.terraform/modules/ */ var defaultExclusions = []rule{ { val: filepath.Join("**", ".git", "**"), excluded: false, }, { val: filepath.Join("**", ".terraform", "**"), excluded: false, }, { val: filepath.Join("**", ".terraform", "modules", "**"), excluded: true, }, } func debug(printAll bool, path string, message ...interface{}) { logLevel := os.Getenv("TF_IGNORE") == "trace" debugPath := os.Getenv("TF_IGNORE_DEBUG") isPath := debugPath != "" if isPath { isPath = strings.Contains(path, debugPath) } if logLevel { if printAll || isPath { fmt.Println(message...) } } } go-slug-0.7.0/terraformignore_test.go000066400000000000000000000041171401620361300176650ustar00rootroot00000000000000package slug import ( "testing" ) func TestTerraformIgnore(t *testing.T) { // path to directory without .terraformignore p := parseIgnoreFile("testdata/external-dir") if len(p) != 3 { t.Fatal("A directory without .terraformignore should get the default patterns") } // load the .terraformignore file's patterns ignoreRules := parseIgnoreFile("testdata/archive-dir") type file struct { // the actual path, should be file path format /dir/subdir/file.extension path string // should match match bool } paths := []file{ { path: ".terraform/", match: true, }, { path: "included.txt", match: false, }, { path: ".terraform/foo/bar", match: true, }, { path: ".terraform/foo/bar/more/directories/so/many", match: true, }, { path: ".terraform/foo/ignored-subdirectory/", match: true, }, { path: "baz.txt", match: true, }, { path: "parent/foo/baz.txt", match: true, }, { path: "parent/foo/bar.tf", match: true, }, { path: "parent/bar/bar.tf", match: false, }, // baz.txt is ignored, but a file name including it should not be { path: "something/with-baz.txt", match: false, }, { path: "something/baz.x", match: false, }, // Getting into * patterns { path: "foo/ignored-doc.md", match: true, }, // Should match [a-z] group { path: "bar/something-a.txt", match: true, }, // ignore sub- terraform.d paths { path: "some-module/terraform.d/x", match: true, }, // but not the root one { path: "terraform.d/", match: false, }, { path: "terraform.d/foo", match: false, }, // We ignore the directory, but a file of the same name could exist { path: "terraform.d", match: false, }, // boop.text is ignored everywhere { path: "baz/boop.txt", match: true, }, // except at current directory { path: "boop.txt", match: false, }, } for i, p := range paths { match := matchIgnoreRule(p.path, ignoreRules) if match != p.match { t.Fatalf("%s at index %d should be %t", p.path, i, p.match) } } } go-slug-0.7.0/testdata/000077500000000000000000000000001401620361300147005ustar00rootroot00000000000000go-slug-0.7.0/testdata/.DS_Store000066400000000000000000000140041401620361300163620ustar00rootroot00000000000000Bud1-ignor with-ignorelg1Scomp with-ignoremoDDblobzA with-ignoremodDblobzA with-ignoreph1Scomp  @ @ @ @ EDSDB ` @ @ @go-slug-0.7.0/testdata/archive-dir/000077500000000000000000000000001401620361300170755ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/.terraform/000077500000000000000000000000001401620361300211545ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/.terraform/file.txt000066400000000000000000000000001401620361300226220ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/.terraform/modules/000077500000000000000000000000001401620361300226245ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/.terraform/modules/README000066400000000000000000000001031401620361300234760ustar00rootroot00000000000000Keep this file and directory here to test if its properly ignored go-slug-0.7.0/testdata/archive-dir/.terraform/plugins/000077500000000000000000000000001401620361300226355ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/.terraform/plugins/README000066400000000000000000000001031401620361300235070ustar00rootroot00000000000000Keep this file and directory here to test if its properly ignored go-slug-0.7.0/testdata/archive-dir/.terraformignore000066400000000000000000000006251401620361300223060ustar00rootroot00000000000000# comments are ignored # extra spaces are irrelevant # ignore a file baz.txt # below is an empty line # ignore a directory terraform.d/ # exclude ignoring a directory at the root !/terraform.d/ # ignore a file at a subpath **/foo/bar.tf # ignore files with specific endings foo/*.md # character groups bar/something-[a-z].txt # ignore a file boop.txt # but not one at the current directory !/boop.txtgo-slug-0.7.0/testdata/archive-dir/.terraformrc000066400000000000000000000000001401620361300214120ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/bar.txt000066400000000000000000000000041401620361300203740ustar00rootroot00000000000000bar go-slug-0.7.0/testdata/archive-dir/baz.txt000066400000000000000000000000031401620361300204030ustar00rootroot00000000000000bazgo-slug-0.7.0/testdata/archive-dir/exe000077500000000000000000000000001401620361300175720ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/foo.terraform/000077500000000000000000000000001401620361300216605ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/foo.terraform/bar.txt000066400000000000000000000000001401620361300231530ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/foo.txt000077700000000000000000000000001401620361300245512../external-dir/foo.txtustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/sub/000077500000000000000000000000001401620361300176665ustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/sub/bar.txt000077700000000000000000000000001401620361300227062../bar.txtustar00rootroot00000000000000go-slug-0.7.0/testdata/archive-dir/sub/zip.txt000066400000000000000000000000041401620361300212230ustar00rootroot00000000000000zip go-slug-0.7.0/testdata/external-dir/000077500000000000000000000000001401620361300172765ustar00rootroot00000000000000go-slug-0.7.0/testdata/external-dir/foo.txt000066400000000000000000000000041401620361300206140ustar00rootroot00000000000000foo