diff --git a/.goreleaser.yml b/.goreleaser.yml index f4a0664..49c77aa 100644 --- a/.goreleaser.yml +++ b/.goreleaser.yml @@ -21,18 +21,18 @@ builds: mod_timestamp: '{{ .CommitTimestamp }}' ldflags: - >- - -X github.com/buttahtoast/subst/subst/cmd.Version={{ .Tag }} - -X github.com/buttahtoast/subst/subst/cmd.GitCommit={{ .Commit }} - -X github.com/buttahtoast/subst/subst/cmd.BuildDate={{ .Date }} + -X github.com/bedag/subst/subst/cmd.Version={{ .Tag }} + -X github.com/bedag/subst/subst/cmd.GitCommit={{ .Commit }} + -X github.com/bedag/subst/subst/cmd.BuildDate={{ .Date }} release: footer: | - **Full Changelog**: https://github.com/buttahtoast/{{ .ProjectName }}/compare/{{ .PreviousTag }}...{{ .Tag }} + **Full Changelog**: https://github.com/bedag/{{ .ProjectName }}/compare/{{ .PreviousTag }}...{{ .Tag }} * * * **Docker Images** - - `ghcr.io/buttahtoast/{{ .ProjectName }}:{{ .Tag }}` - - `ghcr.io/buttahtoast/{{ .ProjectName }}-cmp:{{ .Tag }}` + - `ghcr.io/bedag/{{ .ProjectName }}:{{ .Tag }}` + - `ghcr.io/bedag/{{ .ProjectName }}-cmp:{{ .Tag }}` checksum: name_template: 'checksums.txt' @@ -41,8 +41,8 @@ snapshot: name_template: "{{ .Tag }}-next" dockers: - image_templates: - - "ghcr.io/buttahtoast/{{ .ProjectName }}:{{ .Tag }}" - - "ghcr.io/buttahtoast/{{ .ProjectName }}:latest" + - "ghcr.io/bedag/{{ .ProjectName }}:{{ .Tag }}" + - "ghcr.io/bedag/{{ .ProjectName }}:latest" dockerfile: Dockerfile.goreleaser goos: linux goarch: amd64 @@ -56,14 +56,14 @@ dockers: - "--label=org.opencontainers.image.revision={{.FullCommit}}" - "--label=org.opencontainers.image.version={{.Version}}" - "--label=org.opencontainers.image.source={{.GitURL}}" - - "--label=org.opencontainers.image.vendor=Buttahtoast" + - "--label=org.opencontainers.image.vendor=Bedag" - "--label=org.opencontainers.image.licenses=Apache-2.0" - - "--label=org.opencontainers.image.source=https://github.com/butthatoast/subst" - - "--label=org.opencontainers.image.authors=Buttahtoast" - - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/buttahtoast/subst/main/README.md" - - "--label=io.artifacthub.package.logo-url=https://github.com/buttahtoast/subst/raw/main/img/subst.png" + - "--label=org.opencontainers.image.source=https://github.com/bedag/subst" + - "--label=org.opencontainers.image.authors=Bedag" + - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/bedag/subst/main/README.md" + - "--label=io.artifacthub.package.logo-url=https://github.com/bedag/subst/raw/main/img/subst.png" - "--label=io.artifacthub.package.license=Apache-2.0" - #- image_templates: [ "ghcr.io/buttahtoast/{{ .ProjectName }}:{{ .Tag }}" ] + #- image_templates: [ "ghcr.io/bedag/{{ .ProjectName }}:{{ .Tag }}" ] # dockerfile: Dockerfile # goos: linux # goarch: arm64 @@ -77,16 +77,16 @@ dockers: # - "--label=org.opencontainers.image.revision={{.FullCommit}}" # - "--label=org.opencontainers.image.version={{.Version}}" # - "--label=org.opencontainers.image.source={{.GitURL}}" - # - "--label=org.opencontainers.image.vendor=Buttahtoast" + # - "--label=org.opencontainers.image.vendor=Bedag" # - "--label=org.opencontainers.image.licenses=Apache-2.0" - # - "--label=org.opencontainers.image.source=https://github.com/butthatoast/subst" - # - "--label=org.opencontainers.image.authors=Buttahtoast" - # - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/buttahtoast/subst/main/README.md" - # - "--label=io.artifacthub.package.logo-url=https://github.com/buttahtoast/subst/raw/main/img/subst.png" + # - "--label=org.opencontainers.image.source=https://github.com/bedag/subst" + # - "--label=org.opencontainers.image.authors=Bedag" + # - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/bedag/subst/main/README.md" + # - "--label=io.artifacthub.package.logo-url=https://github.com/bedag/subst/raw/main/img/subst.png" # - "--label=io.artifacthub.package.license=Apache-2.0" - image_templates: - - "ghcr.io/buttahtoast/{{ .ProjectName }}-cmp:{{ .Tag }}" - - "ghcr.io/buttahtoast/{{ .ProjectName }}-cmp:latest" + - "ghcr.io/bedag/{{ .ProjectName }}-cmp:{{ .Tag }}" + - "ghcr.io/bedag/{{ .ProjectName }}-cmp:latest" dockerfile: argocd-cmp/Dockerfile.goreleaser goos: linux goarch: amd64 @@ -100,17 +100,17 @@ dockers: - "--label=org.opencontainers.image.revision={{.FullCommit}}" - "--label=org.opencontainers.image.version={{.Version}}" - "--label=org.opencontainers.image.source={{.GitURL}}" - - "--label=org.opencontainers.image.vendor=Buttahtoast" + - "--label=org.opencontainers.image.vendor=Bedag" - "--label=org.opencontainers.image.licenses=Apache-2.0" - - "--label=org.opencontainers.image.source=https://github.com/butthatoast/subst" - - "--label=org.opencontainers.image.authors=Buttahtoast" - - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/buttahtoast/subst/main/README.md" - - "--label=io.artifacthub.package.logo-url=https://github.com/buttahtoast/subst/raw/main/img/subst.png" + - "--label=org.opencontainers.image.source=https://github.com/bedag/subst" + - "--label=org.opencontainers.image.authors=Bedag" + - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/bedag/subst/main/README.md" + - "--label=io.artifacthub.package.logo-url=https://github.com/bedag/subst/raw/main/img/subst.png" - "--label=io.artifacthub.package.license=Apache-2.0" extra_files: - argocd-cmp/cmp.yaml - argocd-cmp/entrypoint.sh - #- image_templates: [ "ghcr.io/buttahtoast/{{ .ProjectName }}-cmp:{{ .Tag }}" ] + #- image_templates: [ "ghcr.io/bedag/{{ .ProjectName }}-cmp:{{ .Tag }}" ] # dockerfile: Dockerfile.argo-cmp # goos: linux # goarch: arm64 @@ -124,12 +124,12 @@ dockers: # - "--label=org.opencontainers.image.revision={{.FullCommit}}" # - "--label=org.opencontainers.image.version={{.Version}}" # - "--label=org.opencontainers.image.source={{.GitURL}}" - # - "--label=org.opencontainers.image.vendor=Buttahtoast" + # - "--label=org.opencontainers.image.vendor=Bedag" # - "--label=org.opencontainers.image.licenses=Apache-2.0" - # - "--label=org.opencontainers.image.source=https://github.com/butthatoast/subst" - # - "--label=org.opencontainers.image.authors=Buttahtoast" - # - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/buttahtoast/subst/main/README.md" - # - "--label=io.artifacthub.package.logo-url=https://github.com/buttahtoast/subst/raw/main/img/subst.png" + # - "--label=org.opencontainers.image.source=https://github.com/bedag/subst" + # - "--label=org.opencontainers.image.authors=Bedag" + # - "--label=io.artifacthub.package.readme-url=https://raw.githubusercontent.com/bedag/subst/main/README.md" + # - "--label=io.artifacthub.package.logo-url=https://github.com/bedag/subst/raw/main/img/subst.png" # - "--label=io.artifacthub.package.license=Apache-2.0" # extra_files: # - argocd-cmp/cmp.yaml @@ -183,11 +183,11 @@ docker_signs: - --yes #brews: # - tap: -# owner: buttahtoast +# owner: bedag # name: subst # branch: main # license: Apache-2.0 -# homepage: "github.com/buttahtoast/subst" +# homepage: "github.com/bedag/subst" # description: "subst - Substitution based on Kustomize" # post_install: | # puts '🌈 subst installed 🌈' \ No newline at end of file diff --git a/CODEOWNERS b/CODEOWNERS index 99107db..69b1262 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1 +1 @@ -* @buttahtoast +* @bedag/sre diff --git a/Dockerfile.argo-cmp b/Dockerfile.argo-cmp index 43a0f50..382f8d3 100644 --- a/Dockerfile.argo-cmp +++ b/Dockerfile.argo-cmp @@ -7,7 +7,7 @@ ARG TARGETARCH WORKDIR /app/ ADD . . -RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-w -s -X github.com/buttahtoast/subst/subst/cmd.Version={{ .Tag }} -X github.com/buttahtoast/subst/subst/cmd.GitCommit={{ .Commit }} -X github.com/buttahtoast/subst/subst/cmd.BuildDate={{ .Date }}" -o subst ./subst/main.go +RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-w -s -X github.com/bedag/subst/subst/cmd.Version={{ .Tag }} -X github.com/bedag/subst/subst/cmd.GitCommit={{ .Commit }} -X github.com/bedag/subst/subst/cmd.BuildDate={{ .Date }}" -o subst ./subst/main.go FROM --platform=${TARGETPLATFORM:-linux/amd64} scratch diff --git a/LICENSE b/LICENSE index 5786ce6..7052823 100644 --- a/LICENSE +++ b/LICENSE @@ -187,6 +187,7 @@ identification within third-party archives. Copyright [2020] Clastix Labs + Copyright [2024] Bedag Informatik AG Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/Makefile b/Makefile index 28bec00..37c2bb6 100644 --- a/Makefile +++ b/Makefile @@ -19,8 +19,8 @@ LOCAL_PLATFORM := linux/$(GOARCH) TARGET_PLATFORMS ?= $(LOCAL_PLATFORM) VERSION ?= $$(git describe --abbrev=0 --tags --match "v*") -IMG ?= ghcr.io/buttahtoast/subst:$(VERSION) -PLUGIN_IMG ?= ghcr.io/buttahtoast/subst-cmp:$(VERSION) +IMG ?= ghcr.io/bedag/subst:$(VERSION) +PLUGIN_IMG ?= ghcr.io/bedag/subst-cmp:$(VERSION) default: help @@ -102,7 +102,7 @@ kind-up: @echo "Building kubernetes $${KIND_K8S_VERSION:-v1.25.0}..." @kind create cluster --name $(K3S_NAME) --image kindest/node:$${KIND_K8S_VERSION:-v1.25.0} --wait=120s -kind-load-image: PLUGIN_IMG = ghcr.io/buttahtoast/subst-cmp:local +kind-load-image: PLUGIN_IMG = ghcr.io/bedag/subst-cmp:local kind-load-image: docker-build-cmp @echo "Loading image into cluster..." @kind load docker-image ${PLUGIN_IMG} --name $(K3S_NAME) diff --git a/README.md b/README.md index cfa4698..eaa9641 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ Install it with the [ArgoCD community chart](https://github.com/argoproj/argo-he extraContainers: - name: cmp-subst args: [/var/run/argocd/argocd-cmp-server] - image: ghcr.io/buttahtoast/subst-cmp:v0.3.0 + image: ghcr.io/bedag/subst-cmp:v0.3.0 imagePullPolicy: Always securityContext: allowPrivilegeEscalation: false @@ -197,18 +197,18 @@ For all decryptors you can create a kubernetes secret, which contains the privat **Brew** ```bash -brew tap buttahtoast/subst +brew tap bedag/subst ``` **Docker** ```bash -docker run -it ghcr.io/buttahtoast/subst -h +docker run -it ghcr.io/bedag/subst -h ``` **Github Releases** -https://github.com/buttahtoast/subst/releases +https://github.com/bedag/subst/releases ## ArgoCD Plugin diff --git a/go.mod b/go.mod index 2ad126f..f207a61 100644 --- a/go.mod +++ b/go.mod @@ -1,20 +1,46 @@ -module github.com/buttahtoast/subst +module github.com/bedag/subst go 1.19 require ( + cloud.google.com/go/kms v1.15.1 + filippo.io/age v1.1.1 + github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 + github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.1 + github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0 + github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0 github.com/BurntSushi/toml v1.2.1 github.com/MakeNowJust/heredoc v1.0.0 github.com/Masterminds/sprig/v3 v3.2.3 - github.com/buttahtoast/pkg/decryptors v0.0.0-20240118231345-2f3b4888024a + github.com/Shopify/ejson v1.4.1 + github.com/aws/aws-sdk-go v1.44.321 + github.com/aws/aws-sdk-go-v2 v1.18.1 + github.com/aws/aws-sdk-go-v2/config v1.18.27 + github.com/aws/aws-sdk-go-v2/credentials v1.13.26 + github.com/aws/aws-sdk-go-v2/service/kms v1.22.2 + github.com/aws/aws-sdk-go-v2/service/sts v1.19.2 + github.com/dimchansky/utfbom v1.1.1 github.com/geofffranks/simpleyaml v0.0.0-20161109204137-c9320f076de5 github.com/geofffranks/spruce v1.29.0 + github.com/hashicorp/vault/api v1.9.2 + github.com/onsi/gomega v1.27.8 + github.com/ory/dockertest/v3 v3.10.0 github.com/sirupsen/logrus v1.9.3 github.com/spf13/cobra v1.6.1 github.com/spf13/pflag v1.0.5 github.com/spf13/viper v1.14.0 github.com/starkandwayne/goutils v0.0.0-20190115202530-896b8a6904be + github.com/stretchr/testify v1.8.4 + go.mozilla.org/sops/v3 v3.7.3 + golang.org/x/net v0.14.0 + google.golang.org/api v0.136.0 + google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5 + google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577 + google.golang.org/grpc v1.57.0 + google.golang.org/protobuf v1.31.0 gopkg.in/yaml.v2 v2.4.0 + gopkg.in/yaml.v3 v3.0.1 + k8s.io/apimachinery v0.27.4 k8s.io/client-go v0.27.4 sigs.k8s.io/kustomize/api v0.13.2 sigs.k8s.io/kustomize/kyaml v0.14.1 @@ -25,14 +51,10 @@ require ( cloud.google.com/go/compute v1.23.0 // indirect cloud.google.com/go/compute/metadata v0.2.3 // indirect cloud.google.com/go/iam v1.1.1 // indirect - cloud.google.com/go/kms v1.15.1 // indirect - filippo.io/age v1.1.1 // indirect github.com/Azure/azure-sdk-for-go v68.0.0+incompatible // indirect - github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.1 // indirect - github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.3.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/internal v1.3.0 // indirect - github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0 // indirect github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v0.8.0 // indirect + github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect github.com/Azure/go-autorest v14.2.0+incompatible // indirect github.com/Azure/go-autorest/autorest v0.11.29 // indirect github.com/Azure/go-autorest/autorest/adal v0.9.23 // indirect @@ -47,29 +69,29 @@ require ( github.com/Knetic/govaluate v3.0.0+incompatible // indirect github.com/Masterminds/goutils v1.1.1 // indirect github.com/Masterminds/semver/v3 v3.2.0 // indirect + github.com/Microsoft/go-winio v0.6.0 // indirect + github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 // indirect github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 // indirect - github.com/Shopify/ejson v1.4.1 // indirect - github.com/aws/aws-sdk-go v1.44.321 // indirect - github.com/aws/aws-sdk-go-v2 v1.18.1 // indirect - github.com/aws/aws-sdk-go-v2/config v1.18.27 // indirect - github.com/aws/aws-sdk-go-v2/credentials v1.13.26 // indirect github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.13.4 // indirect github.com/aws/aws-sdk-go-v2/internal/configsources v1.1.34 // indirect github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.4.28 // indirect github.com/aws/aws-sdk-go-v2/internal/ini v1.3.35 // indirect github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.9.28 // indirect - github.com/aws/aws-sdk-go-v2/service/kms v1.22.2 // indirect github.com/aws/aws-sdk-go-v2/service/sso v1.12.12 // indirect github.com/aws/aws-sdk-go-v2/service/ssooidc v1.14.12 // indirect - github.com/aws/aws-sdk-go-v2/service/sts v1.19.2 // indirect github.com/aws/smithy-go v1.13.5 // indirect github.com/blang/semver v3.5.1+incompatible // indirect github.com/cenkalti/backoff/v3 v3.2.2 // indirect + github.com/cenkalti/backoff/v4 v4.1.3 // indirect github.com/cloudflare/circl v1.3.3 // indirect github.com/cloudfoundry-community/vaultkv v0.5.0 // indirect + github.com/containerd/continuity v0.3.0 // indirect github.com/cpuguy83/go-md2man/v2 v2.0.2 // indirect github.com/davecgh/go-spew v1.1.1 // indirect - github.com/dimchansky/utfbom v1.1.1 // indirect + github.com/docker/cli v20.10.17+incompatible // indirect + github.com/docker/docker v20.10.7+incompatible // indirect + github.com/docker/go-connections v0.4.0 // indirect + github.com/docker/go-units v0.4.0 // indirect github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad // indirect github.com/emicklei/go-restful/v3 v3.10.2 // indirect github.com/evanphx/json-patch v5.6.0+incompatible // indirect @@ -104,7 +126,6 @@ require ( github.com/hashicorp/go-secure-stdlib/strutil v0.1.2 // indirect github.com/hashicorp/go-sockaddr v1.0.2 // indirect github.com/hashicorp/hcl v1.0.0 // indirect - github.com/hashicorp/vault/api v1.9.2 // indirect github.com/howeyc/gopass v0.0.0-20210920133722-c8aef6fb66ef // indirect github.com/huandu/xstrings v1.3.3 // indirect github.com/imdario/mergo v0.3.16 // indirect @@ -123,16 +144,21 @@ require ( github.com/mitchellh/go-wordwrap v1.0.1 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect github.com/mitchellh/reflectwalk v1.0.2 // indirect + github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/onsi/ginkgo v1.16.5 // indirect github.com/onsi/ginkgo/v2 v2.11.0 // indirect + github.com/opencontainers/go-digest v1.0.0 // indirect + github.com/opencontainers/image-spec v1.0.2 // indirect + github.com/opencontainers/runc v1.1.5 // indirect github.com/pelletier/go-toml v1.9.5 // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect github.com/ryanuber/go-glob v1.0.0 // indirect github.com/shopspring/decimal v1.2.0 // indirect @@ -140,33 +166,29 @@ require ( github.com/spf13/cast v1.5.0 // indirect github.com/spf13/jwalterweatherman v1.1.0 // indirect github.com/subosito/gotenv v1.4.1 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect github.com/xlab/treeprint v1.1.0 // indirect github.com/ziutek/utils v0.0.0-20190626152656-eb2a3b364d6c // indirect go.mozilla.org/gopgagent v0.0.0-20170926210634-4d7ea76ff71a // indirect - go.mozilla.org/sops/v3 v3.7.3 // indirect go.opencensus.io v0.24.0 // indirect go.starlark.net v0.0.0-20221205180719-3fd0dac74452 // indirect golang.org/x/crypto v0.12.0 // indirect - golang.org/x/net v0.14.0 // indirect + golang.org/x/mod v0.10.0 // indirect golang.org/x/oauth2 v0.11.0 // indirect golang.org/x/sync v0.3.0 // indirect golang.org/x/sys v0.11.0 // indirect golang.org/x/term v0.11.0 // indirect golang.org/x/text v0.12.0 // indirect golang.org/x/time v0.3.0 // indirect - google.golang.org/api v0.136.0 // indirect + golang.org/x/tools v0.9.3 // indirect google.golang.org/appengine v1.6.7 // indirect - google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20230803162519-f966b187b2e5 // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20230807174057-1744710a1577 // indirect - google.golang.org/grpc v1.57.0 // indirect - google.golang.org/protobuf v1.31.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect gopkg.in/ini.v1 v1.67.0 // indirect gopkg.in/urfave/cli.v1 v1.20.0 // indirect - gopkg.in/yaml.v3 v3.0.1 // indirect k8s.io/api v0.27.4 // indirect - k8s.io/apimachinery v0.27.4 // indirect k8s.io/klog/v2 v2.100.1 // indirect k8s.io/kube-openapi v0.0.0-20230501164219-8b0f38b5fd1f // indirect k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect diff --git a/go.sum b/go.sum index a601402..678d09f 100644 --- a/go.sum +++ b/go.sum @@ -47,7 +47,8 @@ cloud.google.com/go/storage v1.14.0/go.mod h1:GrKmX003DSIwi9o29oFT7YDnHYwZoctc3f dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU= filippo.io/age v1.1.1 h1:pIpO7l151hCnQ4BdyBujnGP2YlUo0uj6sAVNHGBvXHg= filippo.io/age v1.1.1/go.mod h1:l03SrzDUrBkdBx8+IILdnn2KZysqQdbEBUQ4p3sqEQE= -github.com/AdaLogics/go-fuzz-headers v0.0.0-20230106234847-43070de90fa1 h1:EKPd1INOIyr5hWOWhvpmQpY6tKjeG0hT1s3AMC/9fic= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 h1:bvDV9vkmnHYOMsOr4WLk+Vo07yKIzd94sVoIqshQ4bU= +github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible h1:fcYLmCpyNYRnvJbPerq7U0hS+6+I79yEDJBqVNcqUzU= github.com/Azure/azure-sdk-for-go v68.0.0+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc= github.com/Azure/azure-sdk-for-go/sdk/azcore v1.6.1 h1:SEy2xmstIphdPwNBUi7uhvjyjhVKISfwjfOJmuy7kg4= @@ -60,7 +61,9 @@ github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0 h1:yfJe15a github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys v1.0.0/go.mod h1:Q28U+75mpCaSCDowNEmhIo/rmgdkqmkmzI7N6TGR4UY= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v0.8.0 h1:T028gtTPiYt/RMUfs8nVsAL7FDQrfLlrm/NnRG/zcC4= github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v0.8.0/go.mod h1:cw4zVQgBby0Z5f2v0itn6se2dDP17nTjbZFXW5uPyHA= -github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0= +github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX56iTiv29bbRTIsUNlaFfuhWRQBWjQdVyAevI8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 h1:UQHMgLO+TxOElx5B5HZ4hJQsoJ/PvUvKRhJHDQXO8P8= +github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E= github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK/vTfRHdAubSIPRgs= github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24= github.com/Azure/go-autorest/autorest v0.11.24/go.mod h1:G6kyRlFnTuSbEYkQGawPfsCswgme4iYf6rfSKUDzbCc= @@ -104,8 +107,10 @@ github.com/Masterminds/semver/v3 v3.2.0 h1:3MEsd0SM6jqZojhjLWWeBY+Kcjy9i6MQAeY7Y github.com/Masterminds/semver/v3 v3.2.0/go.mod h1:qvl/7zhW3nngYb5+80sSMF+FG2BjYrf8m9wsX0PNOMQ= github.com/Masterminds/sprig/v3 v3.2.3 h1:eL2fZNezLomi0uOLqjQoN6BfsDD+fyLtgbJMAj9n6YA= github.com/Masterminds/sprig/v3 v3.2.3/go.mod h1:rXcFaZ2zZbLRJv/xSysmlgIM1u11eBaRMhvYXJNkGuM= -github.com/Microsoft/go-winio v0.6.1 h1:9/kr64B9VUZrLm5YYwbGtUJnMgqWVOdUAXu6Migciow= +github.com/Microsoft/go-winio v0.6.0 h1:slsWYD/zyx7lCXoZVlvQrj0hPTM1HI4+v1sIda2yDvg= +github.com/Microsoft/go-winio v0.6.0/go.mod h1:cTAf44im0RAYeL23bpB+fzCyDH2MJiz2BO69KH/soAE= github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5 h1:TngWCqHvy9oXAN6lEVMRuU21PR1EtLVZJmdB18Gu3Rw= +github.com/Nvveen/Gotty v0.0.0-20120604004816-cd527374f1e5/go.mod h1:lmUJ/7eu/Q8D7ML55dXQrVaamCz2vxCfdQBasLZfHKk= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95 h1:KLq8BE0KwCL+mmXnjLWEAOYO+2l2AE4YMmqG1ZpZHBs= github.com/ProtonMail/go-crypto v0.0.0-20230717121422-5aa5874ade95/go.mod h1:EjAoLdwvbIOoOQr3ihjnSoLZRtE8azugULFRteWMNc0= @@ -145,19 +150,20 @@ github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kB github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk= github.com/buger/jsonparser v1.1.1/go.mod h1:6RYKKt7H4d4+iWqouImQ9R2FZql3VbhNgx27UK13J/0= -github.com/buttahtoast/pkg/decryptors v0.0.0-20240118231345-2f3b4888024a h1:Xx8bxfr6LTwMNu/az6y1GkiENz2EHtBTt9cBPcDB9Lk= -github.com/buttahtoast/pkg/decryptors v0.0.0-20240118231345-2f3b4888024a/go.mod h1:Bj+vC+2JLzaiTvScwi9ZSLZUGDFxEF4NAwPnD4hc3Mk= github.com/bwesterb/go-ristretto v1.2.3/go.mod h1:fUIoIZaG73pV5biE2Blr2xEzDoMj7NFEuV9ekS419A0= github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4= github.com/cenkalti/backoff/v3 v3.2.2 h1:cfUAAO3yvKMYKPrvhDuHSwQnhZNk/RMHKdZqKTxfm6M= github.com/cenkalti/backoff/v3 v3.2.2/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs= -github.com/cenkalti/backoff/v4 v4.2.1 h1:y4OZtCnogmCPw98Zjyt5a6+QwPLGkiQsYW5oUqylYbM= +github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= +github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc= github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/checkpoint-restore/go-criu/v5 v5.3.0/go.mod h1:E/eQpaFtUKGOOSEBZgmKAcn+zUUwWxqcaKZlF54wK8E= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/cilium/ebpf v0.7.0/go.mod h1:/oI2+1shJiTGAMgl6/RgJr36Eo1jzrRcAWbcXO2usCA= github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= github.com/cloudflare/circl v1.3.3 h1:fE/Qz0QdIGqeWfnwq0RE0R7MI51s0M2E4Ga9kq5AEMs= github.com/cloudflare/circl v1.3.3/go.mod h1:5XYMA4rFBvNIrhs50XuiBJ15vF2pZn4nnUKZrLbUZFA= @@ -171,21 +177,31 @@ github.com/cncf/xds/go v0.0.0-20210312221358-fbca930ec8ed/go.mod h1:eXthEFrGJvWH github.com/cncf/xds/go v0.0.0-20210805033703-aa0b78936158/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= -github.com/containerd/continuity v0.4.1 h1:wQnVrjIyQ8vhU2sgOiL5T07jo+ouqc2bnKsv5/EqGhU= +github.com/containerd/console v1.0.3/go.mod h1:7LqA/THxQ86k76b8c/EMSiaJ3h1eZkMkXar0TQ1gf3U= +github.com/containerd/continuity v0.3.0 h1:nisirsYROK15TAMVukJOUyGJjz4BNQJBVsNvAXZJ/eg= +github.com/containerd/continuity v0.3.0/go.mod h1:wJEAIwKOm/pBZuBd0JmeTvnLquTB1Ag8espWhkykbPM= +github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc= +github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/cyphar/filepath-securejoin v0.2.4 h1:Ugdm7cg7i6ZK6x3xDF1oEu1nfkyfH53EtKeQYTC3kyg= +github.com/creack/pty v1.1.11 h1:07n33Z8lZxZ2qwegKbObQohDhXDQxiMMz1NOUGYlesw= +github.com/creack/pty v1.1.11/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/cyphar/filepath-securejoin v0.2.3/go.mod h1:aPGpWjXOXUn2NCNjFvBE6aRxGGx79pTxQpKOJNYHHl4= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dimchansky/utfbom v1.1.1 h1:vV6w1AhK4VMnhBno/TPVCoK9U/LP0PkLCS9tbxHdi/U= github.com/dimchansky/utfbom v1.1.1/go.mod h1:SxdoEBH5qIqFocHMyGOXVAybYJdr71b1Q/j0mACtrfE= github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI= -github.com/docker/cli v24.0.5+incompatible h1:WeBimjvS0eKdH4Ygx+ihVq1Q++xg36M/rMi4aXAvodc= -github.com/docker/docker v24.0.5+incompatible h1:WmgcE4fxyI6EEXxBRxsHnZXrO1pQ3smi0k/jho4HLeY= +github.com/docker/cli v20.10.17+incompatible h1:eO2KS7ZFeov5UJeaDmIs1NFEDRf32PaqRpvoEkKBy5M= +github.com/docker/cli v20.10.17+incompatible/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= +github.com/docker/docker v20.10.7+incompatible h1:Z6O9Nhsjv+ayUEeI1IojKbYcsGdgYSNqxe1s2MYzUhQ= +github.com/docker/docker v20.10.7+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk= github.com/docker/go-connections v0.4.0 h1:El9xVISelRB7BuFusrZozjnkIM5YnzCViNKohAFqRJQ= -github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4= +github.com/docker/go-connections v0.4.0/go.mod h1:Gbd7IOopHjR8Iph03tsViu4nIes5XhDvyHbTtUxmeec= +github.com/docker/go-units v0.4.0 h1:3uh0PgVws3nIA0Q+MwDC8yjEPf9zjRfZZWXZYDct3Tw= +github.com/docker/go-units v0.4.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE= github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad h1:Qk76DOWdOp+GlyDKBAG3Klr9cn7N+LcYc82AZ2S7+cA= github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad/go.mod h1:mPKfmRa823oBIgl2r20LeMSpTAteW5j7FLkc0vjmzyQ= @@ -205,6 +221,7 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= github.com/flowstack/go-jsonschema v0.1.1/go.mod h1:yL7fNggx1o8rm9RlgXv7hTBWxdBM0rVwpMwimd3F3N0= +github.com/frankban/quicktest v1.11.3/go.mod h1:wRf/ReqHper53s+kmmSZizM8NamnL3IM0I9ntUbOk+k= github.com/frankban/quicktest v1.14.3 h1:FJKSZTDHjyhriyC81FLQ0LY93eSai0ZyR/ZIkd3ZUKE= github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ= @@ -235,9 +252,12 @@ github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= github.com/go-openapi/swag v0.22.4 h1:QLMzNJnMGPRNDCbySlcj1x01tzU8/9LTTL9hZZZogBU= github.com/go-openapi/swag v0.22.4/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14= +github.com/go-sql-driver/mysql v1.6.0 h1:BCTh4TKNUYmOmMUcQ3IipzF5prigylS7XXjEkfCHuOE= github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE= github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI= github.com/go-test/deep v1.0.2 h1:onZX1rnHT3Wv6cqNgYyFOOlgVKJrksuCMCRvJStbMYw= +github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.0.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg= @@ -422,7 +442,9 @@ github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RR github.com/mitchellh/reflectwalk v1.0.0/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= github.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ= github.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw= -github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0= +github.com/moby/sys/mountinfo v0.5.0/go.mod h1:3bMD3Rg+zkqx8MRYPi7Pyb0Ie97QEBmdxbhnCLlSvSU= +github.com/moby/term v0.0.0-20201216013528-df9cb8a40635 h1:rzf0wL0CHVc8CEsgyygG0Mn9CNCCPZqOPaz8RiiHYQk= +github.com/moby/term v0.0.0-20201216013528-df9cb8a40635/go.mod h1:FBS0z0QWA44HXygs7VXDUOGoN/1TV3RuWkLO04am3wc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= @@ -430,6 +452,7 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= +github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A= @@ -444,18 +467,26 @@ github.com/onsi/ginkgo/v2 v2.11.0 h1:WgqUCUt/lT6yXoQ8Wef0fsNn5cAuMK7+KT9UFRz2tcU github.com/onsi/ginkgo/v2 v2.11.0/go.mod h1:ZhrRA5XmEE3x3rhlzamx/JJvujdZoJ2uvgI7kR0iZvM= github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY= github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo= -github.com/onsi/gomega v1.27.10 h1:naR28SdDFlqrG6kScpT8VWpu1xWY5nJRCF3XaYyBjhI= +github.com/onsi/gomega v1.27.8 h1:gegWiwZjBsf2DgiSbf5hpokZ98JVDMcWkUiigk6/KXc= +github.com/onsi/gomega v1.27.8/go.mod h1:2J8vzI/s+2shY9XHRApDkdgPo1TKT7P2u6fXeJKFnNQ= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= +github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.0.2 h1:9yCKha/T5XdGtO0q9Q9a6T5NUCsTn/DrBg0D7ufOcFM= -github.com/opencontainers/runc v1.1.8 h1:zICRlc+C1XzivLc3nzE+cbJV4LIi8tib6YG0MqC6OqA= +github.com/opencontainers/image-spec v1.0.2/go.mod h1:BtxoFyWECRxE4U/7sNtV5W15zMzWCbyJoFRP3s7yZA0= +github.com/opencontainers/runc v1.1.5 h1:L44KXEpKmfWDcS02aeGm8QNTFXTo2D+8MYGDIJ/GDEs= +github.com/opencontainers/runc v1.1.5/go.mod h1:1J5XiS+vdZ3wCyZybsuxXZWGrgSr8fFJHLXuG2PsnNg= +github.com/opencontainers/runtime-spec v1.0.3-0.20210326190908-1c3f411f0417/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/selinux v1.10.0/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= github.com/ory/dockertest v3.3.5+incompatible h1:iLLK6SQwIhcbrG783Dghaaa3WPzGc+4Emza6EbVUUGA= github.com/ory/dockertest/v3 v3.10.0 h1:4K3z2VMe8Woe++invjaTB7VRyQXQy5UY+loujO4aNE4= +github.com/ory/dockertest/v3 v3.10.0/go.mod h1:nr57ZbRWMqfsdGdFNLHz5jjNdDb7VVFnzAeW1n5N1Lg= github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= github.com/pelletier/go-toml v1.9.5/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8 h1:KoWmjvw+nsYOo29YJK9vDA65RGE3NrOnUtO7a+RF9HU= github.com/pkg/browser v0.0.0-20210911075715-681adbf594b8/go.mod h1:HKlIX3XHQyzLZPlr7++PzdhaXEj94dEiJgZDTsxEqUI= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/sftp v1.13.1/go.mod h1:3HaPG6Dq1ILlpPZRO0HVMrsydcdLt6HRDccSgb87qRg= @@ -466,14 +497,18 @@ github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1: github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= +github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= +github.com/seccomp/libseccomp-golang v0.9.2-0.20220502022130-f33da4d89646/go.mod h1:JA8cRccbGaA1s33RQf7Y1+q9gHmZX1yB/z9WDN1C6fg= github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0= github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ= github.com/shopspring/decimal v1.2.0/go.mod h1:DKyhrW/HYNuLGql+MJL6WCR6knT2jwCFRcu2hWCYk4o= +github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/smartystreets/assertions v1.2.1 h1:bKNHfEv7tSIjZ8JbKaFjzFINljxG4lzZvmHUnElzOIg= @@ -488,6 +523,7 @@ github.com/spf13/cobra v1.6.1 h1:o94oiPyS4KD1mPy2fmcYYHHfCxLqYjJOhGsCHFZtEzA= github.com/spf13/cobra v1.6.1/go.mod h1:IOw/AERYS7UzyrGinqmz6HLUo219MORXGxhbaJUqzrY= github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk= github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo= +github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.14.0 h1:Rg7d3Lo706X9tHsJMUjdiwMpHB7W8WnSVOssIY+JElU= @@ -510,10 +546,15 @@ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/subosito/gotenv v1.4.1 h1:jyEFiXpy21Wm81FBN71l9VoMMV8H8jG+qIK3GCpY6Qs= github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0= +github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= +github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE= +github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f h1:J9EGpcZtP0E/raorCMxlFGSTBrsSlaDGf3jU/qvAE2c= github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= -github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= @@ -595,7 +636,8 @@ golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= -golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.10.0 h1:lFO9qtOdlre5W1jxS3r/4szv2/6iXxScdzjoBMXNhYk= +golang.org/x/mod v0.10.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= @@ -674,11 +716,14 @@ golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190726091711-fc99dfbffb4e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191001151750-bb3f8db39f24/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191204072324-ce4227a45e2e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -695,6 +740,7 @@ golang.org/x/sys v0.0.0-20200511232937-7e40ca221e25/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200523222454-059865788121/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200803210538-64077c9b5642/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200831180312-196b9ba8737a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200905004654-be1d3432aa8f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -702,6 +748,7 @@ golang.org/x/sys v0.0.0-20201201145000-ef89a241ccb3/go.mod h1:h1NjWce9XRLGQEsW7w golang.org/x/sys v0.0.0-20210104204734-6f8348627aad/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210225134936-a50acf3fe073/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= @@ -710,6 +757,10 @@ golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20210514084401-e8d321eab015/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20210616045830-e2b7044e8c71/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210906170528-6f6e22806c34/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211116061358-0a5406a5449c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= @@ -762,6 +813,7 @@ golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBn golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= +golang.org/x/tools v0.0.0-20190624222133-a101b041ded4/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc= golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= @@ -803,7 +855,8 @@ golang.org/x/tools v0.0.0-20210108195828-e2f9c7f1fc8e/go.mod h1:emZCQorbCU4vsT4f golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= -golang.org/x/tools v0.12.0 h1:YW6HUoUmYBpwSgyaGaZq1fHjrBjX1rlpZ54T6mu2kss= +golang.org/x/tools v0.9.3 h1:Gn1I8+64MsuTb/HpH+LmQtNas23LhUVr3rYZ0eKuaMM= +golang.org/x/tools v0.9.3/go.mod h1:owI94Op576fPu3cIGQeHs3joujW/2Oc6MtlxbF5dfNc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= @@ -944,6 +997,9 @@ gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gotest.tools v2.2.0+incompatible h1:VsBPFP1AI068pPrMxtb/S8Zkgf9xEmTLJjfM+P5UIEo= +gotest.tools/v3 v3.0.2/go.mod h1:3SzNCllyD9/Y+b5r9JIKQ474KzkZyqLqEfYqMsX94Bk= +gotest.tools/v3 v3.3.0 h1:MfDY1b1/0xN1CyMlQDac0ziEy9zJQd9CXBRRDHw2jJo= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= diff --git a/hack/ draft.sh b/hack/ draft.sh index 5f42f43..6e167c7 100644 --- a/hack/ draft.sh +++ b/hack/ draft.sh @@ -110,7 +110,7 @@ cleanup() { } trap cleanup EXIT -# https://github.com/buttahtoast/ejsonMerger/blob/master/ejson-merger.sh +# https://github.com/bedag/ejsonMerger/blob/master/ejson-merger.sh # Main Function main() { diff --git a/hack/argocd-values.yaml b/hack/argocd-values.yaml index 9c800df..8a6b9dd 100644 --- a/hack/argocd-values.yaml +++ b/hack/argocd-values.yaml @@ -44,7 +44,7 @@ repoServer: name: env-tmp - name: cmp-subst command: [/var/run/argocd/argocd-cmp-server] # Entrypoint should be Argo CD lightweight CMP server i.e. argocd-cmp-server - image: ghcr.io/buttahtoast/subst-cmp:local + image: ghcr.io/bedag/subst-cmp:local imagePullPolicy: Never securityContext: runAsUser: 999 diff --git a/internal/decryptors/LICENSE b/internal/decryptors/LICENSE new file mode 100644 index 0000000..99989d1 --- /dev/null +++ b/internal/decryptors/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + Copyright [2024] Bedag Informatik AG + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/internal/decryptors/NOTICE b/internal/decryptors/NOTICE new file mode 100644 index 0000000..079f4b2 --- /dev/null +++ b/internal/decryptors/NOTICE @@ -0,0 +1 @@ +Source: https://github.com/bedag/pkg diff --git a/internal/decryptors/decryptor.go b/internal/decryptors/decryptor.go new file mode 100644 index 0000000..dbc4762 --- /dev/null +++ b/internal/decryptors/decryptor.go @@ -0,0 +1,21 @@ +package decryptors + +import ( + "context" + + "k8s.io/client-go/kubernetes" +) + +type DecryptorConfig struct { + // Decryption is skipped, but decryption metadata is removed + SkipDecrypt bool +} + +type Decryptor interface { + // Checks if given content is encrypted by the decryptor interface + IsEncrypted(data []byte) (bool, error) + // Reads the given content, based on the decrypter config attempts to decrypt + Decrypt(data []byte) (content map[string]interface{}, err error) + // Read Private Keys from kubernetes secret + KeysFromSecret(secretName string, namespace string, client *kubernetes.Clientset, ctx context.Context) (err error) +} diff --git a/internal/decryptors/ejson/ejson.go b/internal/decryptors/ejson/ejson.go new file mode 100644 index 0000000..260e5e3 --- /dev/null +++ b/internal/decryptors/ejson/ejson.go @@ -0,0 +1,204 @@ +package ejson + +import ( + "bytes" + "context" + "encoding/hex" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "github.com/Shopify/ejson" + "github.com/bedag/subst/internal/decryptors" + "k8s.io/client-go/kubernetes" +) + +const ( + // PublicKeyField is the field name of the public key in the ejson + PublicKeyField = "_public_key" + // DecryptionEjsonExt is the extension of the file containing an ejson prviate key + // file + DecryptionEjsonExt = ".key" +) + +type EjsonDecryptor struct { + // stores all private keys for the decryptor + keys []string + // directory to search for ejson keys on disk + keyDirectory string + // Interface decryptor config + Config decryptors.DecryptorConfig +} + +// Initialize a new EJSON Decryptor +func NewEJSONDecryptor(config decryptors.DecryptorConfig, keyDirectory string, keys ...string) (*EjsonDecryptor, error) { + init := &EjsonDecryptor{ + keys: []string{}, + keyDirectory: keyDirectory, + Config: config, + } + + if len(keys) > 0 { + for _, key := range keys { + init.AddKey(key) + } + } + + err := init.findPrivateKeysFromDisk() + if err != nil { + return nil, err + } + + return init, nil +} + +func (d *EjsonDecryptor) IsEncrypted(data []byte) (bool, error) { + if len(data) == 0 { + return false, nil + } + + var content map[string]interface{} + content, err := decryptors.UnmarshalJSONorYAML(data) + if err != nil { + return false, err + } + + f := content[PublicKeyField] + if f == nil || f == "" { + return false, nil + } + return true, nil +} + +func (d *EjsonDecryptor) AddKey(key string) error { + privkeyBytes, err := hex.DecodeString(strings.TrimSpace(key)) + if err != nil { + return err + } + + if len(privkeyBytes) != 32 { + return fmt.Errorf("invalid private key length: %v", privkeyBytes) + } + + d.keys = append(d.keys, strings.TrimSpace(key)) + return nil +} + +// Load Keys from Kubernetes Secret +// Only keys within the secret with the extension .key +// will be loaded as ejson private keys +func (d *EjsonDecryptor) KeysFromSecret(secretName string, namespace string, client *kubernetes.Clientset, ctx context.Context) (err error) { + keySecret, err := client.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) + if k8serrors.IsNotFound(err) { + return &decryptors.MissingKubernetesSecret{Secret: secretName, Namespace: namespace} + } else if err != nil { + return err + } + + // Exract all keys from secret + for name, value := range keySecret.Data { + if filepath.Ext(name) == DecryptionEjsonExt { + err := d.AddKey(string(value)) + if err != nil { + return fmt.Errorf("failed to import data from %s decryption Secret '%s': %w", name, secretName, err) + } + } + } + + return nil +} + +// Read an ejson file +// Skip decryption still removes the publicKeyField +func (d *EjsonDecryptor) Decrypt(data []byte) (content map[string]interface{}, err error) { + if !d.Config.SkipDecrypt { + data, err = d.read(data) + if err != nil { + return nil, err + } + } + + content, err = decryptors.UnmarshalJSONorYAML(data) + if err != nil { + return nil, fmt.Errorf("HELLO to unmarshal ejson: %w", err) + //return nil, err + } + + // Remove Public Key information + delete(content, PublicKeyField) + + return content, err +} + +// Attempts to decrypt an ejson file with the given keys +func (d *EjsonDecryptor) read(data []byte) (content []byte, err error) { + var outputBuffer bytes.Buffer + + decrypted := false + f := bytes.NewReader(data) + if !d.Config.SkipDecrypt { + + // Try all loaded keys + for key := range d.keys { + err = ejson.Decrypt(f, &outputBuffer, "", string(d.keys[key])) + if err != nil { + continue + } else { + decrypted = true + break + } + } + + // Check if file was decrypted (and must be) + if !decrypted { + e := fmt.Errorf("could not decrypt with given keys") + // This error happens, if the file is not properly encrypted (or not encrypted at all) + // Considered an error. + if err != nil && err.Error() == "invalid message format" { + e = fmt.Errorf("content is not encrypted with ejson (%s)", err) + } + return nil, e + } + } + + if outputBuffer.Bytes() != nil { + return outputBuffer.Bytes(), nil + } + + return data, nil +} + +func (d *EjsonDecryptor) findPrivateKeysFromDisk() error { + if _, err := os.Stat(d.keyDirectory); os.IsNotExist(err) { + return nil + } + files, err := os.ReadDir(d.keyDirectory) + if err != nil { + return err + } + + // Regular expression to match filenames of format [32]byte + // Considering filenames to be hex encoded strings + r := regexp.MustCompile("^[a-fA-F0-9]{64}$") + + for _, file := range files { + if !file.IsDir() && r.MatchString(file.Name()) { + // Step 4: Read the content of the matching files + content, err := os.ReadFile(d.keyDirectory + "/" + file.Name()) + if err != nil { + return err + } + err = d.AddKey(string(content)) + if err != nil { + return err + } + } + } + + return nil +} diff --git a/internal/decryptors/ejson/ejson_test.go b/internal/decryptors/ejson/ejson_test.go new file mode 100644 index 0000000..1342962 --- /dev/null +++ b/internal/decryptors/ejson/ejson_test.go @@ -0,0 +1,154 @@ +package ejson + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + + "github.com/bedag/subst/internal/decryptors" + "github.com/stretchr/testify/assert" +) + +// Generate KeyPair For Testing +// $ ejson keygen +// Public Key: +// 9474413baa1422b613beed7fd2ba8201d433758dc94aaee4d385d0c948176c4d +// Private Key: +// 65b2f2060e6e3a976456c5a7cbcca3f15715eb1d9e0fe54174fa7b36aca1f50e + +// Example data; this will need to be valid for your use case. +const mockPrivateKey = "65b2f2060e6e3a976456c5a7cbcca3f15715eb1d9e0fe54174fa7b36aca1f50e" + +const EncryptedEjsonContent = `{ + "_public_key": "9474413baa1422b613beed7fd2ba8201d433758dc94aaee4d385d0c948176c4d", + "data": { + "database_password": "EJ[1:CuPlhIlHfYXnHQZA4lcF5yIL2ELZp6qcbOfHEWoQegs=:ZPXRiyzY2sCSggghVuOFfM0vHzqY7hSf:BZyLg1crv4xkgGL1JyYRnt3pj3bttOUW2QIo]", + "database_user": "EJ[1:CuPlhIlHfYXnHQZA4lcF5yIL2ELZp6qcbOfHEWoQegs=:QrrHbddJpx/eP3t4sMNCT6OeZi7MPq0m:y+I+og1GqEas4r/4hV5vzbXpG9JA2elo45Ws]" + } +}` +const DecryptedEjsonContent = `{ + "data": { + "database_password": "VERY_SECRET", + "database_user": "MUCH_SECURE" + } +}` +const FaultyEjsonContent = `{ + "_public_key": "9474413baa1422b613beed7fd2ba8201d433758dc94aaee4d385d0c948176c4d", + "data": { + "faulty"="json" + } +}` + +func testdataPath() string { + basePath, _ := os.Getwd() + hackDirPath := filepath.Join(basePath, "testdata") + return hackDirPath +} + +func testkeydirPath() string { + hackDirPath := filepath.Join(testdataPath(), "keydir") + return hackDirPath +} + +func TestAddKey(t *testing.T) { + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{}, "") + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + err = decryptor.AddKey(mockPrivateKey) + + assert.NoError(t, err, "Expected no error when adding a private key") + assert.Contains(t, decryptor.keys, mockPrivateKey, "Expected the key to be added to the keys slice") +} + +func TestMultipleKeyFromDiskAddition(t *testing.T) { + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{}, testkeydirPath()) + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + + files, _ := os.ReadDir(testkeydirPath()) + for _, file := range files { + if !file.IsDir() { + content, err := os.ReadFile(filepath.Join(testkeydirPath(), file.Name())) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + keyContent := string(content) + assert.Contains(t, decryptor.keys, keyContent, "Expected the key to be added to the keys slice") + } + } + expectedSize := 3 + assert.Len(t, decryptor.keys, expectedSize, "Expected array to have size %d, but it has size %d.", expectedSize, len(decryptor.keys)) +} + +func TestMultipleKeyAddition(t *testing.T) { + var keysFromFile []string + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{}, testkeydirPath()) + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + + files, _ := os.ReadDir(testkeydirPath()) + for _, file := range files { + if !file.IsDir() { + content, err := os.ReadFile(filepath.Join(testkeydirPath(), file.Name())) + if err != nil { + t.Fatalf("Failed to read file: %v", err) + } + keyContent := string(content) + keysFromFile = append(keysFromFile, keyContent) + decryptor.AddKey(keyContent) + } + } + + // Test at the end if all keys are added + for _, key := range keysFromFile { + assert.Contains(t, decryptor.keys, key, "Expected the key to be added to the keys slice") + } +} + +func TestAddFaultyKey(t *testing.T) { + faultyKey := "65b2f2060e6e3a9764b1d9e0fe54174fa7b36aca1f50e" + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{}, "") + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + err = decryptor.AddKey(faultyKey) + + assert.Error(t, err, "Expected error when adding a faulty private key") + assert.NotContains(t, decryptor.keys, faultyKey, "Did not expect the key to be added to the keys slice") +} + +func TestIsEncrypted(t *testing.T) { + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{}, "") + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + isEncrypted, err := decryptor.IsEncrypted([]byte(EncryptedEjsonContent)) + + assert.NoError(t, err, "Expected no error when checking if content is encrypted") + assert.True(t, isEncrypted, "Expected the content to be identified as encrypted") +} + +func TestDecrypt(t *testing.T) { + decryptor, err := NewEJSONDecryptor(decryptors.DecryptorConfig{SkipDecrypt: false}, "") + if err != nil { + t.Fatalf("Failed to create decryptor: %v", err) + } + _ = decryptor.AddKey(mockPrivateKey) // Assuming the key is valid and is added without errors. + + decryptedContent, err := decryptor.Decrypt([]byte(EncryptedEjsonContent)) + + assert.NoError(t, err, "Expected no error during decryption") + assert.NotNil(t, decryptedContent, "Expected decrypted content to be non-nil") + + // Convert expected JSON content to map + var expectedMap map[string]interface{} + err = json.Unmarshal([]byte(DecryptedEjsonContent), &expectedMap) + assert.NoError(t, err, "Failed to unmarshal test data expected content") + + // Compare the decrypted content with the expected value + assert.Equal(t, expectedMap, decryptedContent, "The decrypted content does not match the expected value.") +} diff --git a/internal/decryptors/ejson/testdata/decrypted.ejson b/internal/decryptors/ejson/testdata/decrypted.ejson new file mode 100644 index 0000000..2245f37 --- /dev/null +++ b/internal/decryptors/ejson/testdata/decrypted.ejson @@ -0,0 +1,6 @@ +{ + "data": { + "database_password": "VERY_SECRET", + "database_user": "MUCH_SECURE" + } +} \ No newline at end of file diff --git a/internal/decryptors/ejson/testdata/encrypted.ejson b/internal/decryptors/ejson/testdata/encrypted.ejson new file mode 100644 index 0000000..4fc670b --- /dev/null +++ b/internal/decryptors/ejson/testdata/encrypted.ejson @@ -0,0 +1,7 @@ +{ + "_public_key": "9474413baa1422b613beed7fd2ba8201d433758dc94aaee4d385d0c948176c4d", + "data": { + "database_password": "EJ[1:CuPlhIlHfYXnHQZA4lcF5yIL2ELZp6qcbOfHEWoQegs=:ZPXRiyzY2sCSggghVuOFfM0vHzqY7hSf:BZyLg1crv4xkgGL1JyYRnt3pj3bttOUW2QIo]", + "database_user": "EJ[1:CuPlhIlHfYXnHQZA4lcF5yIL2ELZp6qcbOfHEWoQegs=:QrrHbddJpx/eP3t4sMNCT6OeZi7MPq0m:y+I+og1GqEas4r/4hV5vzbXpG9JA2elo45Ws]" + } +} \ No newline at end of file diff --git a/internal/decryptors/ejson/testdata/faulty.ejson b/internal/decryptors/ejson/testdata/faulty.ejson new file mode 100644 index 0000000..d1037ac --- /dev/null +++ b/internal/decryptors/ejson/testdata/faulty.ejson @@ -0,0 +1,6 @@ +{ + "_public_key": "9474413baa1422b613beed7fd2ba8201d433758dc94aaee4d385d0c948176c4d", + "data": { + "faulty"="json" + } +} \ No newline at end of file diff --git a/internal/decryptors/ejson/testdata/keydir/3846f7a7b9771fc3eae3fabae76bc29f9867709a79cfcffeeb1932e1a01e5c07 b/internal/decryptors/ejson/testdata/keydir/3846f7a7b9771fc3eae3fabae76bc29f9867709a79cfcffeeb1932e1a01e5c07 new file mode 100644 index 0000000..a272c97 --- /dev/null +++ b/internal/decryptors/ejson/testdata/keydir/3846f7a7b9771fc3eae3fabae76bc29f9867709a79cfcffeeb1932e1a01e5c07 @@ -0,0 +1 @@ +43fa792284b8514ba60b8976a62b8515f44fa85b78e6a08db62390046ca67519 \ No newline at end of file diff --git a/internal/decryptors/ejson/testdata/keydir/544f44d4ca525b1a497e39a1e8bb85147749f38d3f38ac25a70940827d0e8c3f b/internal/decryptors/ejson/testdata/keydir/544f44d4ca525b1a497e39a1e8bb85147749f38d3f38ac25a70940827d0e8c3f new file mode 100644 index 0000000..9611294 --- /dev/null +++ b/internal/decryptors/ejson/testdata/keydir/544f44d4ca525b1a497e39a1e8bb85147749f38d3f38ac25a70940827d0e8c3f @@ -0,0 +1 @@ +576b9b53f0d75327f0e18d0fcc0b87465861a2a189d674767c00b11ebd5d2fc3 \ No newline at end of file diff --git a/internal/decryptors/ejson/testdata/keydir/8555475bf15814d4ccaa080cddbee899c78e0944e4c660f06d291396807cc579 b/internal/decryptors/ejson/testdata/keydir/8555475bf15814d4ccaa080cddbee899c78e0944e4c660f06d291396807cc579 new file mode 100644 index 0000000..8ea4f6c --- /dev/null +++ b/internal/decryptors/ejson/testdata/keydir/8555475bf15814d4ccaa080cddbee899c78e0944e4c660f06d291396807cc579 @@ -0,0 +1 @@ +648793447d42b9ff3e0a072d29d7d0184c72be18938df45aed5c9c6b3f0f0cd2 \ No newline at end of file diff --git a/internal/decryptors/sops/kustomize-controller/LICENSE b/internal/decryptors/sops/kustomize-controller/LICENSE new file mode 100644 index 0000000..a612ad9 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/LICENSE @@ -0,0 +1,373 @@ +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. diff --git a/internal/decryptors/sops/kustomize-controller/README.md b/internal/decryptors/sops/kustomize-controller/README.md new file mode 100644 index 0000000..e69de29 diff --git a/internal/decryptors/sops/kustomize-controller/age/keysource.go b/internal/decryptors/sops/kustomize-controller/age/keysource.go new file mode 100644 index 0000000..c63d368 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/age/keysource.go @@ -0,0 +1,217 @@ +// Copyright (C) 2021 The Mozilla SOPS authors +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package age + +import ( + "bytes" + "fmt" + "io" + "strings" + + "filippo.io/age" + "filippo.io/age/armor" +) + +// MasterKey is an age key used to Encrypt and Decrypt SOPS' data key. +// +// Adapted from https://github.com/mozilla/sops/blob/v3.7.2/age/keysource.go +// to be able to have fine-grain control over the used decryption keys +// without relying on the existence of file(path)s. +type MasterKey struct { + // Identities contains the set of Bench32-encoded age identities used to + // Decrypt. + // They are lazy-loaded using MasterKeyFromIdentities, or on first + // Decrypt(). + // In addition to using this field, ParsedIdentities.ApplyToMasterKey() can + // be used to parse and lazy-load identities. + Identities []string + // Recipient contains the Bench32-encoded age public key used to Encrypt. + Recipient string + // EncryptedKey contains the SOPS data key encrypted with age. + EncryptedKey string + + // parsedIdentities contains a slice of parsed age identities. + // It is used to lazy-load the Identities at-most once. + // It can also be injected by a (local) keyservice.KeyServiceServer using + // ParsedIdentities.ApplyToMasterKey(). + parsedIdentities []age.Identity + // parsedRecipient contains a parsed age public key. + // It is used to lazy-load the Recipient at-most once. + parsedRecipient *age.X25519Recipient +} + +// MasterKeyFromRecipient takes a Bech32-encoded age public key, parses it, and +// returns a new MasterKey. +func MasterKeyFromRecipient(recipient string) (*MasterKey, error) { + parsedRecipient, err := parseRecipient(recipient) + if err != nil { + return nil, err + } + return &MasterKey{ + Recipient: recipient, + parsedRecipient: parsedRecipient, + }, nil +} + +// MasterKeyFromIdentities takes a set if Bech32-encoded age identities, parses +// them, and returns a new MasterKey. +func MasterKeyFromIdentities(identities ...string) (*MasterKey, error) { + parsedIdentities, err := parseIdentities(identities...) + if err != nil { + return nil, err + } + return &MasterKey{ + Identities: identities, + parsedIdentities: parsedIdentities, + }, nil +} + +// ParsedIdentities contains a set of parsed age identities. +// It allows for creating a (local) keyservice.KeyServiceServer which parses +// identities only once, to then inject them using ApplyToMasterKey() for all +// requests. +type ParsedIdentities []age.Identity + +// Import attempts to parse the given identities, to then add them to itself. +// It returns any parsing error. +// A single identity argument is allowed to be a multiline string containing +// multiple identities. Empty lines and lines starting with "#" are ignored. +// It is not thread safe, and parallel importing would better be done by +// parsing (using age.ParseIdentities) and appending to the slice yourself, in +// combination with e.g. a sync.Mutex. +func (i *ParsedIdentities) Import(identity ...string) error { + identities, err := parseIdentities(identity...) + if err != nil { + return fmt.Errorf("failed to parse and add to age identities: %w", err) + } + *i = append(*i, identities...) + return nil +} + +// ApplyToMasterKey configures the ParsedIdentities on the provided key. +func (i ParsedIdentities) ApplyToMasterKey(key *MasterKey) { + key.parsedIdentities = i +} + +// Encrypt takes a SOPS data key, encrypts it with the Recipient, and stores +// the result in the EncryptedKey field. +func (key *MasterKey) Encrypt(dataKey []byte) error { + if key.parsedRecipient == nil { + parsedRecipient, err := parseRecipient(key.Recipient) + if err != nil { + return err + } + key.parsedRecipient = parsedRecipient + } + + var buffer bytes.Buffer + aw := armor.NewWriter(&buffer) + w, err := age.Encrypt(aw, key.parsedRecipient) + if err != nil { + return fmt.Errorf("failed to create writer for encrypting sops data key with age: %w", err) + } + if _, err := w.Write(dataKey); err != nil { + return fmt.Errorf("failed to encrypt sops data key with age: %w", err) + } + if err := w.Close(); err != nil { + return fmt.Errorf("failed to close writer for encrypting sops data key with age: %w", err) + } + if err := aw.Close(); err != nil { + return fmt.Errorf("failed to close armored writer: %w", err) + } + + key.SetEncryptedDataKey(buffer.Bytes()) + return nil +} + +// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been +// encrypted yet. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// EncryptedDataKey returns the encrypted SOPS data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// SetEncryptedDataKey sets the encrypted SOPS data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// Decrypt decrypts the EncryptedKey with the (parsed) Identities and returns +// the result. +func (key *MasterKey) Decrypt() ([]byte, error) { + if len(key.parsedIdentities) == 0 && len(key.Identities) > 0 { + parsedIdentities, err := parseIdentities(key.Identities...) + if err != nil { + return nil, err + } + key.parsedIdentities = parsedIdentities + } + + src := bytes.NewReader([]byte(key.EncryptedKey)) + ar := armor.NewReader(src) + r, err := age.Decrypt(ar, key.parsedIdentities...) + if err != nil { + return nil, fmt.Errorf("failed to create reader for decrypting sops data key with age: %w", err) + } + + var b bytes.Buffer + if _, err := io.Copy(&b, r); err != nil { + return nil, fmt.Errorf("failed to copy age decrypted data into bytes.Buffer: %w", err) + } + return b.Bytes(), nil +} + +// NeedsRotation returns whether the data key needs to be rotated or not. +func (key *MasterKey) NeedsRotation() bool { + return false +} + +// ToString converts the key to a string representation. +func (key *MasterKey) ToString() string { + return key.Recipient +} + +// ToMap converts the MasterKey to a map for serialization purposes. +func (key *MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["recipient"] = key.Recipient + out["enc"] = key.EncryptedKey + return out +} + +// parseRecipient attempts to parse a string containing an encoded age public +// key. +func parseRecipient(recipient string) (*age.X25519Recipient, error) { + parsedRecipient, err := age.ParseX25519Recipient(recipient) + if err != nil { + return nil, fmt.Errorf("failed to parse input as Bech32-encoded age public key: %w", err) + } + return parsedRecipient, nil +} + +// parseIdentities attempts to parse the string set of encoded age identities. +// A single identity argument is allowed to be a multiline string containing +// multiple identities. Empty lines and lines starting with "#" are ignored. +func parseIdentities(identity ...string) ([]age.Identity, error) { + var identities []age.Identity + for _, i := range identity { + parsed, err := age.ParseIdentities(strings.NewReader(i)) + if err != nil { + return nil, err + } + identities = append(identities, parsed...) + } + return identities, nil +} diff --git a/internal/decryptors/sops/kustomize-controller/age/keysource_test.go b/internal/decryptors/sops/kustomize-controller/age/keysource_test.go new file mode 100644 index 0000000..b32588c --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/age/keysource_test.go @@ -0,0 +1,327 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package age + +import ( + "testing" + + fuzz "github.com/AdaLogics/go-fuzz-headers" + . "github.com/onsi/gomega" + "go.mozilla.org/sops/v3/age" +) + +const ( + mockRecipient string = "age1lzd99uklcjnc0e7d860axevet2cz99ce9pq6tzuzd05l5nr28ams36nvun" + mockIdentity string = "AGE-SECRET-KEY-1G0Q5K9TV4REQ3ZSQRMTMG8NSWQGYT0T7TZ33RAZEE0GZYVZN0APSU24RK7" + + // mockUnrelatedIdentity is not actually utilized in tests, but confirms we + // iterate over all available identities. + mockUnrelatedIdentity string = "AGE-SECRET-KEY-1432K5YRNSC44GC4986NXMX6GVZ52WTMT9C79CLUVWYY4DKDHD5JSNDP4MC" + + // mockEncryptedKey equals to "data" when decrypted with mockIdentity. + mockEncryptedKey string = `-----BEGIN AGE ENCRYPTED FILE----- +YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSBvY2t2NkdLUGRvY3l2OGNy +MVJWcUhCOEZrUG8yeCtnRnhxL0I5NFk4YjJFCmE4SVQ3MEdyZkFqRWpSa2F0NVhF +VDUybzBxdS9nSGpHSVRVMUI0UEVqZkkKLS0tIGJjeGhNQ0Y5L2VZRVVYSm90djFF +bzdnQ3UwTGljMmtrbWNMV1MxYkFzUFUK4xjOZOTGdcbzuwUY/zeBXhcF+Md3e5PQ +EylloI7MNGbadPGb +-----END AGE ENCRYPTED FILE-----` +) + +var ( + mockIdentities = []string{ + mockUnrelatedIdentity, + mockIdentity, + } +) + +func TestMasterKeyFromRecipient(t *testing.T) { + g := NewWithT(t) + + got, err := MasterKeyFromRecipient(mockRecipient) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(got).ToNot(BeNil()) + g.Expect(got.Recipient).To(Equal(mockRecipient)) + g.Expect(got.parsedRecipient).ToNot(BeNil()) + g.Expect(got.parsedIdentities).To(BeEmpty()) + + got, err = MasterKeyFromRecipient("invalid") + g.Expect(err).To(HaveOccurred()) + g.Expect(got).To(BeNil()) +} + +func TestMasterKeyFromIdentities(t *testing.T) { + g := NewWithT(t) + + got, err := MasterKeyFromIdentities(mockIdentities...) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(got).ToNot(BeNil()) + g.Expect(got.Identities).To(HaveLen(2)) + g.Expect(got.Identities).To(ContainElements(mockIdentities)) + g.Expect(got.parsedIdentities).To(HaveLen(2)) + + got, err = MasterKeyFromIdentities("invalid") + g.Expect(err).To(HaveOccurred()) + g.Expect(got).To(BeNil()) +} + +func TestParsedIdentities_Import(t *testing.T) { + g := NewWithT(t) + + i := make(ParsedIdentities, 0) + g.Expect(i.Import(mockIdentities...)).To(Succeed()) + g.Expect(i).To(HaveLen(2)) + + g.Expect(i.Import("invalid")).To(HaveOccurred()) + g.Expect(i).To(HaveLen(2)) +} + +func TestParsedIdentities_ApplyToMasterKey(t *testing.T) { + g := NewWithT(t) + + i := make(ParsedIdentities, 0) + g.Expect(i.Import(mockIdentities...)).To(Succeed()) + + key := &MasterKey{} + i.ApplyToMasterKey(key) + g.Expect(key.parsedIdentities).To(BeEquivalentTo(i)) +} + +func TestMasterKey_Encrypt(t *testing.T) { + mockParsedRecipient, _ := parseRecipient(mockRecipient) + + tests := []struct { + name string + key *MasterKey + wantErr bool + }{ + { + name: "recipient", + key: &MasterKey{ + Recipient: mockRecipient, + }, + }, + { + name: "parsed recipient", + key: &MasterKey{ + parsedRecipient: mockParsedRecipient, + }, + }, + { + name: "invalid recipient", + key: &MasterKey{ + Recipient: "invalid", + }, + wantErr: true, + }, + { + name: "parsed recipient and invalid recipient", + key: &MasterKey{ + Recipient: "invalid", + parsedRecipient: mockParsedRecipient, + }, + // This should pass, confirming parsedRecipient > Recipient + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + err := tt.key.Encrypt([]byte("data")) + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(tt.key.EncryptedKey).To(BeEmpty()) + return + } + + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(tt.key.EncryptedKey).ToNot(BeEmpty()) + g.Expect(tt.key.EncryptedKey).To(ContainSubstring("AGE ENCRYPTED FILE")) + }) + } +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + dataKey := []byte("foo") + + encryptKey := &MasterKey{ + Recipient: mockRecipient, + } + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + t.Setenv(age.SopsAgeKeyEnv, mockIdentity) + decryptKey := &age.MasterKey{ + EncryptedKey: encryptKey.EncryptedKey, + } + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptIfNeeded(t *testing.T) { + g := NewWithT(t) + + key, err := MasterKeyFromRecipient(mockRecipient) + g.Expect(err).ToNot(HaveOccurred()) + + g.Expect(key.EncryptIfNeeded([]byte("data"))).To(Succeed()) + + encryptedKey := key.EncryptedKey + g.Expect(encryptedKey).To(ContainSubstring("AGE ENCRYPTED FILE")) + + g.Expect(key.EncryptIfNeeded([]byte("some other data"))).To(Succeed()) + g.Expect(key.EncryptedKey).To(Equal(encryptedKey)) +} + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{EncryptedKey: "some key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_Decrypt(t *testing.T) { + parsedIdentities, _ := parseIdentities(mockIdentities...) + + tests := []struct { + name string + key *MasterKey + wantErr bool + }{ + { + name: "identities", + key: &MasterKey{ + Identities: mockIdentities, + EncryptedKey: mockEncryptedKey, + }, + }, + { + name: "parsed identities", + key: &MasterKey{ + EncryptedKey: mockEncryptedKey, + parsedIdentities: parsedIdentities, + }, + }, + { + name: "no identities", + key: &MasterKey{ + Identities: []string{}, + EncryptedKey: mockEncryptedKey, + }, + wantErr: true, + }, + { + name: "invalid identity", + key: &MasterKey{ + Identities: []string{"invalid"}, + EncryptedKey: mockEncryptedKey, + }, + wantErr: true, + }, + { + name: "invalid encrypted key", + key: &MasterKey{ + Identities: mockIdentities, + EncryptedKey: "invalid", + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + data, err := tt.key.Decrypt() + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(data).To(BeNil()) + return + } + + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(data).To(Equal([]byte("data"))) + }) + } +} + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + dataKey := []byte("foo") + + encryptKey := &age.MasterKey{ + Recipient: mockRecipient, + } + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + decryptKey := &MasterKey{ + Identities: []string{mockIdentity}, + EncryptedKey: encryptKey.EncryptedKey, + } + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + encryptKey, err := MasterKeyFromRecipient(mockRecipient) + g.Expect(err).ToNot(HaveOccurred()) + + data := []byte("some secret data") + g.Expect(encryptKey.Encrypt(data)).To(Succeed()) + g.Expect(encryptKey.EncryptedKey).ToNot(BeEmpty()) + + decryptKey, err := MasterKeyFromIdentities(mockIdentity) + g.Expect(err).ToNot(HaveOccurred()) + + decryptKey.EncryptedKey = encryptKey.EncryptedKey + decryptedData, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decryptedData).To(Equal(data)) +} + +func TestMasterKey_ToString(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{Recipient: mockRecipient} + g.Expect(key.ToString()).To(Equal(key.Recipient)) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{ + Recipient: mockRecipient, + Identities: mockIdentities, // must never be included + EncryptedKey: "some-encrypted-key", + } + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "recipient": mockRecipient, + "enc": key.EncryptedKey, + })) +} + +func Fuzz_Age(f *testing.F) { + f.Fuzz(func(t *testing.T, receipt, identities string, seed, data []byte) { + fc := fuzz.NewConsumer(seed) + masterKey := MasterKey{} + + if err := fc.GenerateStruct(&masterKey); err != nil { + return + } + + _ = masterKey.Encrypt(data) + _ = masterKey.EncryptIfNeeded(data) + _, _ = MasterKeyFromRecipient(receipt) + _, _ = MasterKeyFromIdentities(identities) + }) +} diff --git a/internal/decryptors/sops/kustomize-controller/awskms/keysource.go b/internal/decryptors/sops/kustomize-controller/awskms/keysource.go new file mode 100644 index 0000000..c287ad6 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/awskms/keysource.go @@ -0,0 +1,291 @@ +/* +Copyright (C) 2022 The Flux authors + +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 https://mozilla.org/MPL/2.0/. +*/ + +package awskms + +import ( + "context" + "fmt" + "os" + "regexp" + "strings" + "time" + + "encoding/base64" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/kms" + "github.com/aws/aws-sdk-go-v2/service/sts" + "sigs.k8s.io/yaml" +) + +const ( + // arnRegex matches an AWS ARN. + // valid ARN example: arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48 + arnRegex = `^arn:aws[\w-]*:kms:(.+):[0-9]+:(key|alias)/.+$` + // stsSessionRegex matches an AWS STS session name. + // valid STS session examples: john_s, sops@42WQm042 + stsSessionRegex = "[^a-zA-Z0-9=,.@-_]+" + // kmsTTL is the duration after which a MasterKey requires rotation. + kmsTTL = time.Hour * 24 * 30 * 6 + // roleSessionNameLengthLimit is the AWS role session name length limit. + roleSessionNameLengthLimit = 64 +) + +// MasterKey is an AWS KMS key used to encrypt and decrypt sops' data key. +// Adapted from: https://github.com/mozilla/sops/blob/v3.7.2/kms/keysource.go#L39 +// Modified to accept custom static credentials as opposed to using env vars by default +// and use aws-sdk-go-v2 instead of aws-sdk-go being used in upstream. +type MasterKey struct { + // AWS Role ARN associated with the KMS key. + Arn string + // AWS Role ARN used to assume a role through AWS STS. + Role string + // EncryptedKey stores the data key in it's encrypted form. + EncryptedKey string + // CreationDate is when this MasterKey was created. + CreationDate time.Time + // EncryptionContext provides additional context about the data key. + // Ref: https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#encrypt_context + EncryptionContext map[string]string + // AWSProfile is the profile to use for loading configuration and credentials. + AwsProfile string + + // credentialsProvider is used to configure the AWS config with the + // necessary credentials. + credentialsProvider aws.CredentialsProvider + + // epResolver can be used to override the endpoint the AWS client resolves + // to by default. This is mostly used for testing purposes as it can not be + // injected using e.g. an environment variable. The field is not publicly + // exposed, nor configurable. + epResolver aws.EndpointResolverWithOptions +} + +// CredsProvider is a wrapper around aws.CredentialsProvider used for authenticating +// towards AWS KMS. +type CredsProvider struct { + credsProvider aws.CredentialsProvider +} + +// NewCredsProvider returns a CredsProvider object with the provided aws.CredentialsProvider. +func NewCredsProvider(cp aws.CredentialsProvider) *CredsProvider { + return &CredsProvider{ + credsProvider: cp, + } +} + +// ApplyToMasterKey configures the credentials the provided key. +func (c CredsProvider) ApplyToMasterKey(key *MasterKey) { + key.credentialsProvider = c.credsProvider +} + +// LoadCredsProviderFromYaml parses the given YAML returns a CredsProvider object +// which contains the credentials provider used for authenticating towards AWS KMS. +func LoadCredsProviderFromYaml(b []byte) (*CredsProvider, error) { + credInfo := struct { + AccessKeyID string `json:"aws_access_key_id"` + SecretAccessKey string `json:"aws_secret_access_key"` + SessionToken string `json:"aws_session_token"` + }{} + if err := yaml.Unmarshal(b, &credInfo); err != nil { + return nil, fmt.Errorf("failed to unmarshal AWS credentials file: %w", err) + } + return &CredsProvider{ + credsProvider: credentials.NewStaticCredentialsProvider(credInfo.AccessKeyID, + credInfo.SecretAccessKey, credInfo.SessionToken), + }, nil +} + +// EncryptedDataKey returns the encrypted data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// SetEncryptedDataKey sets the encrypted data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// Encrypt takes a SOPS data key, encrypts it with KMS and stores the result +// in the EncryptedKey field. +func (key *MasterKey) Encrypt(dataKey []byte) error { + cfg, err := key.createKMSConfig() + if err != nil { + return err + } + client := kms.NewFromConfig(*cfg) + input := &kms.EncryptInput{ + KeyId: &key.Arn, + Plaintext: dataKey, + EncryptionContext: key.EncryptionContext, + } + out, err := client.Encrypt(context.TODO(), input) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key with AWS KMS: %w", err) + } + key.EncryptedKey = base64.StdEncoding.EncodeToString(out.CiphertextBlob) + return nil +} + +// EncryptIfNeeded encrypts the provided sops' data key and encrypts it, if it +// has not been encrypted yet. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// Decrypt decrypts the EncryptedKey field with AWS KMS and returns the result. +func (key *MasterKey) Decrypt() ([]byte, error) { + k, err := base64.StdEncoding.DecodeString(key.EncryptedKey) + if err != nil { + return nil, fmt.Errorf("error base64-decoding encrypted data key: %s", err) + } + cfg, err := key.createKMSConfig() + if err != nil { + return nil, err + } + client := kms.NewFromConfig(*cfg) + input := &kms.DecryptInput{ + KeyId: &key.Arn, + CiphertextBlob: k, + EncryptionContext: key.EncryptionContext, + } + decrypted, err := client.Decrypt(context.TODO(), input) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key with AWS KMS: %w", err) + } + return decrypted.Plaintext, nil +} + +// NeedsRotation returns whether the data key needs to be rotated or not. +func (key *MasterKey) NeedsRotation() bool { + return time.Since(key.CreationDate) > kmsTTL +} + +// ToString converts the key to a string representation. +func (key *MasterKey) ToString() string { + return key.Arn +} + +// ToMap converts the MasterKey to a map for serialization purposes. +func (key MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["arn"] = key.Arn + if key.Role != "" { + out["role"] = key.Role + } + out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) + out["enc"] = key.EncryptedKey + if key.EncryptionContext != nil { + outcontext := make(map[string]string) + for k, v := range key.EncryptionContext { + outcontext[k] = v + } + out["context"] = outcontext + } + return out +} + +// NewMasterKey creates a new MasterKey from an ARN, role and context, setting the +// creation date to the current date. +func NewMasterKey(arn string, role string, context map[string]string) *MasterKey { + return &MasterKey{ + Arn: arn, + Role: role, + EncryptionContext: context, + CreationDate: time.Now().UTC(), + } +} + +// NewMasterKeyFromArn takes an ARN string and returns a new MasterKey for that +// ARN. +func NewMasterKeyFromArn(arn string, context map[string]string, awsProfile string) *MasterKey { + k := &MasterKey{} + arn = strings.Replace(arn, " ", "", -1) + roleIndex := strings.Index(arn, "+arn:aws:iam::") + if roleIndex > 0 { + k.Arn = arn[:roleIndex] + k.Role = arn[roleIndex+1:] + } else { + k.Arn = arn + } + k.EncryptionContext = context + k.CreationDate = time.Now().UTC() + k.AwsProfile = awsProfile + return k +} + +// createKMSConfig returns a Config configured with the appropriate credentials. +func (key MasterKey) createKMSConfig() (*aws.Config, error) { + re := regexp.MustCompile(arnRegex) + matches := re.FindStringSubmatch(key.Arn) + if matches == nil { + return nil, fmt.Errorf("no valid ARN found in '%s'", key.Arn) + } + region := matches[1] + cfg, err := config.LoadDefaultConfig(context.TODO(), func(lo *config.LoadOptions) error { + // Use the credentialsProvider if present, otherwise default to reading credentials + // from the environment. + if key.credentialsProvider != nil { + lo.Credentials = key.credentialsProvider + } + if key.AwsProfile != "" { + lo.SharedConfigProfile = key.AwsProfile + } + lo.Region = region + + // Set the epResolver, if present. Used ONLY for tests. + if key.epResolver != nil { + lo.EndpointResolverWithOptions = key.epResolver + } + return nil + }) + if err != nil { + return nil, fmt.Errorf("couldn't load AWS config: %w", err) + } + if key.Role != "" { + return key.createSTSConfig(&cfg) + } + + return &cfg, nil +} + +// createSTSConfig uses AWS STS to assume a role and returns a Config configured +// with that role's credentials. +func (key MasterKey) createSTSConfig(config *aws.Config) (*aws.Config, error) { + hostname, err := os.Hostname() + if err != nil { + return nil, err + } + stsRoleSessionNameRe := regexp.MustCompile(stsSessionRegex) + + sanitizedHostname := stsRoleSessionNameRe.ReplaceAllString(hostname, "") + name := "sops@" + sanitizedHostname + if len(name) >= roleSessionNameLengthLimit { + name = name[:roleSessionNameLengthLimit] + } + + client := sts.NewFromConfig(*config) + input := &sts.AssumeRoleInput{ + RoleArn: &key.Role, + RoleSessionName: &name, + } + out, err := client.AssumeRole(context.TODO(), input) + if err != nil { + return nil, fmt.Errorf("failed to assume role '%s': %w", key.Role, err) + } + config.Credentials = credentials.NewStaticCredentialsProvider(*out.Credentials.AccessKeyId, + *out.Credentials.SecretAccessKey, *out.Credentials.SessionToken, + ) + return config, nil +} diff --git a/internal/decryptors/sops/kustomize-controller/awskms/keysource_test.go b/internal/decryptors/sops/kustomize-controller/awskms/keysource_test.go new file mode 100644 index 0000000..54f5040 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/awskms/keysource_test.go @@ -0,0 +1,406 @@ +/* +Copyright (C) 2022 The Flux authors + +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 https://mozilla.org/MPL/2.0/. +*/ + +package awskms + +import ( + "context" + "encoding/base64" + "fmt" + logger "log" + "os" + "testing" + "time" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/kms" + awsv1 "github.com/aws/aws-sdk-go/aws" + sessionv1 "github.com/aws/aws-sdk-go/aws/session" + kmsv1 "github.com/aws/aws-sdk-go/service/kms" + . "github.com/onsi/gomega" + "github.com/ory/dockertest/v3" +) + +var ( + testKMSServerURL string + testKMSARN string +) + +const ( + dummyARN = "arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48" + testLocalKMSTag = "3.11.1" + testLocalKMSImage = "nsmithuk/local-kms" +) + +// TestMain initializes a AWS KMS server using Docker, writes the HTTP address to +// testAWSEndpoint, tries to generate a key for encryption-decryption using a +// backoff retry approach and then sets testKMSARN to the id of the generated key. +// It then runs all the tests, which can make use of the various `test*` variables. +func TestMain(m *testing.M) { + // Uses a sensible default on Windows (TCP/HTTP) and Linux/MacOS (socket) + pool, err := dockertest.NewPool("") + if err != nil { + logger.Fatalf("could not connect to docker: %s", err) + } + + // Pull the image, create a container based on it, and run it + // resource, err := pool.Run("nsmithuk/local-kms", testLocalKMSVersion, []string{}) + resource, err := pool.RunWithOptions(&dockertest.RunOptions{ + Repository: testLocalKMSImage, + Tag: testLocalKMSTag, + ExposedPorts: []string{"8080"}, + }) + if err != nil { + logger.Fatalf("could not start resource: %s", err) + } + + purgeResource := func() { + if err := pool.Purge(resource); err != nil { + logger.Printf("could not purge resource: %s", err) + } + } + + testKMSServerURL = fmt.Sprintf("http://127.0.0.1:%v", resource.GetPort("8080/tcp")) + masterKey := createTestMasterKey(dummyARN) + + kmsClient, err := createTestKMSClient(masterKey) + if err != nil { + purgeResource() + logger.Fatalf("could not create session: %s", err) + } + + var key *kms.CreateKeyOutput + if err := pool.Retry(func() error { + key, err = kmsClient.CreateKey(context.TODO(), &kms.CreateKeyInput{}) + if err != nil { + return err + } + return nil + }); err != nil { + purgeResource() + logger.Fatalf("could not create key: %s", err) + } + + if key.KeyMetadata.Arn != nil { + testKMSARN = *key.KeyMetadata.Arn + } else { + purgeResource() + logger.Fatalf("could not set arn") + } + + // Run the tests, but only if we succeeded in setting up the AWS KMS server. + var code int + if err == nil { + code = m.Run() + } + + // This can't be deferred, as os.Exit simpy does not care + if err := pool.Purge(resource); err != nil { + logger.Fatalf("could not purge resource: %s", err) + } + + os.Exit(code) +} + +func TestMasterKey_Encrypt(t *testing.T) { + g := NewWithT(t) + key := createTestMasterKey(testKMSARN) + dataKey := []byte("thisistheway") + g.Expect(key.Encrypt(dataKey)).To(Succeed()) + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + + kmsClient, err := createTestKMSClient(key) + g.Expect(err).ToNot(HaveOccurred()) + + k, err := base64.StdEncoding.DecodeString(key.EncryptedKey) + g.Expect(err).ToNot(HaveOccurred()) + + input := &kms.DecryptInput{ + CiphertextBlob: k, + EncryptionContext: key.EncryptionContext, + } + decrypted, err := kmsClient.Decrypt(context.TODO(), input) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decrypted.Plaintext).To(Equal(dataKey)) +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + encryptKey := createTestMasterKey(testKMSARN) + dataKey := []byte("encrypt-compat") + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + // This is the core decryption logic of `sopskms.MasterKey.Decrypt()`. + // We don't call `sops.MasterKey.Decrypt()` directly to avoid issues with + // session and config setup. + config := awsv1.Config{ + Region: awsv1.String("us-west-2"), + Endpoint: &testKMSServerURL, + } + t.Setenv("AWS_ACCESS_KEY_ID", "id") + t.Setenv("AWS_SECRET_ACCESS_KEY", "secret") + k, err := base64.StdEncoding.DecodeString(encryptKey.EncryptedKey) + g.Expect(err).ToNot(HaveOccurred()) + sess, err := sessionv1.NewSessionWithOptions(sessionv1.Options{ + Config: config, + }) + kmsSvc := kmsv1.New(sess) + decrypted, err := kmsSvc.Decrypt(&kmsv1.DecryptInput{CiphertextBlob: k}) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decrypted.Plaintext).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptIfNeeded(t *testing.T) { + g := NewWithT(t) + + key := createTestMasterKey(testKMSARN) + g.Expect(key.EncryptIfNeeded([]byte("data"))).To(Succeed()) + + encryptedKey := key.EncryptedKey + g.Expect(encryptedKey).ToNot(BeEmpty()) + + g.Expect(key.EncryptIfNeeded([]byte("some other data"))).To(Succeed()) + g.Expect(key.EncryptedKey).To(Equal(encryptedKey)) +} + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{EncryptedKey: "some key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_Decrypt(t *testing.T) { + g := NewWithT(t) + + key := createTestMasterKey(testKMSARN) + kmsClient, err := createTestKMSClient(key) + g.Expect(err).ToNot(HaveOccurred()) + + dataKey := []byte("itsalwaysdns") + out, err := kmsClient.Encrypt(context.TODO(), &kms.EncryptInput{ + Plaintext: dataKey, KeyId: &key.Arn, EncryptionContext: key.EncryptionContext, + }) + g.Expect(err).ToNot(HaveOccurred()) + + key.EncryptedKey = base64.StdEncoding.EncodeToString(out.CiphertextBlob) + got, err := key.Decrypt() + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(got).To(Equal(dataKey)) +} + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + // This is the core encryption logic of `sopskms.MasterKey.Encrypt()`. + // We don't call `sops.MasterKey.Encrypt()` directly to avoid issues with + // session and config setup. + dataKey := []byte("decrypt-compat") + config := awsv1.Config{ + Region: awsv1.String("us-west-2"), + Endpoint: &testKMSServerURL, + } + t.Setenv("AWS_ACCESS_KEY_ID", "id") + t.Setenv("AWS_SECRET_ACCESS_KEY", "secret") + sess, err := sessionv1.NewSessionWithOptions(sessionv1.Options{ + Config: config, + }) + kmsSvc := kmsv1.New(sess) + encrypted, err := kmsSvc.Encrypt(&kmsv1.EncryptInput{Plaintext: dataKey, KeyId: &testKMSARN}) + g.Expect(err).ToNot(HaveOccurred()) + + decryptKey := createTestMasterKey(testKMSARN) + decryptKey.EncryptedKey = base64.StdEncoding.EncodeToString(encrypted.CiphertextBlob) + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + dataKey := []byte("thisistheway") + + encryptKey := createTestMasterKey(testKMSARN) + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + g.Expect(encryptKey.EncryptedKey).ToNot(BeEmpty()) + + decryptKey := createTestMasterKey(testKMSARN) + decryptKey.EncryptedKey = encryptKey.EncryptedKey + + decryptedData, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decryptedData).To(Equal(dataKey)) +} + +func TestMasterKey_NeedsRotation(t *testing.T) { + g := NewWithT(t) + + key := NewMasterKeyFromArn(dummyARN, nil, "") + g.Expect(key.NeedsRotation()).To(BeFalse()) + + key.CreationDate = key.CreationDate.Add(-(kmsTTL + time.Second)) + g.Expect(key.NeedsRotation()).To(BeTrue()) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + key := MasterKey{ + Arn: "test-arn", + Role: "test-role", + EncryptedKey: "enc-key", + EncryptionContext: map[string]string{ + "env": "test", + }, + } + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "arn": "test-arn", + "role": "test-role", + "created_at": "0001-01-01T00:00:00Z", + "enc": "enc-key", + "context": map[string]string{ + "env": "test", + }, + })) +} + +func TestCreds_ApplyToMasterKey(t *testing.T) { + g := NewWithT(t) + + creds := CredsProvider{ + credsProvider: credentials.NewStaticCredentialsProvider("", "", ""), + } + key := &MasterKey{} + creds.ApplyToMasterKey(key) + g.Expect(key.credentialsProvider).To(Equal(creds.credsProvider)) +} + +func TestLoadAwsKmsCredsFromYaml(t *testing.T) { + g := NewWithT(t) + credsYaml := []byte(` +aws_access_key_id: test-id +aws_secret_access_key: test-secret +aws_session_token: test-token +`) + credsProvider, err := LoadCredsProviderFromYaml(credsYaml) + g.Expect(err).ToNot(HaveOccurred()) + + creds, err := credsProvider.credsProvider.Retrieve(context.TODO()) + g.Expect(err).ToNot(HaveOccurred()) + + g.Expect(creds.AccessKeyID).To(Equal("test-id")) + g.Expect(creds.SecretAccessKey).To(Equal("test-secret")) + g.Expect(creds.SessionToken).To(Equal("test-token")) +} + +func Test_createKMSConfig(t *testing.T) { + tests := []struct { + name string + key MasterKey + assertFunc func(g *WithT, cfg *aws.Config, err error) + fallback bool + }{ + { + name: "master key with invalid arn fails", + key: MasterKey{ + Arn: "arn:gcp:kms:antartica-north-2::key/45e6-aca6-a5b005693a48", + }, + assertFunc: func(g *WithT, _ *aws.Config, err error) { + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("no valid ARN found")) + }, + }, + { + name: "master key with with proper configuration passes", + key: MasterKey{ + credentialsProvider: credentials.NewStaticCredentialsProvider("test-id", "test-secret", "test-token"), + AwsProfile: "test-profile", + Arn: "arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48", + }, + assertFunc: func(g *WithT, cfg *aws.Config, err error) { + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(cfg.Region).To(Equal("us-west-2")) + + creds, err := cfg.Credentials.Retrieve(context.TODO()) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(creds.AccessKeyID).To(Equal("test-id")) + g.Expect(creds.SecretAccessKey).To(Equal("test-secret")) + g.Expect(creds.SessionToken).To(Equal("test-token")) + + // ConfigSources is a slice of config.Config, which in turn is an interface. + // Since we use a LoadOptions object, we assert the type of cfgSrc and then + // check if the expected profile is present. + for _, cfgSrc := range cfg.ConfigSources { + if src, ok := cfgSrc.(config.LoadOptions); ok { + g.Expect(src.SharedConfigProfile).To(Equal("test-profile")) + } + } + }, + }, + { + name: "master key without creds and profile falls back to the environment variables", + key: MasterKey{ + Arn: "arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48", + }, + fallback: true, + assertFunc: func(g *WithT, cfg *aws.Config, err error) { + g.Expect(err).ToNot(HaveOccurred()) + + creds, err := cfg.Credentials.Retrieve(context.TODO()) + g.Expect(creds.AccessKeyID).To(Equal("id")) + g.Expect(creds.SecretAccessKey).To(Equal("secret")) + g.Expect(creds.SessionToken).To(Equal("token")) + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + // Set the environment variables if we want to fallback + if tt.fallback { + t.Setenv("AWS_ACCESS_KEY_ID", "id") + t.Setenv("AWS_SECRET_ACCESS_KEY", "secret") + t.Setenv("AWS_SESSION_TOKEN", "token") + } + cfg, err := tt.key.createKMSConfig() + tt.assertFunc(g, cfg, err) + }) + } +} + +func createTestMasterKey(arn string) MasterKey { + return MasterKey{ + Arn: arn, + credentialsProvider: credentials.NewStaticCredentialsProvider("id", "secret", ""), + epResolver: epResolver{}, + } +} + +// epResolver is a dummy resolver that points to the local test KMS server +type epResolver struct{} + +func (e epResolver) ResolveEndpoint(service, region string, options ...interface{}) (aws.Endpoint, error) { + return aws.Endpoint{ + URL: testKMSServerURL, + }, nil +} + +func createTestKMSClient(key MasterKey) (*kms.Client, error) { + cfg, err := key.createKMSConfig() + if err != nil { + return nil, err + } + + cfg.EndpointResolverWithOptions = epResolver{} + + return kms.NewFromConfig(*cfg), nil +} diff --git a/internal/decryptors/sops/kustomize-controller/azkv/config.go b/internal/decryptors/sops/kustomize-controller/azkv/config.go new file mode 100644 index 0000000..4685cdd --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/azkv/config.go @@ -0,0 +1,130 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package azkv + +import ( + "fmt" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "sigs.k8s.io/yaml" +) + +// LoadAADConfigFromBytes attempts to load the given bytes into the given AADConfig. +// By first decoding it if UTF-16, and then unmarshalling it into the given struct. +// It returns an error for any failure. +func LoadAADConfigFromBytes(b []byte, s *AADConfig) error { + b, err := decode(b) + if err != nil { + return fmt.Errorf("failed to decode Azure authentication file bytes: %w", err) + } + if err = yaml.Unmarshal(b, s); err != nil { + err = fmt.Errorf("failed to unmarshal Azure authentication file: %w", err) + } + return err +} + +// AADConfig contains the selection of fields from an Azure authentication file +// required for Active Directory authentication. +type AADConfig struct { + AZConfig + TenantID string `json:"tenantId,omitempty"` + ClientID string `json:"clientId,omitempty"` + ClientSecret string `json:"clientSecret,omitempty"` + ClientCertificate string `json:"clientCertificate,omitempty"` + ClientCertificatePassword string `json:"clientCertificatePassword,omitempty"` + ClientCertificateSendChain bool `json:"clientCertificateSendChain,omitempty"` + AuthorityHost string `json:"authorityHost,omitempty"` +} + +// AZConfig contains the Service Principal fields as generated by `az`. +// Ref: https://docs.microsoft.com/en-us/azure/aks/kubernetes-service-principal?tabs=azure-cli#manually-create-a-service-principal +type AZConfig struct { + AppID string `json:"appId,omitempty"` + Tenant string `json:"tenant,omitempty"` + Password string `json:"password,omitempty"` +} + +// TokenFromAADConfig attempts to construct a Token using the AADConfig values. +// It detects credentials in the following order: +// +// - azidentity.ClientSecretCredential when `tenantId`, `clientId` and +// `clientSecret` fields are found. +// - azidentity.ClientCertificateCredential when `tenantId`, +// `clientCertificate` (and optionally `clientCertificatePassword`) fields +// are found. +// - azidentity.ClientSecretCredential when AZConfig fields are found. +// - azidentity.ManagedIdentityCredential for a User ID, when a `clientId` +// field but no `tenantId` is found. +// +// If no set of credentials is found or the azcore.TokenCredential can not be +// created, an error is returned. +func TokenFromAADConfig(c AADConfig) (_ *Token, err error) { + var token azcore.TokenCredential + if c.TenantID != "" && c.ClientID != "" { + if c.ClientSecret != "" { + if token, err = azidentity.NewClientSecretCredential(c.TenantID, c.ClientID, c.ClientSecret, &azidentity.ClientSecretCredentialOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: c.GetCloudConfig(), + }, + }); err != nil { + return + } + return NewToken(token), nil + } + if c.ClientCertificate != "" { + certs, pk, err := azidentity.ParseCertificates([]byte(c.ClientCertificate), []byte(c.ClientCertificatePassword)) + if err != nil { + return nil, err + } + if token, err = azidentity.NewClientCertificateCredential(c.TenantID, c.ClientID, certs, pk, &azidentity.ClientCertificateCredentialOptions{ + SendCertificateChain: c.ClientCertificateSendChain, + ClientOptions: azcore.ClientOptions{ + Cloud: c.GetCloudConfig(), + }, + }); err != nil { + return nil, err + } + return NewToken(token), nil + } + } + + switch { + case c.Tenant != "" && c.AppID != "" && c.Password != "": + if token, err = azidentity.NewClientSecretCredential(c.Tenant, c.AppID, c.Password, &azidentity.ClientSecretCredentialOptions{ + ClientOptions: azcore.ClientOptions{ + Cloud: c.GetCloudConfig(), + }, + }); err != nil { + return + } + return NewToken(token), nil + case c.ClientID != "": + if token, err = azidentity.NewManagedIdentityCredential(&azidentity.ManagedIdentityCredentialOptions{ + ID: azidentity.ClientID(c.ClientID), + }); err != nil { + return + } + return NewToken(token), nil + default: + return nil, fmt.Errorf("invalid data: requires a '%s' field, a combination of '%s', '%s' and '%s', or '%s', '%s' and '%s'", + "clientId", "tenantId", "clientId", "clientSecret", "tenantId", "clientId", "clientCertificate") + } +} + +// GetCloudConfig returns a cloud.Configuration with the AuthorityHost, or the +// Azure Public Cloud default. +func (s AADConfig) GetCloudConfig() cloud.Configuration { + if s.AuthorityHost != "" { + return cloud.Configuration{ + ActiveDirectoryAuthorityHost: s.AuthorityHost, + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{}, + } + } + return cloud.AzurePublic +} diff --git a/internal/decryptors/sops/kustomize-controller/azkv/config_test.go b/internal/decryptors/sops/kustomize-controller/azkv/config_test.go new file mode 100644 index 0000000..c30b990 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/azkv/config_test.go @@ -0,0 +1,207 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package azkv + +import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "math/big" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/cloud" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + . "github.com/onsi/gomega" +) + +func TestLoadAADConfigFromBytes(t *testing.T) { + tests := []struct { + name string + b []byte + want AADConfig + wantErr bool + }{ + { + name: "Service Principal with Secret", + b: []byte(`tenantId: "some-tenant-id" +clientId: "some-client-id" +clientSecret: "some-client-secret"`), + want: AADConfig{ + TenantID: "some-tenant-id", + ClientID: "some-client-id", + ClientSecret: "some-client-secret", + }, + }, + { + name: "Service Principal with Certificate", + b: []byte(`tenantId: "some-tenant-id" +clientId: "some-client-id" +clientCertificate: "some-client-certificate"`), + want: AADConfig{ + TenantID: "some-tenant-id", + ClientID: "some-client-id", + ClientCertificate: "some-client-certificate", + }, + }, + { + name: "Managed Identity with Client ID", + b: []byte(`clientId: "some-client-id"`), + want: AADConfig{ + ClientID: "some-client-id", + }, + }, + { + name: "Service Principal with Secret from az CLI", + b: []byte(`{"appId": "some-app-id", "tenant": "some-tenant", "password": "some-password"}`), + want: AADConfig{ + AZConfig: AZConfig{ + AppID: "some-app-id", + Tenant: "some-tenant", + Password: "some-password", + }, + }, + }, + { + name: "Authority host", + b: []byte(`{"authorityHost": "https://example.com"}`), + want: AADConfig{ + AuthorityHost: "https://example.com", + }, + }, + { + name: "invalid", + b: []byte("some string"), + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + got := AADConfig{} + err := LoadAADConfigFromBytes(tt.b, &got) + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(got).To(Equal(tt.want)) + return + } + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(got).To(Equal(tt.want)) + }) + } +} + +func TestTokenFromAADConfig(t *testing.T) { + tlsMock := validTLS(t) + + tests := []struct { + name string + config AADConfig + want azcore.TokenCredential + wantErr bool + }{ + { + name: "Service Principal with Secret", + config: AADConfig{ + TenantID: "some-tenant-id", + ClientID: "some-client-id", + ClientSecret: "some-client-secret", + }, + want: &azidentity.ClientSecretCredential{}, + }, + { + name: "Service Principal with Certificate", + config: AADConfig{ + TenantID: "some-tenant-id", + ClientID: "some-client-id", + ClientCertificate: string(tlsMock), + }, + want: &azidentity.ClientCertificateCredential{}, + }, + { + name: "Service Principal with az CLI format", + config: AADConfig{ + AZConfig: AZConfig{ + AppID: "some-app-id", + Tenant: "some-tenant", + Password: "some-password", + }, + }, + want: &azidentity.ClientSecretCredential{}, + }, + { + name: "Managed Identity with Client ID", + config: AADConfig{ + ClientID: "some-client-id", + }, + want: &azidentity.ManagedIdentityCredential{}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + got, err := TokenFromAADConfig(tt.config) + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(got.token).To(BeNil()) + return + } + + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(got.token).ToNot(BeNil()) + g.Expect(got.token).To(BeAssignableToTypeOf(tt.want)) + }) + } +} + +func TestAADConfig_GetCloudConfig(t *testing.T) { + g := NewWithT(t) + + g.Expect((AADConfig{}).GetCloudConfig()).To(Equal(cloud.AzurePublic)) + g.Expect((AADConfig{AuthorityHost: "https://example.com"}).GetCloudConfig()).To(Equal(cloud.Configuration{ + ActiveDirectoryAuthorityHost: "https://example.com", + Services: map[cloud.ServiceName]cloud.ServiceConfiguration{}, + })) +} + +func validTLS(t *testing.T) []byte { + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatal("Private key cannot be created.", err.Error()) + } + + out := bytes.NewBuffer(nil) + + var privateKey = &pem.Block{ + Type: "PRIVATE KEY", + Bytes: x509.MarshalPKCS1PrivateKey(key), + } + if err = pem.Encode(out, privateKey); err != nil { + t.Fatal("Private key cannot be PEM encoded.", err.Error()) + } + + certTemplate := x509.Certificate{ + SerialNumber: big.NewInt(1337), + } + cert, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, &key.PublicKey, key) + if err != nil { + t.Fatal("Certificate cannot be created.", err.Error()) + } + var certificate = &pem.Block{ + Type: "CERTIFICATE", + Bytes: cert, + } + if err = pem.Encode(out, certificate); err != nil { + t.Fatal("Certificate cannot be PEM encoded.", err.Error()) + } + + return out.Bytes() +} diff --git a/internal/decryptors/sops/kustomize-controller/azkv/keysource.go b/internal/decryptors/sops/kustomize-controller/azkv/keysource.go new file mode 100644 index 0000000..4fddff9 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/azkv/keysource.go @@ -0,0 +1,277 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package azkv + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/binary" + "errors" + "fmt" + "io/ioutil" + "os" + "strings" + "time" + "unicode/utf16" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys" + "github.com/dimchansky/utfbom" +) + +var ( + // azkvTTL is the duration after which a MasterKey requires rotation. + azkvTTL = time.Hour * 24 * 30 * 6 +) + +// MasterKey is an Azure Key Vault Key used to Encrypt and Decrypt SOPS' +// data key. +// +// The underlying authentication token can be configured using TokenFromAADConfig +// and Token.ApplyToMasterKey(). +type MasterKey struct { + VaultURL string + Name string + Version string + + EncryptedKey string + CreationDate time.Time + + token azcore.TokenCredential +} + +// MasterKeyFromURL creates a new MasterKey from a Vault URL, key name, and key +// version. +func MasterKeyFromURL(url, name, version string) *MasterKey { + key := &MasterKey{ + VaultURL: url, + Name: name, + Version: version, + CreationDate: time.Now().UTC(), + } + return key +} + +// Token is an azcore.TokenCredential used for authenticating towards Azure Key +// Vault. +type Token struct { + token azcore.TokenCredential +} + +// NewToken creates a new Token with the provided azcore.TokenCredential. +func NewToken(token azcore.TokenCredential) *Token { + return &Token{token: token} +} + +// ApplyToMasterKey configures the Token on the provided key. +func (t Token) ApplyToMasterKey(key *MasterKey) { + key.token = t.token +} + +// Encrypt takes a SOPS data key, encrypts it with Azure Key Vault, and stores +// the result in the EncryptedKey field. +func (key *MasterKey) Encrypt(dataKey []byte) error { + creds, err := key.getTokenCredential() + if err != nil { + return fmt.Errorf("failed to get Azure token credential to encrypt: %w", err) + } + c, err := azkeys.NewClient(key.VaultURL, creds, nil) + if err != nil { + return fmt.Errorf("failed to construct Azure Key Vault crypto client to encrypt data: %w", err) + } + resp, err := c.Encrypt(context.Background(), key.Name, key.Version, azkeys.KeyOperationParameters{ + Algorithm: to.Ptr(azkeys.EncryptionAlgorithmRSAOAEP256), + Value: dataKey, + }, nil) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key with Azure Key Vault key '%s': %w", key.ToString(), err) + } + // This is for compatibility between the SOPS upstream which uses + // a much older Azure SDK, and our implementation which is up-to-date + // with the latest. + encodedEncryptedKey := base64.RawURLEncoding.EncodeToString(resp.Result) + key.SetEncryptedDataKey([]byte(encodedEncryptedKey)) + return nil +} + +// EncryptedDataKey returns the encrypted data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// SetEncryptedDataKey sets the encrypted data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been +// encrypted yet. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// Decrypt decrypts the EncryptedKey field with Azure Key Vault and returns +// the result. +func (key *MasterKey) Decrypt() ([]byte, error) { + creds, err := key.getTokenCredential() + if err != nil { + return nil, fmt.Errorf("failed to get Azure token credential to decrypt: %w", err) + } + c, err := azkeys.NewClient(key.VaultURL, creds, nil) + if err != nil { + return nil, fmt.Errorf("failed to construct Azure Key Vault crypto client to decrypt data: %w", err) + } + // This is for compatibility between the SOPS upstream which uses + // a much older Azure SDK, and our implementation which is up-to-date + // with the latest. + rawEncryptedKey, err := base64.RawURLEncoding.DecodeString(key.EncryptedKey) + if err != nil { + return nil, fmt.Errorf("failed to base64 decode Azure Key Vault encrypted key: %w", err) + } + resp, err := c.Decrypt(context.Background(), key.Name, key.Version, azkeys.KeyOperationParameters{ + Algorithm: to.Ptr(azkeys.EncryptionAlgorithmRSAOAEP256), + Value: rawEncryptedKey, + }, nil) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key with Azure Key Vault key '%s': %w", key.ToString(), err) + } + return resp.Result, nil +} + +// NeedsRotation returns whether the data key needs to be rotated or not. +func (key *MasterKey) NeedsRotation() bool { + return time.Since(key.CreationDate) > (azkvTTL) +} + +// ToString converts the key to a string representation. +func (key *MasterKey) ToString() string { + return fmt.Sprintf("%s/keys/%s/%s", key.VaultURL, key.Name, key.Version) +} + +// ToMap converts the MasterKey to a map for serialization purposes. +func (key MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["vaultUrl"] = key.VaultURL + out["key"] = key.Name + out["version"] = key.Version + out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) + out["enc"] = key.EncryptedKey + return out +} + +func decode(b []byte) ([]byte, error) { + reader, enc := utfbom.Skip(bytes.NewReader(b)) + switch enc { + case utfbom.UTF16LittleEndian: + u16 := make([]uint16, (len(b)/2)-1) + err := binary.Read(reader, binary.LittleEndian, &u16) + if err != nil { + return nil, err + } + return []byte(string(utf16.Decode(u16))), nil + case utfbom.UTF16BigEndian: + u16 := make([]uint16, (len(b)/2)-1) + err := binary.Read(reader, binary.BigEndian, &u16) + if err != nil { + return nil, err + } + return []byte(string(utf16.Decode(u16))), nil + } + return ioutil.ReadAll(reader) +} + +// getTokenCredential returns the tokenCredential of the MasterKey, or +// azidentity.NewDefaultAzureCredential. +func (key *MasterKey) getTokenCredential() (azcore.TokenCredential, error) { + if key.token == nil { + return getDefaultAzureCredential() + } + return key.token, nil +} + +// getDefaultAzureCredentials is a modification of +// azidentity.NewDefaultAzureCredential, specifically adapted to not shell out +// to the Azure CLI. +// +// It attemps to return an azcore.TokenCredential based on the following order: +// +// - azidentity.NewEnvironmentCredential if environment variables AZURE_CLIENT_ID, +// AZURE_CLIENT_ID is set with either one of the following: (AZURE_CLIENT_SECRET) +// or (AZURE_CLIENT_CERTIFICATE_PATH and AZURE_CLIENT_CERTIFICATE_PATH) or +// (AZURE_USERNAME, AZURE_PASSWORD) +// - azidentity.WorkloadIdentity if environment variable configuration +// (AZURE_AUTHORITY_HOST, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_TENANT_ID) +// is set by the Azure workload identity webhook. +// - azidentity.ManagedIdentity if only AZURE_CLIENT_ID env variable is set. +func getDefaultAzureCredential() (azcore.TokenCredential, error) { + var ( + azureClientID = "AZURE_CLIENT_ID" + azureFederatedTokenFile = "AZURE_FEDERATED_TOKEN_FILE" + azureAuthorityHost = "AZURE_AUTHORITY_HOST" + azureTenantID = "AZURE_TENANT_ID" + ) + + var errorMessages []string + options := &azidentity.DefaultAzureCredentialOptions{} + + envCred, err := azidentity.NewEnvironmentCredential(&azidentity.EnvironmentCredentialOptions{ + ClientOptions: options.ClientOptions, DisableInstanceDiscovery: options.DisableInstanceDiscovery}, + ) + if err == nil { + return envCred, nil + } else { + errorMessages = append(errorMessages, "EnvironmentCredential: "+err.Error()) + } + + // workload identity requires values for AZURE_AUTHORITY_HOST, AZURE_CLIENT_ID, AZURE_FEDERATED_TOKEN_FILE, AZURE_TENANT_ID + haveWorkloadConfig := false + clientID, haveClientID := os.LookupEnv(azureClientID) + if haveClientID { + if file, ok := os.LookupEnv(azureFederatedTokenFile); ok { + if _, ok := os.LookupEnv(azureAuthorityHost); ok { + if tenantID, ok := os.LookupEnv(azureTenantID); ok { + haveWorkloadConfig = true + workloadCred, err := azidentity.NewWorkloadIdentityCredential(&azidentity.WorkloadIdentityCredentialOptions{ + ClientID: clientID, + TenantID: tenantID, + TokenFilePath: file, + ClientOptions: options.ClientOptions, + DisableInstanceDiscovery: options.DisableInstanceDiscovery, + }) + if err == nil { + return workloadCred, nil + } else { + errorMessages = append(errorMessages, "Workload Identity"+": "+err.Error()) + } + } + } + } + } + if !haveWorkloadConfig { + err := errors.New("missing environment variables for workload identity. Check webhook and pod configuration") + errorMessages = append(errorMessages, fmt.Sprintf("Workload Identity: %s", err)) + } + + o := &azidentity.ManagedIdentityCredentialOptions{ClientOptions: options.ClientOptions} + if haveClientID { + o.ID = azidentity.ClientID(clientID) + } + miCred, err := azidentity.NewManagedIdentityCredential(o) + if err == nil { + return miCred, nil + } else { + errorMessages = append(errorMessages, "ManagedIdentity"+": "+err.Error()) + } + + return nil, errors.New(strings.Join(errorMessages, "\n")) +} diff --git a/internal/decryptors/sops/kustomize-controller/azkv/keysource_integration_test.go b/internal/decryptors/sops/kustomize-controller/azkv/keysource_integration_test.go new file mode 100644 index 0000000..4de95d4 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/azkv/keysource_integration_test.go @@ -0,0 +1,147 @@ +//go:build integration +// +build integration + +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package azkv + +import ( + "context" + "encoding/base64" + "os" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore/to" + "github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys" + . "github.com/onsi/gomega" + "go.mozilla.org/sops/v3/azkv" +) + +// The following values should be created based on the instructions in: +// https://github.com/mozilla/sops#encrypting-using-azure-key-vault +var ( + testVaultURL = os.Getenv("TEST_AZURE_VAULT_URL") + testVaultKeyName = os.Getenv("TEST_AZURE_VAULT_KEY_NAME") + testVaultKeyVersion = os.Getenv("TEST_AZURE_VAULT_KEY_VERSION") + testAADConfig = AADConfig{ + TenantID: os.Getenv("TEST_AZURE_TENANT_ID"), + ClientID: os.Getenv("TEST_AZURE_CLIENT_ID"), + ClientSecret: os.Getenv("TEST_AZURE_CLIENT_SECRET"), + } +) + +func TestMasterKey_Encrypt(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL(testVaultURL, testVaultKeyName, testVaultKeyVersion) + token, err := TokenFromAADConfig(testAADConfig) + g.Expect(err).ToNot(HaveOccurred()) + token.ApplyToMasterKey(key) + + g.Expect(key.Encrypt([]byte("foo"))).To(Succeed()) + g.Expect(key.EncryptedDataKey()).ToNot(BeEmpty()) +} + +func TestMasterKey_Decrypt(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL(testVaultURL, testVaultKeyName, testVaultKeyVersion) + token, err := TokenFromAADConfig(testAADConfig) + g.Expect(err).ToNot(HaveOccurred()) + token.ApplyToMasterKey(key) + + dataKey := []byte("this is super secret data") + c, err := azkeys.NewClient(key.VaultURL, key.token, nil) + g.Expect(err).ToNot(HaveOccurred()) + resp, err := c.Encrypt(context.Background(), key.Name, key.Version, azkeys.KeyOperationParameters{ + Algorithm: to.Ptr(azkeys.EncryptionAlgorithmRSAOAEP256), + Value: dataKey, + }, nil) + g.Expect(err).ToNot(HaveOccurred()) + key.EncryptedKey = base64.RawURLEncoding.EncodeToString(resp.Result) + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + g.Expect(key.EncryptedKey).ToNot(Equal(dataKey)) + + got, err := key.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(got).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL(testVaultURL, testVaultKeyName, testVaultKeyVersion) + token, err := TokenFromAADConfig(testAADConfig) + g.Expect(err).ToNot(HaveOccurred()) + token.ApplyToMasterKey(key) + + dataKey := []byte("some-data-that-should-be-secret") + + g.Expect(key.Encrypt(dataKey)).To(Succeed()) + g.Expect(key.EncryptedDataKey()).ToNot(BeEmpty()) + + dec, err := key.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + encryptKey := MasterKeyFromURL(testVaultURL, testVaultKeyName, testVaultKeyVersion) + token, err := TokenFromAADConfig(testAADConfig) + g.Expect(err).ToNot(HaveOccurred()) + token.ApplyToMasterKey(encryptKey) + + dataKey := []byte("foo") + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + t.Setenv("AZURE_CLIENT_ID", testAADConfig.ClientID) + t.Setenv("AZURE_TENANT_ID", testAADConfig.TenantID) + t.Setenv("AZURE_CLIENT_SECRET", testAADConfig.ClientSecret) + + decryptKey := &azkv.MasterKey{ + VaultURL: testVaultURL, + Name: testVaultKeyName, + Version: testVaultKeyVersion, + EncryptedKey: encryptKey.EncryptedKey, + CreationDate: time.Now(), + } + + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + t.Setenv("AZURE_CLIENT_ID", testAADConfig.ClientID) + t.Setenv("AZURE_TENANT_ID", testAADConfig.TenantID) + t.Setenv("AZURE_CLIENT_SECRET", testAADConfig.ClientSecret) + + dataKey := []byte("foo") + + encryptKey := &azkv.MasterKey{ + VaultURL: testVaultURL, + Name: testVaultKeyName, + Version: testVaultKeyVersion, + CreationDate: time.Now(), + } + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + decryptKey := MasterKeyFromURL(testVaultURL, testVaultKeyName, testVaultKeyVersion) + token, err := TokenFromAADConfig(testAADConfig) + g.Expect(err).ToNot(HaveOccurred()) + token.ApplyToMasterKey(decryptKey) + + decryptKey.EncryptedKey = encryptKey.EncryptedKey + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} diff --git a/internal/decryptors/sops/kustomize-controller/azkv/keysource_test.go b/internal/decryptors/sops/kustomize-controller/azkv/keysource_test.go new file mode 100644 index 0000000..39c19aa --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/azkv/keysource_test.go @@ -0,0 +1,74 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package azkv + +import ( + "testing" + "time" + + . "github.com/onsi/gomega" +) + +func TestToken_ApplyToMasterKey(t *testing.T) { + g := NewWithT(t) + + token, err := TokenFromAADConfig( + AADConfig{TenantID: "tenant", ClientID: "client", ClientSecret: "secret"}, + ) + g.Expect(err).ToNot(HaveOccurred()) + + key := &MasterKey{} + token.ApplyToMasterKey(key) + g.Expect(key.token).To(Equal(token.token)) +} + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{EncryptedKey: "some key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_SetEncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + encryptedKey := []byte("encrypted") + key := &MasterKey{} + key.SetEncryptedDataKey(encryptedKey) + g.Expect(key.EncryptedKey).To(BeEquivalentTo(encryptedKey)) +} + +func TestMasterKey_NeedsRotation(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL("", "", "") + g.Expect(key.NeedsRotation()).To(BeFalse()) + + key.CreationDate = key.CreationDate.Add(-(azkvTTL + time.Second)) + g.Expect(key.NeedsRotation()).To(BeTrue()) +} + +func TestMasterKey_ToString(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL("https://myvault.vault.azure.net", "key-name", "key-version") + g.Expect(key.ToString()).To(Equal("https://myvault.vault.azure.net/keys/key-name/key-version")) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromURL("https://myvault.vault.azure.net", "key-name", "key-version") + key.EncryptedKey = "data" + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "vaultUrl": key.VaultURL, + "key": key.Name, + "version": key.Version, + "created_at": key.CreationDate.UTC().Format(time.RFC3339), + "enc": key.EncryptedKey, + })) +} diff --git a/internal/decryptors/sops/kustomize-controller/gcpkms/keysource.go b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource.go new file mode 100644 index 0000000..a1946a1 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource.go @@ -0,0 +1,181 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package gcpkms + +import ( + "context" + "encoding/base64" + "fmt" + "regexp" + "time" + + kms "cloud.google.com/go/kms/apiv1" + kmspb "cloud.google.com/go/kms/apiv1/kmspb" + "google.golang.org/api/option" + "google.golang.org/grpc" +) + +var ( + // gcpkmsTTL is the duration after which a MasterKey requires rotation. + gcpkmsTTL = time.Hour * 24 * 30 * 6 +) + +// CredentialJSON is the service account keys used for authentication towards +// GCP KMS. +type CredentialJSON []byte + +// ApplyToMasterKey configures the CredentialJSON on the provided key. +func (c CredentialJSON) ApplyToMasterKey(key *MasterKey) { + key.credentialJSON = c +} + +// MasterKey is a GCP KMS key used to encrypt and decrypt the SOPS +// data key. +// Adapted from https://github.com/mozilla/sops/blob/v3.7.2/gcpkms/keysource.go +// to be able to have fine-grain control over the credentials used to authenticate +// towards GCP KMS. +type MasterKey struct { + // ResourceID is the resource id used to refer to the gcp kms key. + // It can be retrieved using the `gcloud` command. + ResourceID string + // EncryptedKey is the string returned after encrypting with GCP KMS. + EncryptedKey string + // CreationDate is the creation timestamp of the MasterKey. Used + // for NeedsRotation. + CreationDate time.Time + + // credentialJSON are the service account keys used to authenticate + // towards GCP KMS. + credentialJSON []byte + // grpcConn can be used to inject a custom GCP client connection. + // Mostly useful for testing at present, to wire the client to a mock + // server. + grpcConn *grpc.ClientConn +} + +// MasterKeyFromResourceID creates a new MasterKey with the provided resource +// ID. +func MasterKeyFromResourceID(resourceID string) *MasterKey { + return &MasterKey{ + ResourceID: resourceID, + CreationDate: time.Now().UTC(), + } +} + +// Encrypt takes a SOPS data key, encrypts it with GCP KMS, and stores the +// result in the EncryptedKey field. +func (key *MasterKey) Encrypt(datakey []byte) error { + cloudkmsService, err := key.newKMSClient() + if err != nil { + return err + } + defer cloudkmsService.Close() + + req := &kmspb.EncryptRequest{ + Name: key.ResourceID, + Plaintext: datakey, + } + ctx := context.Background() + resp, err := cloudkmsService.Encrypt(ctx, req) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key with GCP KMS: %w", err) + } + key.EncryptedKey = base64.StdEncoding.EncodeToString(resp.Ciphertext) + return nil +} + +// SetEncryptedDataKey sets the encrypted data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// EncryptedDataKey returns the encrypted data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been +// encrypted yet. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// Decrypt decrypts the EncryptedKey field with GCP KMS and returns +// the result. +func (key *MasterKey) Decrypt() ([]byte, error) { + service, err := key.newKMSClient() + if err != nil { + return nil, err + } + defer service.Close() + + decodedCipher, err := base64.StdEncoding.DecodeString(string(key.EncryptedDataKey())) + if err != nil { + return nil, err + } + req := &kmspb.DecryptRequest{ + Name: key.ResourceID, + Ciphertext: decodedCipher, + } + ctx := context.Background() + resp, err := service.Decrypt(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key with GCP KMS Key: %w", err) + } + + return resp.Plaintext, nil +} + +// NeedsRotation returns whether the data key needs to be rotated or not. +func (key *MasterKey) NeedsRotation() bool { + return time.Since(key.CreationDate) > (gcpkmsTTL) +} + +// ToString converts the key to a string representation. +func (key *MasterKey) ToString() string { + return key.ResourceID +} + +// ToMap converts the MasterKey to a map for serialization purposes. +func (key MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["resource_id"] = key.ResourceID + out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) + out["enc"] = key.EncryptedKey + return out +} + +// newKMSClient returns a GCP KMS client configured with the credentialJSON +// and/or grpcConn, falling back to environmental defaults. +// It returns an error if the ResourceID is invalid, or if the client setup +// fails. +func (key *MasterKey) newKMSClient() (*kms.KeyManagementClient, error) { + re := regexp.MustCompile(`^projects/[^/]+/locations/[^/]+/keyRings/[^/]+/cryptoKeys/[^/]+$`) + matches := re.FindStringSubmatch(key.ResourceID) + if matches == nil { + return nil, fmt.Errorf("no valid resourceId found in %q", key.ResourceID) + } + + var opts []option.ClientOption + if key.credentialJSON != nil { + opts = append(opts, option.WithCredentialsJSON(key.credentialJSON)) + } + if key.grpcConn != nil { + opts = append(opts, option.WithGRPCConn(key.grpcConn)) + } + + ctx := context.Background() + client, err := kms.NewKeyManagementClient(ctx, opts...) + if err != nil { + return nil, err + } + + return client, nil +} diff --git a/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_integration_test.go b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_integration_test.go new file mode 100644 index 0000000..e8412a4 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_integration_test.go @@ -0,0 +1,148 @@ +//go:build integration && disabled +// +build integration,disabled + +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package gcpkms + +import ( + "context" + "fmt" + "io/ioutil" + "os" + "testing" + + . "github.com/onsi/gomega" + "go.mozilla.org/sops/v3/gcpkms" + + "google.golang.org/api/option" + kmspb "google.golang.org/genproto/googleapis/cloud/kms/v1" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + kms "cloud.google.com/go/kms/apiv1" +) + +var ( + project = os.Getenv("TEST_PROJECT") + testKeyring = os.Getenv("TEST_KEYRING") + testKey = os.Getenv("TEST_CRYPTO_KEY") + testCredsJSON = os.Getenv("TEST_CRED_JSON") + resourceID = fmt.Sprintf("projects/%s/locations/global/keyRings/%s/cryptoKeys/%s", + project, testKeyring, testKey) +) + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", testCredsJSON) + + g.Expect(createKMSKeyIfNotExists(resourceID)).To(Succeed()) + + dataKey := []byte("blue golden light") + encryptedKey := gcpkms.NewMasterKeyFromResourceID(resourceID) + g.Expect(encryptedKey.Encrypt(dataKey)).To(Succeed()) + + decryptionKey := MasterKeyFromResourceID(resourceID) + creds, err := ioutil.ReadFile(testCredsJSON) + g.Expect(err).ToNot(HaveOccurred()) + decryptionKey.EncryptedKey = encryptedKey.EncryptedKey + decryptionKey.credentialJSON = creds + dec, err := decryptionKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + os.Setenv("GOOGLE_APPLICATION_CREDENTIALS", testCredsJSON) + g := NewWithT(t) + + g.Expect(createKMSKeyIfNotExists(resourceID)).To(Succeed()) + + dataKey := []byte("silver golden lights") + + encryptionKey := MasterKeyFromResourceID(resourceID) + creds, err := ioutil.ReadFile(testCredsJSON) + g.Expect(err).ToNot(HaveOccurred()) + encryptionKey.credentialJSON = creds + err = encryptionKey.Encrypt(dataKey) + g.Expect(err).ToNot(HaveOccurred()) + + decryptionKey := gcpkms.NewMasterKeyFromResourceID(resourceID) + decryptionKey.EncryptedKey = encryptionKey.EncryptedKey + dec, err := decryptionKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + g.Expect(createKMSKeyIfNotExists(resourceID)).To(Succeed()) + + key := MasterKeyFromResourceID(resourceID) + creds, err := ioutil.ReadFile(testCredsJSON) + g.Expect(err).ToNot(HaveOccurred()) + key.credentialJSON = creds + + datakey := []byte("a thousand splendid sons") + g.Expect(key.Encrypt(datakey)).To(Succeed()) + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + + dec, err := key.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(datakey)) +} + +func createKMSKeyIfNotExists(resourceID string) error { + ctx := context.Background() + // check if crypto key exists if not create it + c, err := kms.NewKeyManagementClient(ctx, option.WithCredentialsFile(testCredsJSON)) + if err != nil { + return fmt.Errorf("err creating client: %q", err) + } + + getCryptoKeyReq := &kmspb.GetCryptoKeyRequest{ + Name: resourceID, + } + _, err = c.GetCryptoKey(ctx, getCryptoKeyReq) + if err == nil { + return nil + } + + e, ok := status.FromError(err) + if !ok || (ok && e.Code() != codes.NotFound) { + return fmt.Errorf("err getting crypto key: %q", err) + } + + projectID := fmt.Sprintf("projects/%s/locations/global", project) + createKeyRingReq := &kmspb.CreateKeyRingRequest{ + Parent: projectID, + KeyRingId: testKeyring, + } + + _, err = c.CreateKeyRing(ctx, createKeyRingReq) + e, ok = status.FromError(err) + if err != nil && !(ok && e.Code() == codes.AlreadyExists) { + return fmt.Errorf("err creating key ring: %q", err) + } + + keyRingName := fmt.Sprintf("%s/keyRings/%s", projectID, testKeyring) + keyReq := &kmspb.CreateCryptoKeyRequest{ + Parent: keyRingName, + CryptoKeyId: testKey, + CryptoKey: &kmspb.CryptoKey{ + Purpose: kmspb.CryptoKey_ENCRYPT_DECRYPT, + }, + } + _, err = c.CreateCryptoKey(ctx, keyReq) + e, ok = status.FromError(err) + if err != nil && !(ok && e.Code() == codes.AlreadyExists) { + return fmt.Errorf("err creating crypto key: %q", err) + } + + return nil +} diff --git a/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_test.go b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_test.go new file mode 100644 index 0000000..c22c455 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/gcpkms/keysource_test.go @@ -0,0 +1,165 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package gcpkms + +import ( + "encoding/base64" + "fmt" + "log" + "net" + "testing" + "time" + + kmspb "cloud.google.com/go/kms/apiv1/kmspb" + . "github.com/onsi/gomega" + "google.golang.org/grpc" +) + +var ( + testResourceID = "projects/test-flux/locations/global/keyRings/test-flux/cryptoKeys/sops" + decryptedData = "decrypted data" + encryptedData = "encrypted data" +) + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + key := MasterKey{EncryptedKey: encryptedData} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(encryptedData)) +} + +func TestMasterKey_SetEncryptedDataKey(t *testing.T) { + g := NewWithT(t) + enc := "encrypted key" + key := &MasterKey{} + key.SetEncryptedDataKey([]byte(enc)) + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(enc)) +} + +func TestMasterKey_EncryptIfNeeded(t *testing.T) { + g := NewWithT(t) + key := MasterKey{EncryptedKey: "encrypted key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) + + err := key.EncryptIfNeeded([]byte("sops data key")) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_ToString(t *testing.T) { + rsrcId := testResourceID + g := NewWithT(t) + key := MasterKeyFromResourceID(rsrcId) + g.Expect(key.ToString()).To(Equal(rsrcId)) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + key := MasterKey{ + credentialJSON: []byte("sensitive creds"), + CreationDate: time.Date(2016, time.October, 31, 10, 0, 0, 0, time.UTC), + ResourceID: testResourceID, + EncryptedKey: "this is encrypted", + } + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "resource_id": testResourceID, + "enc": "this is encrypted", + "created_at": "2016-10-31T10:00:00Z", + })) +} + +func TestMasterKey_createCloudKMSService(t *testing.T) { + g := NewWithT(t) + + tests := []struct { + key MasterKey + errString string + }{ + { + key: MasterKey{ + ResourceID: "/projects", + credentialJSON: []byte("some secret"), + }, + errString: "no valid resourceId", + }, + { + key: MasterKey{ + ResourceID: testResourceID, + credentialJSON: []byte(`{ "client_id": ".apps.googleusercontent.com", + "client_secret": "", + "type": "authorized_user"}`), + }, + }, + } + + for _, tt := range tests { + _, err := tt.key.newKMSClient() + if tt.errString != "" { + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring(tt.errString)) + } else { + g.Expect(err).To(BeNil()) + } + } +} + +func TestMasterKey_Decrypt(t *testing.T) { + g := NewWithT(t) + + mockKeyManagement.err = nil + mockKeyManagement.reqs = nil + mockKeyManagement.resps = append(mockKeyManagement.resps[:0], &kmspb.DecryptResponse{ + Plaintext: []byte(decryptedData), + }) + key := MasterKey{ + grpcConn: newGRPCServer("0"), + ResourceID: testResourceID, + EncryptedKey: "encryptedKey", + } + data, err := key.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(data).To(BeEquivalentTo(decryptedData)) +} + +func TestMasterKey_Encrypt(t *testing.T) { + g := NewWithT(t) + + mockKeyManagement.err = nil + mockKeyManagement.reqs = nil + mockKeyManagement.resps = append(mockKeyManagement.resps[:0], &kmspb.EncryptResponse{ + Ciphertext: []byte(encryptedData), + }) + + key := MasterKey{ + grpcConn: newGRPCServer("0"), + ResourceID: testResourceID, + } + err := key.Encrypt([]byte("encrypt")) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(base64.StdEncoding.EncodeToString([]byte(encryptedData)))) +} + +var ( + mockKeyManagement mockKeyManagementServer +) + +func newGRPCServer(port string) *grpc.ClientConn { + serv := grpc.NewServer() + kmspb.RegisterKeyManagementServiceServer(serv, &mockKeyManagement) + + lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%s", port)) + if err != nil { + log.Fatal(err) + } + go serv.Serve(lis) + + conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure()) + if err != nil { + log.Fatal(err) + } + + return conn +} diff --git a/internal/decryptors/sops/kustomize-controller/gcpkms/mock_kms_server_test.go b/internal/decryptors/sops/kustomize-controller/gcpkms/mock_kms_server_test.go new file mode 100644 index 0000000..1cb09ab --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/gcpkms/mock_kms_server_test.go @@ -0,0 +1,328 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Code generated by gapic-generator. DO NOT EDIT. + +// Ref: https://github.com/googleapis/google-cloud-go/blob/4fe86a327f97ada275ce1744459129df38f9c95b/kms/apiv1/mock_test.go + +package gcpkms + +import ( + "context" + "fmt" + "io" + "strings" + + kmspb "cloud.google.com/go/kms/apiv1/kmspb" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" + + status "google.golang.org/genproto/googleapis/rpc/status" + "google.golang.org/grpc/metadata" +) + +var _ = io.EOF +var _ = anypb.New +var _ status.Status + +type mockKeyManagementServer struct { + // Embed for forward compatibility. + // Tests will keep working if more methods are added + // in the future. + kmspb.KeyManagementServiceServer + + reqs []proto.Message + + // If set, all calls return this error. + err error + + // responses to return if err == nil + resps []proto.Message +} + +func (s *mockKeyManagementServer) ListKeyRings(ctx context.Context, req *kmspb.ListKeyRingsRequest) (*kmspb.ListKeyRingsResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ListKeyRingsResponse), nil +} + +func (s *mockKeyManagementServer) ListCryptoKeys(ctx context.Context, req *kmspb.ListCryptoKeysRequest) (*kmspb.ListCryptoKeysResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ListCryptoKeysResponse), nil +} + +func (s *mockKeyManagementServer) ListCryptoKeyVersions(ctx context.Context, req *kmspb.ListCryptoKeyVersionsRequest) (*kmspb.ListCryptoKeyVersionsResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ListCryptoKeyVersionsResponse), nil +} + +func (s *mockKeyManagementServer) ListImportJobs(ctx context.Context, req *kmspb.ListImportJobsRequest) (*kmspb.ListImportJobsResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ListImportJobsResponse), nil +} + +func (s *mockKeyManagementServer) GetKeyRing(ctx context.Context, req *kmspb.GetKeyRingRequest) (*kmspb.KeyRing, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.KeyRing), nil +} + +func (s *mockKeyManagementServer) GetCryptoKey(ctx context.Context, req *kmspb.GetCryptoKeyRequest) (*kmspb.CryptoKey, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKey), nil +} + +func (s *mockKeyManagementServer) GetCryptoKeyVersion(ctx context.Context, req *kmspb.GetCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} + +func (s *mockKeyManagementServer) GetPublicKey(ctx context.Context, req *kmspb.GetPublicKeyRequest) (*kmspb.PublicKey, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.PublicKey), nil +} + +func (s *mockKeyManagementServer) GetImportJob(ctx context.Context, req *kmspb.GetImportJobRequest) (*kmspb.ImportJob, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ImportJob), nil +} + +func (s *mockKeyManagementServer) CreateKeyRing(ctx context.Context, req *kmspb.CreateKeyRingRequest) (*kmspb.KeyRing, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.KeyRing), nil +} + +func (s *mockKeyManagementServer) CreateCryptoKey(ctx context.Context, req *kmspb.CreateCryptoKeyRequest) (*kmspb.CryptoKey, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKey), nil +} + +func (s *mockKeyManagementServer) CreateCryptoKeyVersion(ctx context.Context, req *kmspb.CreateCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} + +func (s *mockKeyManagementServer) ImportCryptoKeyVersion(ctx context.Context, req *kmspb.ImportCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} + +func (s *mockKeyManagementServer) CreateImportJob(ctx context.Context, req *kmspb.CreateImportJobRequest) (*kmspb.ImportJob, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.ImportJob), nil +} + +func (s *mockKeyManagementServer) UpdateCryptoKey(ctx context.Context, req *kmspb.UpdateCryptoKeyRequest) (*kmspb.CryptoKey, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKey), nil +} + +func (s *mockKeyManagementServer) UpdateCryptoKeyVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} + +func (s *mockKeyManagementServer) Encrypt(ctx context.Context, req *kmspb.EncryptRequest) (*kmspb.EncryptResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.EncryptResponse), nil +} + +func (s *mockKeyManagementServer) Decrypt(ctx context.Context, req *kmspb.DecryptRequest) (*kmspb.DecryptResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.DecryptResponse), nil +} + +func (s *mockKeyManagementServer) AsymmetricSign(ctx context.Context, req *kmspb.AsymmetricSignRequest) (*kmspb.AsymmetricSignResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.AsymmetricSignResponse), nil +} + +func (s *mockKeyManagementServer) AsymmetricDecrypt(ctx context.Context, req *kmspb.AsymmetricDecryptRequest) (*kmspb.AsymmetricDecryptResponse, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.AsymmetricDecryptResponse), nil +} + +func (s *mockKeyManagementServer) UpdateCryptoKeyPrimaryVersion(ctx context.Context, req *kmspb.UpdateCryptoKeyPrimaryVersionRequest) (*kmspb.CryptoKey, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKey), nil +} + +func (s *mockKeyManagementServer) DestroyCryptoKeyVersion(ctx context.Context, req *kmspb.DestroyCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} + +func (s *mockKeyManagementServer) RestoreCryptoKeyVersion(ctx context.Context, req *kmspb.RestoreCryptoKeyVersionRequest) (*kmspb.CryptoKeyVersion, error) { + md, _ := metadata.FromIncomingContext(ctx) + if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") { + return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg) + } + s.reqs = append(s.reqs, req) + if s.err != nil { + return nil, s.err + } + return s.resps[0].(*kmspb.CryptoKeyVersion), nil +} diff --git a/internal/decryptors/sops/kustomize-controller/hcvault/keysource.go b/internal/decryptors/sops/kustomize-controller/hcvault/keysource.go new file mode 100644 index 0000000..cfbfde0 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/hcvault/keysource.go @@ -0,0 +1,217 @@ +// Copyright (C) 2020 The Mozilla SOPS authors +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package hcvault + +import ( + "encoding/base64" + "fmt" + "path" + "time" + + "github.com/hashicorp/vault/api" +) + +var ( + // vaultTTL is the duration after which a MasterKey requires rotation. + vaultTTL = time.Hour * 24 * 30 * 6 +) + +// VaultToken used for authenticating towards a Vault server. +type VaultToken string + +// ApplyToMasterKey configures the token on the provided key. +func (t VaultToken) ApplyToMasterKey(key *MasterKey) { + key.vaultToken = string(t) +} + +// MasterKey is a Vault Transit backend path used to Encrypt and Decrypt +// SOPS' data key. +// +// Adapted from https://github.com/mozilla/sops/blob/v3.7.1/hcvault/keysource.go +// to be able to have fine-grain control over the used decryption keys +// without relying on the existence of environment variable or file. +type MasterKey struct { + KeyName string + EnginePath string + VaultAddress string + + EncryptedKey string + CreationDate time.Time + + vaultToken string +} + +// MasterKeyFromAddress creates a new MasterKey from a Vault address, Transit +// backend path and a key name. +func MasterKeyFromAddress(address, enginePath, keyName string) *MasterKey { + key := &MasterKey{ + VaultAddress: address, + EnginePath: enginePath, + KeyName: keyName, + CreationDate: time.Now().UTC(), + } + return key +} + +// Encrypt takes a SOPS data key, encrypts it with Vault Transit, and stores +// the result in the EncryptedKey field. +func (key *MasterKey) Encrypt(dataKey []byte) error { + client, err := vaultClient(key.VaultAddress, key.vaultToken) + if err != nil { + return err + } + + fullPath := key.encryptPath() + secret, err := client.Logical().Write(fullPath, encryptPayload(dataKey)) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key to Vault transit backend '%s': %w", fullPath, err) + } + encryptedKey, err := encryptedKeyFromSecret(secret) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key to Vault transit backend '%s': %w", fullPath, err) + } + key.EncryptedKey = encryptedKey + return nil +} + +// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been +// encrypted yet. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// EncryptedDataKey returns the encrypted data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// SetEncryptedDataKey sets the encrypted data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// Decrypt decrypts the EncryptedKey field with Vault Transit and returns the result. +func (key *MasterKey) Decrypt() ([]byte, error) { + client, err := vaultClient(key.VaultAddress, key.vaultToken) + if err != nil { + return nil, err + } + + fullPath := key.decryptPath() + secret, err := client.Logical().Write(fullPath, decryptPayload(key.EncryptedKey)) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key from Vault transit backend '%s': %w", fullPath, err) + } + dataKey, err := dataKeyFromSecret(secret) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key from Vault transit backend '%s': %w", fullPath, err) + } + return dataKey, nil +} + +// NeedsRotation returns whether the data key needs to be rotated or not. +func (key *MasterKey) NeedsRotation() bool { + // TODO: manage rewrapping https://www.vaultproject.io/api/secret/transit/index.html#rewrap-data + return time.Since(key.CreationDate) > (vaultTTL) +} + +// ToString converts the key to a string representation. +func (key *MasterKey) ToString() string { + return fmt.Sprintf("%s/v1/%s/keys/%s", key.VaultAddress, key.EnginePath, key.KeyName) +} + +// ToMap converts the MasterKey to a map for serialization purposes. +func (key MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["vault_address"] = key.VaultAddress + out["key_name"] = key.KeyName + out["engine_path"] = key.EnginePath + out["enc"] = key.EncryptedKey + out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) + return out +} + +// encryptPath returns the path for Encrypt requests. +func (key *MasterKey) encryptPath() string { + return path.Join(key.EnginePath, "encrypt", key.KeyName) +} + +// decryptPath returns the path for Decrypt requests. +func (key *MasterKey) decryptPath() string { + return path.Join(key.EnginePath, "decrypt", key.KeyName) +} + +// encryptPayload returns the payload for an encrypt request of the dataKey. +func encryptPayload(dataKey []byte) map[string]interface{} { + encoded := base64.StdEncoding.EncodeToString(dataKey) + return map[string]interface{}{ + "plaintext": encoded, + } +} + +// encryptedKeyFromSecret attempts to extract the encrypted key from the data +// of the provided secret. +func encryptedKeyFromSecret(secret *api.Secret) (string, error) { + if secret == nil || secret.Data == nil { + return "", fmt.Errorf("transit backend is empty") + } + encrypted, ok := secret.Data["ciphertext"] + if !ok { + return "", fmt.Errorf("no encrypted data") + } + encryptedKey, ok := encrypted.(string) + if !ok { + return "", fmt.Errorf("encrypted ciphertext cannot be cast to string") + } + return encryptedKey, nil +} + +// decryptPayload returns the payload for a decrypt request of the +// encryptedKey. +func decryptPayload(encryptedKey string) map[string]interface{} { + return map[string]interface{}{ + "ciphertext": encryptedKey, + } +} + +// dataKeyFromSecret attempts to extract the data key from the data of the +// provided secret. +func dataKeyFromSecret(secret *api.Secret) ([]byte, error) { + if secret == nil || secret.Data == nil { + return nil, fmt.Errorf("transit backend is empty") + } + decrypted, ok := secret.Data["plaintext"] + if !ok { + return nil, fmt.Errorf("no decrypted data") + } + plaintext, ok := decrypted.(string) + if !ok { + return nil, fmt.Errorf("decrypted plaintext data cannot be cast to string") + } + dataKey, err := base64.StdEncoding.DecodeString(plaintext) + if err != nil { + return nil, fmt.Errorf("cannot decode base64 plaintext into data key bytes") + } + return dataKey, nil +} + +// vaultClient returns a new Vault client, configured with the given address +// and token. +func vaultClient(address, token string) (*api.Client, error) { + cfg := api.DefaultConfig() + cfg.Address = address + client, err := api.NewClient(cfg) + if err != nil { + return nil, fmt.Errorf("cannot create Vault client: %w", err) + } + client.SetToken(token) + return client, nil +} diff --git a/internal/decryptors/sops/kustomize-controller/hcvault/keysource_test.go b/internal/decryptors/sops/kustomize-controller/hcvault/keysource_test.go new file mode 100644 index 0000000..dfeabf2 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/hcvault/keysource_test.go @@ -0,0 +1,371 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package hcvault + +import ( + "fmt" + logger "log" + "os" + "path" + "testing" + "time" + + "github.com/hashicorp/vault/api" + . "github.com/onsi/gomega" + "github.com/ory/dockertest/v3" + "go.mozilla.org/sops/v3/hcvault" +) + +var ( + // testVaultVersion is the version (image tag) of the Vault server image + // used to test against. + testVaultVersion = "1.10.0" + // testVaultToken is the token of the Vault server. + testVaultToken = "secret" + // testEnginePath is the path to mount the Vault Transit on. + testEnginePath = "sops" + // testVaultAddress is the HTTP/S address of the Vault server, it is set + // by TestMain after booting it. + testVaultAddress string +) + +// TestMain initializes a Vault server using Docker, writes the HTTP address to +// testVaultAddress, waits for it to become ready to serve requests, and enables +// Vault Transit on the testEnginePath. It then runs all the tests, which can +// make use of the various `test*` variables. +func TestMain(m *testing.M) { + // Uses a sensible default on Windows (TCP/HTTP) and Linux/MacOS (socket) + pool, err := dockertest.NewPool("") + if err != nil { + logger.Fatalf("could not connect to docker: %s", err) + } + + // Pull the image, create a container based on it, and run it + resource, err := pool.Run("vault", testVaultVersion, []string{"VAULT_DEV_ROOT_TOKEN_ID=" + testVaultToken}) + if err != nil { + logger.Fatalf("could not start resource: %s", err) + } + + purgeResource := func() { + if err := pool.Purge(resource); err != nil { + logger.Printf("could not purge resource: %s", err) + } + } + + testVaultAddress = fmt.Sprintf("http://127.0.0.1:%v", resource.GetPort("8200/tcp")) + // Wait until Vault is ready to serve requests + if err := pool.Retry(func() error { + cfg := api.DefaultConfig() + cfg.Address = testVaultAddress + cli, err := api.NewClient(cfg) + if err != nil { + return fmt.Errorf("cannot create Vault client: %w", err) + } + status, err := cli.Sys().InitStatus() + if err != nil { + return err + } + if status != true { + return fmt.Errorf("waiting on Vault server to become ready") + } + return nil + }); err != nil { + purgeResource() + logger.Fatalf("could not connect to docker: %s", err) + } + + if err = enableVaultTransit(testVaultAddress, testVaultToken, testEnginePath); err != nil { + purgeResource() + logger.Fatalf("could not enable Vault transit: %s", err) + } + + // Run the tests, but only if we succeeded in setting up the Vault server + var code int + if err == nil { + code = m.Run() + } + + // This can't be deferred, as os.Exit simpy does not care + if err := pool.Purge(resource); err != nil { + logger.Fatalf("could not purge resource: %s", err) + } + + os.Exit(code) +} + +func TestMasterKey_Encrypt(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromAddress(testVaultAddress, testEnginePath, "encrypt") + (VaultToken(testVaultToken)).ApplyToMasterKey(key) + g.Expect(createVaultKey(key)).To(Succeed()) + + dataKey := []byte("the majority of your brain is fat") + g.Expect(key.Encrypt(dataKey)).To(Succeed()) + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + + client, err := vaultClient(key.VaultAddress, key.vaultToken) + g.Expect(err).ToNot(HaveOccurred()) + + payload := decryptPayload(key.EncryptedKey) + secret, err := client.Logical().Write(key.decryptPath(), payload) + g.Expect(err).ToNot(HaveOccurred()) + + decryptedData, err := dataKeyFromSecret(secret) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decryptedData).To(Equal(dataKey)) + + key.EnginePath = "invalid" + g.Expect(key.Encrypt(dataKey)).To(HaveOccurred()) + + key.EnginePath = testEnginePath + key.vaultToken = "" + g.Expect(key.Encrypt(dataKey)).To(HaveOccurred()) +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + encryptKey := MasterKeyFromAddress(testVaultAddress, testEnginePath, "encrypt-compat") + (VaultToken(testVaultToken)).ApplyToMasterKey(encryptKey) + g.Expect(createVaultKey(encryptKey)).To(Succeed()) + + dataKey := []byte("foo") + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + t.Setenv("VAULT_ADDR", testVaultAddress) + t.Setenv("VAULT_TOKEN", testVaultToken) + decryptKey := hcvault.NewMasterKey(testVaultAddress, testEnginePath, "encrypt-compat") + decryptKey.EncryptedKey = encryptKey.EncryptedKey + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptIfNeeded(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromAddress(testVaultAddress, testEnginePath, "encrypt-if-needed") + (VaultToken(testVaultToken)).ApplyToMasterKey(key) + g.Expect(createVaultKey(key)).To(Succeed()) + + g.Expect(key.EncryptIfNeeded([]byte("data"))).To(Succeed()) + + encryptedKey := key.EncryptedKey + g.Expect(encryptedKey).ToNot(BeEmpty()) + + g.Expect(key.EncryptIfNeeded([]byte("some other data"))).To(Succeed()) + g.Expect(key.EncryptedKey).To(Equal(encryptedKey)) +} + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{EncryptedKey: "some key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_Decrypt(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromAddress(testVaultAddress, testEnginePath, "decrypt") + (VaultToken(testVaultToken)).ApplyToMasterKey(key) + g.Expect(createVaultKey(key)).To(Succeed()) + + client, err := vaultClient(key.VaultAddress, key.vaultToken) + g.Expect(err).ToNot(HaveOccurred()) + + dataKey := []byte("the heart of a shrimp is located in its head") + secret, err := client.Logical().Write(key.encryptPath(), encryptPayload(dataKey)) + g.Expect(err).ToNot(HaveOccurred()) + + encryptedKey, err := encryptedKeyFromSecret(secret) + g.Expect(err).NotTo(HaveOccurred()) + + key.EncryptedKey = encryptedKey + got, err := key.Decrypt() + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(got).To(Equal(dataKey)) + + key.EnginePath = "invalid" + g.Expect(key.Encrypt(dataKey)).To(HaveOccurred()) + + key.EnginePath = testEnginePath + key.vaultToken = "" + g.Expect(key.Encrypt(dataKey)).To(HaveOccurred()) +} + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + decryptKey := MasterKeyFromAddress(testVaultAddress, testEnginePath, "decrypt-compat") + (VaultToken(testVaultToken)).ApplyToMasterKey(decryptKey) + g.Expect(createVaultKey(decryptKey)).To(Succeed()) + + dataKey := []byte("foo") + + t.Setenv("VAULT_ADDR", testVaultAddress) + t.Setenv("VAULT_TOKEN", testVaultToken) + encryptKey := hcvault.NewMasterKey(testVaultAddress, testEnginePath, "decrypt-compat") + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + decryptKey.EncryptedKey = encryptKey.EncryptedKey + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + token := VaultToken(testVaultToken) + + encryptKey := MasterKeyFromAddress(testVaultAddress, testEnginePath, "roundtrip") + token.ApplyToMasterKey(encryptKey) + g.Expect(createVaultKey(encryptKey)).To(Succeed()) + + dataKey := []byte("some people have an extra bone in their knee") + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + g.Expect(encryptKey.EncryptedKey).ToNot(BeEmpty()) + + decryptKey := MasterKeyFromAddress(testVaultAddress, testEnginePath, "roundtrip") + token.ApplyToMasterKey(decryptKey) + decryptKey.EncryptedKey = encryptKey.EncryptedKey + + decryptedData, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decryptedData).To(Equal(dataKey)) +} + +func TestMasterKey_NeedsRotation(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromAddress("", "", "") + g.Expect(key.NeedsRotation()).To(BeFalse()) + + key.CreationDate = key.CreationDate.Add(-(vaultTTL + time.Second)) + g.Expect(key.NeedsRotation()).To(BeTrue()) +} + +func TestMasterKey_ToString(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromAddress("https://example.com", "engine", "key-name") + g.Expect(key.ToString()).To(Equal("https://example.com/v1/engine/keys/key-name")) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{ + KeyName: "test-key", + EnginePath: "engine", + VaultAddress: testVaultAddress, + EncryptedKey: "some-encrypted-key", + } + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "vault_address": key.VaultAddress, + "key_name": key.KeyName, + "engine_path": key.EnginePath, + "enc": key.EncryptedKey, + "created_at": "0001-01-01T00:00:00Z", + })) +} + +func Test_encryptedKeyFromSecret(t *testing.T) { + tests := []struct { + name string + secret *api.Secret + want string + wantErr bool + }{ + {name: "nil secret", secret: nil, wantErr: true}, + {name: "secret with nil data", secret: &api.Secret{Data: nil}, wantErr: true}, + {name: "secret without ciphertext data", secret: &api.Secret{Data: map[string]interface{}{"other": true}}, wantErr: true}, + {name: "ciphertext non string", secret: &api.Secret{Data: map[string]interface{}{"ciphertext": 123}}, wantErr: true}, + {name: "ciphertext data", secret: &api.Secret{Data: map[string]interface{}{"ciphertext": "secret string"}}, want: "secret string"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + got, err := encryptedKeyFromSecret(tt.secret) + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(got).To(BeEmpty()) + return + } + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(got).To(Equal(tt.want)) + }) + } +} + +func Test_dataKeyFromSecret(t *testing.T) { + tests := []struct { + name string + secret *api.Secret + want []byte + wantErr bool + }{ + {name: "nil secret", secret: nil, wantErr: true}, + {name: "secret with nil data", secret: &api.Secret{Data: nil}, wantErr: true}, + {name: "secret without plaintext data", secret: &api.Secret{Data: map[string]interface{}{"other": true}}, wantErr: true}, + {name: "plaintext non string", secret: &api.Secret{Data: map[string]interface{}{"plaintext": 123}}, wantErr: true}, + {name: "plaintext non base64", secret: &api.Secret{Data: map[string]interface{}{"plaintext": "notbase64"}}, wantErr: true}, + {name: "plaintext base64 data", secret: &api.Secret{Data: map[string]interface{}{"plaintext": "Zm9v"}}, want: []byte("foo")}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + g := NewWithT(t) + + got, err := dataKeyFromSecret(tt.secret) + if tt.wantErr { + g.Expect(err).To(HaveOccurred()) + g.Expect(got).To(BeNil()) + return + } + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(got).To(Equal(tt.want)) + }) + } +} + +// enableVaultTransit enables the Vault Transit backend on the given enginePath. +func enableVaultTransit(address, token, enginePath string) error { + client, err := vaultClient(address, token) + if err != nil { + return fmt.Errorf("cannot create Vault client: %w", err) + } + + if err = client.Sys().Mount(enginePath, &api.MountInput{ + Type: "transit", + Description: "backend transit used by SOPS", + }); err != nil { + return fmt.Errorf("failed to mount transit on engine path '%s': %w", enginePath, err) + } + return nil +} + +// createVaultKey creates a new RSA-4096 Vault key using the data from the +// provided MasterKey. +func createVaultKey(key *MasterKey) error { + client, err := vaultClient(key.VaultAddress, key.vaultToken) + if err != nil { + return fmt.Errorf("cannot create Vault client: %w", err) + } + + p := path.Join(key.EnginePath, "keys", key.KeyName) + payload := make(map[string]interface{}) + payload["type"] = "rsa-4096" + if _, err = client.Logical().Write(p, payload); err != nil { + return err + } + + _, err = client.Logical().Read(p) + return err +} diff --git a/internal/decryptors/sops/kustomize-controller/keyservice/keyservice.go b/internal/decryptors/sops/kustomize-controller/keyservice/keyservice.go new file mode 100644 index 0000000..4d2dda5 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/keyservice/keyservice.go @@ -0,0 +1,23 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + "go.mozilla.org/sops/v3/age" + "go.mozilla.org/sops/v3/keys" + "go.mozilla.org/sops/v3/pgp" +) + +// IsOfflineMethod returns true for offline decrypt methods or false otherwise +func IsOfflineMethod(mk keys.MasterKey) bool { + switch mk.(type) { + case *pgp.MasterKey, *age.MasterKey: + return true + default: + return false + } +} diff --git a/internal/decryptors/sops/kustomize-controller/keyservice/options.go b/internal/decryptors/sops/kustomize-controller/keyservice/options.go new file mode 100644 index 0000000..76204f1 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/keyservice/options.go @@ -0,0 +1,88 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + extage "filippo.io/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/gcpkms" + "go.mozilla.org/sops/v3/keyservice" + + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/awskms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/azkv" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/hcvault" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/pgp" +) + +// ServerOption is some configuration that modifies the Server. +type ServerOption interface { + // ApplyToServer applies this configuration to the given Server. + ApplyToServer(s *Server) +} + +// WithGnuPGHome configures the GnuPG home directory on the Server. +type WithGnuPGHome string + +// ApplyToServer applies this configuration to the given Server. +func (o WithGnuPGHome) ApplyToServer(s *Server) { + s.gnuPGHome = pgp.GnuPGHome(o) +} + +// WithVaultToken configures the Hashicorp Vault token on the Server. +type WithVaultToken string + +// ApplyToServer applies this configuration to the given Server. +func (o WithVaultToken) ApplyToServer(s *Server) { + s.vaultToken = hcvault.VaultToken(o) +} + +// WithAgeIdentities configures the parsed age identities on the Server. +type WithAgeIdentities []extage.Identity + +// ApplyToServer applies this configuration to the given Server. +func (o WithAgeIdentities) ApplyToServer(s *Server) { + s.ageIdentities = age.ParsedIdentities(o) +} + +// WithAWSKeys configures the AWS credentials on the Server +type WithAWSKeys struct { + CredsProvider *awskms.CredsProvider +} + +// ApplyToServer applies this configuration to the given Server. +func (o WithAWSKeys) ApplyToServer(s *Server) { + s.awsCredsProvider = o.CredsProvider +} + +// WithGCPCredsJSON configures the GCP service account credentials JSON on the +// Server. +type WithGCPCredsJSON []byte + +// ApplyToServer applies this configuration to the given Server. +func (o WithGCPCredsJSON) ApplyToServer(s *Server) { + s.gcpCredsJSON = gcpkms.CredentialJSON(o) +} + +// WithAzureToken configures the Azure credential token on the Server. +type WithAzureToken struct { + Token *azkv.Token +} + +// ApplyToServer applies this configuration to the given Server. +func (o WithAzureToken) ApplyToServer(s *Server) { + s.azureToken = o.Token +} + +// WithDefaultServer configures the fallback default server on the Server. +type WithDefaultServer struct { + Server keyservice.KeyServiceServer +} + +// ApplyToServer applies this configuration to the given Server. +func (o WithDefaultServer) ApplyToServer(s *Server) { + s.defaultServer = o.Server +} diff --git a/internal/decryptors/sops/kustomize-controller/keyservice/server.go b/internal/decryptors/sops/kustomize-controller/keyservice/server.go new file mode 100644 index 0000000..231d3cb --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/keyservice/server.go @@ -0,0 +1,362 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + "fmt" + + "go.mozilla.org/sops/v3/keyservice" + "golang.org/x/net/context" + + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/awskms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/azkv" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/gcpkms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/hcvault" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/pgp" +) + +// Server is a key service server that uses SOPS MasterKeys to fulfill +// requests. It intercepts Encrypt and Decrypt requests made for key types +// that need to run in a contained environment, instead of the default +// implementation which heavily utilizes environment variables or the runtime +// environment. Any request not handled by the Server is forwarded to the +// embedded default server. +type Server struct { + // gnuPGHome is the GnuPG home directory used for the Encrypt and Decrypt + // operations for PGP key types. + // When empty, the requests will be handled using the systems' runtime + // keyring. + gnuPGHome pgp.GnuPGHome + + // ageIdentities are the parsed age identities used for Decrypt + // operations for age key types. + ageIdentities age.ParsedIdentities + + // vaultToken is the token used for Encrypt and Decrypt operations of + // Hashicorp Vault requests. + // When empty, the request will be handled by defaultServer. + vaultToken hcvault.VaultToken + + // azureToken is the credential token used for Encrypt and Decrypt + // operations of Azure Key Vault requests. + // When nil, the request will be handled by defaultServer. + azureToken *azkv.Token + + // awsCredsProvider is the Credentials object used for Encrypt and Decrypt + // operations of AWS KMS requests. + // When nil, the request will be handled by defaultServer. + awsCredsProvider *awskms.CredsProvider + + // gcpCredsJSON is the JSON credentials used for Decrypt and Encrypt + // operations of GCP KMS requests. When nil, a default client with + // environmental runtime settings will be used. + gcpCredsJSON gcpkms.CredentialJSON + + // defaultServer is the fallback server, used to handle any request that + // is not eligible to be handled by this Server. + defaultServer keyservice.KeyServiceServer +} + +// NewServer constructs a new Server, configuring it with the provided options +// before returning the result. +// When WithDefaultServer() is not provided as an option, the SOPS server +// implementation is configured as default. +func NewServer(options ...ServerOption) keyservice.KeyServiceServer { + s := &Server{} + for _, opt := range options { + opt.ApplyToServer(s) + } + if s.defaultServer == nil { + s.defaultServer = &keyservice.Server{ + Prompt: false, + } + } + return s +} + +// Encrypt takes an encrypt request and encrypts the provided plaintext with +// the provided key, returning the encrypted result. +func (ks Server) Encrypt(ctx context.Context, req *keyservice.EncryptRequest) (*keyservice.EncryptResponse, error) { + key := req.Key + switch k := key.KeyType.(type) { + case *keyservice.Key_PgpKey: + ciphertext, err := ks.encryptWithPgp(k.PgpKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: ciphertext, + }, nil + case *keyservice.Key_AgeKey: + ciphertext, err := ks.encryptWithAge(k.AgeKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: ciphertext, + }, nil + case *keyservice.Key_VaultKey: + if ks.vaultToken != "" { + ciphertext, err := ks.encryptWithHCVault(k.VaultKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: ciphertext, + }, nil + } + case *keyservice.Key_KmsKey: + cipherText, err := ks.encryptWithAWSKMS(k.KmsKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: cipherText, + }, nil + case *keyservice.Key_AzureKeyvaultKey: + ciphertext, err := ks.encryptWithAzureKeyVault(k.AzureKeyvaultKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: ciphertext, + }, nil + case *keyservice.Key_GcpKmsKey: + ciphertext, err := ks.encryptWithGCPKMS(k.GcpKmsKey, req.Plaintext) + if err != nil { + return nil, err + } + return &keyservice.EncryptResponse{ + Ciphertext: ciphertext, + }, nil + case nil: + return nil, fmt.Errorf("must provide a key") + } + // Fallback to default server for any other request. + return ks.defaultServer.Encrypt(ctx, req) +} + +// Decrypt takes a decrypt request and decrypts the provided ciphertext with +// the provided key, returning the decrypted result. +func (ks Server) Decrypt(ctx context.Context, req *keyservice.DecryptRequest) (*keyservice.DecryptResponse, error) { + key := req.Key + switch k := key.KeyType.(type) { + case *keyservice.Key_PgpKey: + plaintext, err := ks.decryptWithPgp(k.PgpKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + case *keyservice.Key_AgeKey: + plaintext, err := ks.decryptWithAge(k.AgeKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + case *keyservice.Key_VaultKey: + if ks.vaultToken != "" { + plaintext, err := ks.decryptWithHCVault(k.VaultKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + } + case *keyservice.Key_KmsKey: + plaintext, err := ks.decryptWithAWSKMS(k.KmsKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + case *keyservice.Key_AzureKeyvaultKey: + plaintext, err := ks.decryptWithAzureKeyVault(k.AzureKeyvaultKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + case *keyservice.Key_GcpKmsKey: + plaintext, err := ks.decryptWithGCPKMS(k.GcpKmsKey, req.Ciphertext) + if err != nil { + return nil, err + } + return &keyservice.DecryptResponse{ + Plaintext: plaintext, + }, nil + case nil: + return nil, fmt.Errorf("must provide a key") + } + // Fallback to default server for any other request. + return ks.defaultServer.Decrypt(ctx, req) +} + +func (ks *Server) encryptWithPgp(key *keyservice.PgpKey, plaintext []byte) ([]byte, error) { + pgpKey := pgp.MasterKeyFromFingerprint(key.Fingerprint) + if ks.gnuPGHome != "" { + ks.gnuPGHome.ApplyToMasterKey(pgpKey) + } + err := pgpKey.Encrypt(plaintext) + if err != nil { + return nil, err + } + return []byte(pgpKey.EncryptedKey), nil +} + +func (ks *Server) decryptWithPgp(key *keyservice.PgpKey, ciphertext []byte) ([]byte, error) { + pgpKey := pgp.MasterKeyFromFingerprint(key.Fingerprint) + if ks.gnuPGHome != "" { + ks.gnuPGHome.ApplyToMasterKey(pgpKey) + } + pgpKey.EncryptedKey = string(ciphertext) + plaintext, err := pgpKey.Decrypt() + return plaintext, err +} + +func (ks Server) encryptWithAge(key *keyservice.AgeKey, plaintext []byte) ([]byte, error) { + // Unlike the other encrypt and decrypt methods, validation of configuration + // is not required here. As the encryption happens purely based on the + // Recipient from the key. + + ageKey := age.MasterKey{ + Recipient: key.Recipient, + } + if err := ageKey.Encrypt(plaintext); err != nil { + return nil, err + } + return []byte(ageKey.EncryptedKey), nil +} + +func (ks *Server) decryptWithAge(key *keyservice.AgeKey, ciphertext []byte) ([]byte, error) { + ageKey := age.MasterKey{ + Recipient: key.Recipient, + } + ks.ageIdentities.ApplyToMasterKey(&ageKey) + ageKey.EncryptedKey = string(ciphertext) + plaintext, err := ageKey.Decrypt() + return plaintext, err +} + +func (ks *Server) encryptWithHCVault(key *keyservice.VaultKey, plaintext []byte) ([]byte, error) { + vaultKey := hcvault.MasterKey{ + VaultAddress: key.VaultAddress, + EnginePath: key.EnginePath, + KeyName: key.KeyName, + } + ks.vaultToken.ApplyToMasterKey(&vaultKey) + if err := vaultKey.Encrypt(plaintext); err != nil { + return nil, err + } + return []byte(vaultKey.EncryptedKey), nil +} + +func (ks *Server) decryptWithHCVault(key *keyservice.VaultKey, ciphertext []byte) ([]byte, error) { + vaultKey := hcvault.MasterKey{ + VaultAddress: key.VaultAddress, + EnginePath: key.EnginePath, + KeyName: key.KeyName, + } + vaultKey.EncryptedKey = string(ciphertext) + ks.vaultToken.ApplyToMasterKey(&vaultKey) + plaintext, err := vaultKey.Decrypt() + return plaintext, err +} + +func (ks *Server) encryptWithAWSKMS(key *keyservice.KmsKey, plaintext []byte) ([]byte, error) { + context := make(map[string]string) + for key, val := range key.Context { + context[key] = val + } + awsKey := awskms.MasterKey{ + Arn: key.Arn, + Role: key.Role, + EncryptionContext: context, + } + if ks.awsCredsProvider != nil { + ks.awsCredsProvider.ApplyToMasterKey(&awsKey) + } + if err := awsKey.Encrypt(plaintext); err != nil { + return nil, err + } + return []byte(awsKey.EncryptedKey), nil +} + +func (ks *Server) decryptWithAWSKMS(key *keyservice.KmsKey, cipherText []byte) ([]byte, error) { + context := make(map[string]string) + for key, val := range key.Context { + context[key] = val + } + awsKey := awskms.MasterKey{ + Arn: key.Arn, + Role: key.Role, + EncryptionContext: context, + } + awsKey.EncryptedKey = string(cipherText) + + if ks.awsCredsProvider != nil { + ks.awsCredsProvider.ApplyToMasterKey(&awsKey) + } + return awsKey.Decrypt() +} + +func (ks *Server) encryptWithAzureKeyVault(key *keyservice.AzureKeyVaultKey, plaintext []byte) ([]byte, error) { + azureKey := azkv.MasterKey{ + VaultURL: key.VaultUrl, + Name: key.Name, + Version: key.Version, + } + if ks.azureToken != nil { + ks.azureToken.ApplyToMasterKey(&azureKey) + } + if err := azureKey.Encrypt(plaintext); err != nil { + return nil, err + } + return []byte(azureKey.EncryptedKey), nil +} + +func (ks *Server) decryptWithAzureKeyVault(key *keyservice.AzureKeyVaultKey, ciphertext []byte) ([]byte, error) { + azureKey := azkv.MasterKey{ + VaultURL: key.VaultUrl, + Name: key.Name, + Version: key.Version, + } + if ks.azureToken != nil { + ks.azureToken.ApplyToMasterKey(&azureKey) + } + azureKey.EncryptedKey = string(ciphertext) + plaintext, err := azureKey.Decrypt() + return plaintext, err +} + +func (ks *Server) encryptWithGCPKMS(key *keyservice.GcpKmsKey, plaintext []byte) ([]byte, error) { + gcpKey := gcpkms.MasterKey{ + ResourceID: key.ResourceId, + } + ks.gcpCredsJSON.ApplyToMasterKey(&gcpKey) + if err := gcpKey.Encrypt(plaintext); err != nil { + return nil, err + } + return gcpKey.EncryptedDataKey(), nil +} + +func (ks *Server) decryptWithGCPKMS(key *keyservice.GcpKmsKey, ciphertext []byte) ([]byte, error) { + gcpKey := gcpkms.MasterKey{ + ResourceID: key.ResourceId, + } + ks.gcpCredsJSON.ApplyToMasterKey(&gcpKey) + gcpKey.EncryptedKey = string(ciphertext) + plaintext, err := gcpKey.Decrypt() + return plaintext, err +} diff --git a/internal/decryptors/sops/kustomize-controller/keyservice/server_test.go b/internal/decryptors/sops/kustomize-controller/keyservice/server_test.go new file mode 100644 index 0000000..de623d3 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/keyservice/server_test.go @@ -0,0 +1,220 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + "fmt" + "os" + "testing" + + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + "github.com/aws/aws-sdk-go-v2/credentials" + . "github.com/onsi/gomega" + "go.mozilla.org/sops/v3/keyservice" + "golang.org/x/net/context" + + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/awskms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/azkv" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/gcpkms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/hcvault" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/pgp" +) + +func TestServer_EncryptDecrypt_PGP(t *testing.T) { + const ( + mockPublicKey = "../pgp/testdata/public.gpg" + mockPrivateKey = "../pgp/testdata/private.gpg" + mockFingerprint = "B59DAF469E8C948138901A649732075EA221A7EA" + ) + + g := NewWithT(t) + + gnuPGHome, err := pgp.NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPublicKey)).To(Succeed()) + + s := NewServer(WithGnuPGHome(gnuPGHome)) + key := KeyFromMasterKey(pgp.MasterKeyFromFingerprint(mockFingerprint)) + dataKey := []byte("some data key") + encResp, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + Plaintext: dataKey, + }) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(encResp.Ciphertext).ToNot(BeEmpty()) + g.Expect(encResp.Ciphertext).ToNot(Equal(dataKey)) + + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + decResp, err := s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + Ciphertext: encResp.Ciphertext, + }) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decResp.Plaintext).To(Equal(dataKey)) +} + +func TestServer_EncryptDecrypt_age(t *testing.T) { + g := NewWithT(t) + + const ( + mockRecipient string = "age1lzd99uklcjnc0e7d860axevet2cz99ce9pq6tzuzd05l5nr28ams36nvun" + mockIdentity string = "AGE-SECRET-KEY-1G0Q5K9TV4REQ3ZSQRMTMG8NSWQGYT0T7TZ33RAZEE0GZYVZN0APSU24RK7" + ) + + s := NewServer() + key := KeyFromMasterKey(&age.MasterKey{Recipient: mockRecipient}) + dataKey := []byte("some data key") + encResp, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + Plaintext: dataKey, + }) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(encResp.Ciphertext).ToNot(BeEmpty()) + g.Expect(encResp.Ciphertext).ToNot(Equal(dataKey)) + + i := make(age.ParsedIdentities, 0) + g.Expect(i.Import(mockIdentity)).To(Succeed()) + + s = NewServer(WithAgeIdentities(i)) + decResp, err := s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + Ciphertext: encResp.Ciphertext, + }) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decResp.Plaintext).To(Equal(dataKey)) +} + +func TestServer_EncryptDecrypt_HCVault(t *testing.T) { + g := NewWithT(t) + + s := NewServer(WithVaultToken("token")) + key := KeyFromMasterKey(hcvault.MasterKeyFromAddress("https://example.com", "engine-path", "key-name")) + _, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to encrypt sops data key to Vault transit backend")) + + _, err = s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to decrypt sops data key from Vault transit backend")) +} + +func TestServer_EncryptDecrypt_HCVault_Fallback(t *testing.T) { + g := NewWithT(t) + + fallback := NewMockKeyServer() + s := NewServer(WithDefaultServer{Server: fallback}) + + key := KeyFromMasterKey(hcvault.MasterKeyFromAddress("https://example.com", "engine-path", "key-name")) + encReq := &keyservice.EncryptRequest{ + Key: &key, + Plaintext: []byte("some data key"), + } + _, err := s.Encrypt(context.TODO(), encReq) + g.Expect(err).To(HaveOccurred()) + g.Expect(fallback.encryptReqs).To(HaveLen(1)) + g.Expect(fallback.encryptReqs).To(ContainElement(encReq)) + g.Expect(fallback.decryptReqs).To(HaveLen(0)) + + fallback = NewMockKeyServer() + s = NewServer(WithDefaultServer{Server: fallback}) + decReq := &keyservice.DecryptRequest{ + Key: &key, + Ciphertext: []byte("some ciphertext"), + } + _, err = s.Decrypt(context.TODO(), decReq) + g.Expect(fallback.decryptReqs).To(HaveLen(1)) + g.Expect(fallback.decryptReqs).To(ContainElement(decReq)) + g.Expect(fallback.encryptReqs).To(HaveLen(0)) +} + +func TestServer_EncryptDecrypt_awskms(t *testing.T) { + g := NewWithT(t) + s := NewServer(WithAWSKeys{ + CredsProvider: awskms.NewCredsProvider(credentials.StaticCredentialsProvider{}), + }) + + key := KeyFromMasterKey(awskms.NewMasterKeyFromArn("arn:aws:kms:us-west-2:107501996527:key/612d5f0p-p1l3-45e6-aca6-a5b005693a48", nil, "")) + _, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to encrypt sops data key with AWS KMS")) + + _, err = s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to decrypt sops data key with AWS KMS")) +} + +func TestServer_EncryptDecrypt_azkv(t *testing.T) { + g := NewWithT(t) + + identity, err := azidentity.NewDefaultAzureCredential(nil) + g.Expect(err).ToNot(HaveOccurred()) + s := NewServer(WithAzureToken{Token: azkv.NewToken(identity)}) + + key := KeyFromMasterKey(azkv.MasterKeyFromURL("", "", "")) + _, err = s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to encrypt sops data key with Azure Key Vault")) + + _, err = s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to decrypt sops data key with Azure Key Vault")) + +} + +func TestServer_EncryptDecrypt_gcpkms(t *testing.T) { + g := NewWithT(t) + + creds := `{ "client_id": ".apps.googleusercontent.com", + "client_secret": "", + "type": "authorized_user"}` + s := NewServer(WithGCPCredsJSON([]byte(creds))) + + resourceID := "projects/test-flux/locations/global/keyRings/test-flux/cryptoKeys/sops" + key := KeyFromMasterKey(gcpkms.MasterKeyFromResourceID(resourceID)) + _, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to encrypt sops data key with GCP KMS")) + + _, err = s.Decrypt(context.TODO(), &keyservice.DecryptRequest{ + Key: &key, + }) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("failed to decrypt sops data key with GCP KMS")) + +} + +func TestServer_EncryptDecrypt_Nil_KeyType(t *testing.T) { + g := NewWithT(t) + + s := NewServer(WithDefaultServer{NewMockKeyServer()}) + + expectErr := fmt.Errorf("must provide a key") + + _, err := s.Encrypt(context.TODO(), &keyservice.EncryptRequest{Key: &keyservice.Key{KeyType: nil}}) + g.Expect(err).To(Equal(expectErr)) + + _, err = s.Decrypt(context.TODO(), &keyservice.DecryptRequest{Key: &keyservice.Key{KeyType: nil}}) + g.Expect(err).To(Equal(expectErr)) +} diff --git a/internal/decryptors/sops/kustomize-controller/keyservice/utils_test.go b/internal/decryptors/sops/kustomize-controller/keyservice/utils_test.go new file mode 100644 index 0000000..e73b897 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/keyservice/utils_test.go @@ -0,0 +1,105 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package keyservice + +import ( + "context" + "fmt" + + "go.mozilla.org/sops/v3/keys" + "go.mozilla.org/sops/v3/keyservice" + + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/awskms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/azkv" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/gcpkms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/hcvault" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/pgp" +) + +// KeyFromMasterKey converts a SOPS internal MasterKey to an RPC Key that can +// be serialized with Protocol Buffers. +func KeyFromMasterKey(k keys.MasterKey) keyservice.Key { + switch mk := k.(type) { + case *pgp.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_PgpKey{ + PgpKey: &keyservice.PgpKey{ + Fingerprint: mk.Fingerprint, + }, + }, + } + case *hcvault.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_VaultKey{ + VaultKey: &keyservice.VaultKey{ + VaultAddress: mk.VaultAddress, + EnginePath: mk.EnginePath, + KeyName: mk.KeyName, + }, + }, + } + case *awskms.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_KmsKey{ + KmsKey: &keyservice.KmsKey{ + Arn: mk.Arn, + }, + }, + } + case *azkv.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_AzureKeyvaultKey{ + AzureKeyvaultKey: &keyservice.AzureKeyVaultKey{ + VaultUrl: mk.VaultURL, + Name: mk.Name, + Version: mk.Version, + }, + }, + } + case *age.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_AgeKey{ + AgeKey: &keyservice.AgeKey{ + Recipient: mk.Recipient, + }, + }, + } + case *gcpkms.MasterKey: + return keyservice.Key{ + KeyType: &keyservice.Key_GcpKmsKey{ + GcpKmsKey: &keyservice.GcpKmsKey{ + ResourceId: mk.ResourceID, + }, + }, + } + default: + panic(fmt.Sprintf("tried to convert unknown MasterKey type %T to keyservice.Key", mk)) + } +} + +type MockKeyServer struct { + encryptReqs []*keyservice.EncryptRequest + decryptReqs []*keyservice.DecryptRequest +} + +func NewMockKeyServer() *MockKeyServer { + return &MockKeyServer{ + encryptReqs: make([]*keyservice.EncryptRequest, 0), + decryptReqs: make([]*keyservice.DecryptRequest, 0), + } +} + +func (ks *MockKeyServer) Encrypt(_ context.Context, req *keyservice.EncryptRequest) (*keyservice.EncryptResponse, error) { + ks.encryptReqs = append(ks.encryptReqs, req) + return nil, fmt.Errorf("not actually implemented") +} + +func (ks *MockKeyServer) Decrypt(_ context.Context, req *keyservice.DecryptRequest) (*keyservice.DecryptResponse, error) { + ks.decryptReqs = append(ks.decryptReqs, req) + return nil, fmt.Errorf("not actually implemented") +} diff --git a/internal/decryptors/sops/kustomize-controller/pgp/keysource.go b/internal/decryptors/sops/kustomize-controller/pgp/keysource.go new file mode 100644 index 0000000..1d9343d --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/pgp/keysource.go @@ -0,0 +1,286 @@ +// Copyright (C) 2016-2020 The Mozilla SOPS authors +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package pgp + +import ( + "bytes" + "fmt" + "io" + "os" + "os/exec" + "os/user" + "path/filepath" + "strings" + "time" +) + +const ( + // SopsGpgExecEnv can be set as an environment variable to overwrite the + // GnuPG binary used. + SopsGpgExecEnv = "FLUX_SOPS_GPG_EXEC" +) + +var ( + // pgpTTL is the duration after which a MasterKey requires rotation. + pgpTTL = time.Hour * 24 * 30 * 6 +) + +// MasterKey is a PGP key used to securely store SOPS' data key by +// encrypting it and decrypting it. +// +// Adapted from https://github.com/mozilla/sops/blob/v3.7.2/pgp/keysource.go +// to be able to control the GPG home directory and have a "contained" +// environment. +// +// We are unable to drop the dependency on the GPG binary (although we +// wish!) because the builtin GPG support in Go is limited, it does for +// example not offer support for FIPS: +// * https://github.com/golang/go/issues/11658#issuecomment-120448974 +// * https://github.com/golang/go/issues/45188 +type MasterKey struct { + // Fingerprint contains the fingerprint of the PGP key used to Encrypt + // or Decrypt the data key with. + Fingerprint string + // EncryptedKey contains the SOPS data key encrypted with PGP. + EncryptedKey string + // CreationDate of the MasterKey, used to determine if the EncryptedKey + // needs rotation. + CreationDate time.Time + + // gnuPGHomeDir contains the absolute path to a GnuPG home directory. + // It can be injected by a (local) keyservice.KeyServiceServer using + // GnuPGHome.ApplyToMasterKey(). + gnuPGHomeDir string +} + +// MasterKeyFromFingerprint takes a PGP fingerprint and returns a +// new MasterKey with that fingerprint. +func MasterKeyFromFingerprint(fingerprint string) *MasterKey { + return &MasterKey{ + Fingerprint: strings.Replace(fingerprint, " ", "", -1), + CreationDate: time.Now().UTC(), + } +} + +// GnuPGHome is the absolute path to a GnuPG home directory. +// A new keyring can be constructed by combining the use of NewGnuPGHome() and +// Import() or ImportFile(). +type GnuPGHome string + +// NewGnuPGHome initializes a new GnuPGHome in a temporary directory. +// The caller is expected to handle the garbage collection of the created +// directory. +func NewGnuPGHome() (GnuPGHome, error) { + tmpDir, err := os.MkdirTemp("", "sops-gnupghome-") + if err != nil { + return "", fmt.Errorf("failed to create new GnuPG home: %w", err) + } + return GnuPGHome(tmpDir), nil +} + +// Import attempts to import the armored key bytes into the GnuPGHome keyring. +// It returns an error if the GnuPGHome does not pass Validate, or if the +// import failed. +func (d GnuPGHome) Import(armoredKey []byte) error { + if err := d.Validate(); err != nil { + return fmt.Errorf("cannot import armored key data into GnuPG keyring: %w", err) + } + + args := []string{"--batch", "--import"} + err, _, stderr := gpgExec(d.String(), args, bytes.NewReader(armoredKey)) + if err != nil { + return fmt.Errorf("failed to import armored key data into GnuPG keyring: %s", strings.TrimSpace(stderr.String())) + } + return nil +} + +// ImportFile attempts to import the armored key file into the GnuPGHome +// keyring. +// It returns an error if the GnuPGHome does not pass Validate, or if the +// import failed. +func (d GnuPGHome) ImportFile(path string) error { + b, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("cannot read armored key data from file: %w", err) + } + return d.Import(b) +} + +// Validate ensures the GnuPGHome is a valid GnuPG home directory path. +// When validation fails, it returns a descriptive reason as error. +func (d GnuPGHome) Validate() error { + if d == "" { + return fmt.Errorf("empty GNUPGHOME path") + } + if !filepath.IsAbs(d.String()) { + return fmt.Errorf("GNUPGHOME must be an absolute path") + } + fi, err := os.Lstat(d.String()) + if err != nil { + if os.IsNotExist(err) { + return fmt.Errorf("GNUPGHOME does not exist") + } + return fmt.Errorf("cannot stat GNUPGHOME: %w", err) + } + if !fi.IsDir() { + return fmt.Errorf("GNUGPHOME is not a directory") + } + if perm := fi.Mode().Perm(); perm != 0o700 { + return fmt.Errorf("GNUPGHOME has invalid permissions: got %#o wanted %#o", perm, 0o700) + } + return nil +} + +// String returns the GnuPGHome as a string. It does not Validate. +func (d GnuPGHome) String() string { + return string(d) +} + +// ApplyToMasterKey configures the GnuPGHome on the provided key if it passes +// Validate. +func (d GnuPGHome) ApplyToMasterKey(key *MasterKey) { + if err := d.Validate(); err == nil { + key.gnuPGHomeDir = d.String() + } +} + +// Encrypt encrypts the data key with the PGP key with the same +// fingerprint as the MasterKey. +func (key *MasterKey) Encrypt(dataKey []byte) error { + fingerprint := shortenFingerprint(key.Fingerprint) + + args := []string{ + "--no-default-recipient", + "--yes", + "--encrypt", + "-a", + "-r", + key.Fingerprint, + "--trusted-key", + fingerprint, + "--no-encrypt-to", + } + err, stdout, stderr := gpgExec(key.gnuPGHome(), args, bytes.NewReader(dataKey)) + if err != nil { + return fmt.Errorf("failed to encrypt sops data key with pgp: %s", strings.TrimSpace(stderr.String())) + } + + key.SetEncryptedDataKey(bytes.TrimSpace(stdout.Bytes())) + return nil +} + +// EncryptIfNeeded encrypts the data key with PGP only if it's needed, +// that is, if it hasn't been encrypted already. +func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error { + if key.EncryptedKey == "" { + return key.Encrypt(dataKey) + } + return nil +} + +// EncryptedDataKey returns the encrypted data key this master key holds. +func (key *MasterKey) EncryptedDataKey() []byte { + return []byte(key.EncryptedKey) +} + +// SetEncryptedDataKey sets the encrypted data key for this master key. +func (key *MasterKey) SetEncryptedDataKey(enc []byte) { + key.EncryptedKey = string(enc) +} + +// Decrypt uses PGP to obtain the data key from the EncryptedKey store +// in the MasterKey and returns it. +func (key *MasterKey) Decrypt() ([]byte, error) { + args := []string{ + "-d", + } + err, stdout, stderr := gpgExec(key.gnuPGHome(), args, strings.NewReader(key.EncryptedKey)) + if err != nil { + return nil, fmt.Errorf("failed to decrypt sops data key with pgp: %s", strings.TrimSpace(stderr.String())) + } + return stdout.Bytes(), nil +} + +// NeedsRotation returns whether the data key needs to be rotated +// or not. +func (key *MasterKey) NeedsRotation() bool { + return time.Since(key.CreationDate) > (pgpTTL) +} + +// ToString returns the string representation of the key, i.e. its +// fingerprint. +func (key *MasterKey) ToString() string { + return key.Fingerprint +} + +// ToMap converts the MasterKey into a map for serialization purposes. +func (key MasterKey) ToMap() map[string]interface{} { + out := make(map[string]interface{}) + out["fp"] = key.Fingerprint + out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339) + out["enc"] = key.EncryptedKey + return out +} + +// gnuPGHome determines the GnuPG home directory for the MasterKey, and returns +// its path. In order of preference: +// 1. MasterKey.gnuPGHomeDir +// 2. $GNUPGHOME +// 3. user.Current().HomeDir/.gnupg +// 4. $HOME/.gnupg +func (key *MasterKey) gnuPGHome() string { + if key.gnuPGHomeDir == "" { + dir := os.Getenv("GNUPGHOME") + if dir == "" { + usr, err := user.Current() + if err != nil { + return filepath.Join(os.Getenv("HOME"), ".gnupg") + } + return filepath.Join(usr.HomeDir, ".gnupg") + } + return dir + } + return key.gnuPGHomeDir +} + +// gpgExec runs the provided args with the gpgBinary, while restricting it to +// gnuPGHome. Stdout and stderr can be read from the returned buffers. +// When the command fails, an error is returned. +func gpgExec(gnuPGHome string, args []string, stdin io.Reader) (err error, stdout bytes.Buffer, stderr bytes.Buffer) { + if gnuPGHome != "" { + args = append([]string{"--no-default-keyring", "--homedir", gnuPGHome}, args...) + } + + cmd := exec.Command(gpgBinary(), args...) + cmd.Stdin = stdin + cmd.Stdout = &stdout + cmd.Stderr = &stderr + err = cmd.Run() + return +} + +// gpgBinary returns the GnuPG binary which must be used. +// It allows for runtime modifications by setting the environment variable +// SopsGpgExecEnv to the absolute path of the replacement binary. +func gpgBinary() string { + binary := "gpg" + if envBinary := os.Getenv(SopsGpgExecEnv); envBinary != "" && filepath.IsAbs(envBinary) { + binary = envBinary + } + return binary +} + +// shortenFingerprint returns the short ID of the given fingerprint. +// This is mostly used for compatability reasons, as older versions of GnuPG +// do not always like long IDs. +func shortenFingerprint(fingerprint string) string { + if offset := len(fingerprint) - 16; offset > 0 { + fingerprint = fingerprint[offset:] + } + return fingerprint +} diff --git a/internal/decryptors/sops/kustomize-controller/pgp/keysource_test.go b/internal/decryptors/sops/kustomize-controller/pgp/keysource_test.go new file mode 100644 index 0000000..4080084 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/pgp/keysource_test.go @@ -0,0 +1,419 @@ +// Copyright (C) 2022 The Flux authors +// +// 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 https://mozilla.org/MPL/2.0/. + +package pgp + +import ( + "bytes" + "os" + "os/user" + "path/filepath" + "strings" + "testing" + "time" + + fuzz "github.com/AdaLogics/go-fuzz-headers" + . "github.com/onsi/gomega" + "go.mozilla.org/sops/v3/pgp" +) + +var ( + mockPublicKey = "testdata/public.gpg" + mockPrivateKey = "testdata/private.gpg" + mockFingerprint = "B59DAF469E8C948138901A649732075EA221A7EA" +) + +func TestMasterKeyFromFingerprint(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromFingerprint(mockFingerprint) + g.Expect(key.Fingerprint).To(Equal(mockFingerprint)) + g.Expect(key.CreationDate).Should(BeTemporally("~", time.Now(), time.Second)) + + key = MasterKeyFromFingerprint("B59DAF 469E8C94813 8901A 649732075E A221A7EA") + g.Expect(key.Fingerprint).To(Equal(mockFingerprint)) +} + +func TestNewGnuPGHome(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).NotTo(HaveOccurred()) + + g.Expect(gnuPGHome.String()).To(BeADirectory()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.Validate()).ToNot(HaveOccurred()) +} + +func TestGnuPGHome_Import(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).NotTo(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + + b, err := os.ReadFile(mockPublicKey) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(gnuPGHome.Import(b)).To(Succeed()) + + err, _, stderr := gpgExec(gnuPGHome.String(), []string{"--list-keys", mockFingerprint}, nil) + g.Expect(err).ToNot(HaveOccurred(), stderr.String()) + + b, err = os.ReadFile(mockPrivateKey) + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(gnuPGHome.Import(b)).To(Succeed()) + + err, _, stderr = gpgExec(gnuPGHome.String(), []string{"--list-secret-keys", mockFingerprint}, nil) + g.Expect(err).ToNot(HaveOccurred(), stderr.String()) + + g.Expect(gnuPGHome.Import([]byte("invalid armored data"))).To(HaveOccurred()) + + g.Expect(GnuPGHome("").Import(b)).To(HaveOccurred()) +} + +func TestGnuPGHome_ImportFile(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).NotTo(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + + g.Expect(gnuPGHome.ImportFile(mockPublicKey)).To(Succeed()) + g.Expect(gnuPGHome.ImportFile("invalid")).To(HaveOccurred()) +} + +func TestGnuPGHome_Validate(t *testing.T) { + t.Run("empty path", func(t *testing.T) { + g := NewWithT(t) + + g.Expect(GnuPGHome("").Validate()).To(HaveOccurred()) + }) + + t.Run("relative path", func(t *testing.T) { + g := NewWithT(t) + + g.Expect(GnuPGHome("../../.gnupghome").Validate()).To(HaveOccurred()) + }) + + t.Run("file path", func(t *testing.T) { + g := NewWithT(t) + + tmpDir := t.TempDir() + f, err := os.CreateTemp(tmpDir, "file") + g.Expect(err).ToNot(HaveOccurred()) + defer f.Close() + + g.Expect(GnuPGHome(f.Name()).Validate()).To(HaveOccurred()) + }) + + t.Run("wrong permissions", func(t *testing.T) { + g := NewWithT(t) + + // Is created with 0755 + tmpDir := t.TempDir() + g.Expect(GnuPGHome(tmpDir).Validate()).To(HaveOccurred()) + }) + + t.Run("valid", func(t *testing.T) { + g := NewWithT(t) + + gnupgHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnupgHome.String()) + }) + g.Expect(gnupgHome.Validate()).To(Succeed()) + }) +} + +func TestGnuPGHome_String(t *testing.T) { + g := NewWithT(t) + + gnuPGHome := GnuPGHome("/some/absolute/path") + g.Expect(gnuPGHome.String()).To(Equal("/some/absolute/path")) +} + +func TestGnuPGHome_ApplyToMasterKey(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + + key := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(key) + g.Expect(key.gnuPGHomeDir).To(Equal(gnuPGHome.String())) + + gnuPGHome = "/non/existing/absolute/path/fails/validate" + gnuPGHome.ApplyToMasterKey(key) + g.Expect(key.gnuPGHomeDir).ToNot(Equal(gnuPGHome.String())) +} + +func TestMasterKey_Encrypt(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPublicKey)).To(Succeed()) + + key := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(key) + data := []byte("oh no, my darkest secret") + g.Expect(key.Encrypt(data)).To(Succeed()) + + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + g.Expect(key.EncryptedKey).ToNot(Equal(data)) + + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + args := []string{ + "-d", + } + err, stdout, stderr := gpgExec(key.gnuPGHome(), args, strings.NewReader(key.EncryptedKey)) + g.Expect(err).ToNot(HaveOccurred(), stderr.String()) + g.Expect(stdout.Bytes()).To(Equal(data)) + + key.Fingerprint = "invalid" + err = key.Encrypt([]byte("invalid")) + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(Equal("failed to encrypt sops data key with pgp: gpg: 'invalid' is not a valid long keyID")) +} + +func TestMasterKey_Encrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + dataKey := []byte("foo") + + encryptKey := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(encryptKey) + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + t.Setenv("GNUPGHOME", gnuPGHome.String()) + decryptKey := pgp.NewMasterKeyFromFingerprint(mockFingerprint) + decryptKey.EncryptedKey = encryptKey.EncryptedKey + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptIfNeeded(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + key := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(key) + g.Expect(key.EncryptIfNeeded([]byte("data"))).To(Succeed()) + + encryptedKey := key.EncryptedKey + g.Expect(encryptedKey).To(ContainSubstring("END PGP MESSAGE")) + + g.Expect(key.EncryptIfNeeded([]byte("some other data"))).To(Succeed()) + g.Expect(key.EncryptedKey).To(Equal(encryptedKey)) +} + +func TestMasterKey_EncryptedDataKey(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{EncryptedKey: "some key"} + g.Expect(key.EncryptedDataKey()).To(BeEquivalentTo(key.EncryptedKey)) +} + +func TestMasterKey_Decrypt(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + fingerprint := shortenFingerprint(mockFingerprint) + + data := []byte("this data is absolutely top secret") + err, stdout, stderr := gpgExec(gnuPGHome.String(), []string{ + "--no-default-recipient", + "--yes", + "--encrypt", + "-a", + "-r", + fingerprint, + "--trusted-key", + fingerprint, + "--no-encrypt-to", + }, bytes.NewReader(data)) + g.Expect(err).NotTo(HaveOccurred(), stderr.String()) + + encryptedData := stdout.String() + g.Expect(encryptedData).ToNot(BeEquivalentTo(data)) + + key := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(key) + key.EncryptedKey = encryptedData + + got, err := key.Decrypt() + g.Expect(err).NotTo(HaveOccurred()) + g.Expect(got).To(Equal(data)) + + key.EncryptedKey = "absolute invalid" + got, err = key.Decrypt() + g.Expect(err).To(HaveOccurred()) + g.Expect(err.Error()).To(ContainSubstring("gpg: no valid OpenPGP data found")) + g.Expect(got).To(BeNil()) +} + +func TestMasterKey_Decrypt_SOPS_Compat(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + dataKey := []byte("foo") + + t.Setenv("GNUPGHOME", gnuPGHome.String()) + encryptKey := pgp.NewMasterKeyFromFingerprint(mockFingerprint) + g.Expect(encryptKey.Encrypt(dataKey)).To(Succeed()) + + decryptKey := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(decryptKey) + decryptKey.EncryptedKey = encryptKey.EncryptedKey + + dec, err := decryptKey.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(dec).To(Equal(dataKey)) +} + +func TestMasterKey_EncryptDecrypt_RoundTrip(t *testing.T) { + g := NewWithT(t) + + gnuPGHome, err := NewGnuPGHome() + g.Expect(err).ToNot(HaveOccurred()) + t.Cleanup(func() { + _ = os.RemoveAll(gnuPGHome.String()) + }) + g.Expect(gnuPGHome.ImportFile(mockPrivateKey)).To(Succeed()) + + key := MasterKeyFromFingerprint(mockFingerprint) + gnuPGHome.ApplyToMasterKey(key) + + data := []byte("some secret data") + g.Expect(key.Encrypt(data)).To(Succeed()) + g.Expect(key.EncryptedKey).ToNot(BeEmpty()) + + decryptedData, err := key.Decrypt() + g.Expect(err).ToNot(HaveOccurred()) + g.Expect(decryptedData).To(Equal(data)) +} + +func TestMasterKey_NeedsRotation(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromFingerprint("") + g.Expect(key.NeedsRotation()).To(BeFalse()) + + key.CreationDate = key.CreationDate.Add(-(pgpTTL + time.Second)) + g.Expect(key.NeedsRotation()).To(BeTrue()) +} + +func TestMasterKey_ToString(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromFingerprint(mockFingerprint) + g.Expect(key.ToString()).To(Equal(mockFingerprint)) +} + +func TestMasterKey_ToMap(t *testing.T) { + g := NewWithT(t) + + key := MasterKeyFromFingerprint(mockFingerprint) + key.EncryptedKey = "data" + g.Expect(key.ToMap()).To(Equal(map[string]interface{}{ + "fp": mockFingerprint, + "created_at": key.CreationDate.UTC().Format(time.RFC3339), + "enc": key.EncryptedKey, + })) +} + +func TestMasterKey_gnuPGHome(t *testing.T) { + g := NewWithT(t) + + key := &MasterKey{} + + usr, err := user.Current() + if err == nil { + g.Expect(key.gnuPGHome()).To(Equal(filepath.Join(usr.HomeDir, ".gnupg"))) + } else { + g.Expect(key.gnuPGHome()).To(Equal(filepath.Join(os.Getenv("HOME"), ".gnupg"))) + } + + gnupgHome := "/overwrite/home" + t.Setenv("GNUPGHOME", gnupgHome) + g.Expect(key.gnuPGHome()).To(Equal(gnupgHome)) + + key.gnuPGHomeDir = "/home/dir/overwrite" + g.Expect(key.gnuPGHome()).To(Equal(key.gnuPGHomeDir)) +} + +func Test_gpgBinary(t *testing.T) { + g := NewWithT(t) + + g.Expect(gpgBinary()).To(Equal("gpg")) + + overwrite := "/some/other/gpg" + t.Setenv(SopsGpgExecEnv, overwrite) + g.Expect(gpgBinary()).To(Equal(overwrite)) +} + +func Test_shortenFingerprint(t *testing.T) { + g := NewWithT(t) + + shortId := shortenFingerprint(mockFingerprint) + g.Expect(shortId).To(Equal("9732075EA221A7EA")) + + g.Expect(shortenFingerprint(shortId)).To(Equal(shortId)) +} + +func Fuzz_Pgp(f *testing.F) { + f.Fuzz(func(t *testing.T, seed, data []byte) { + fc := fuzz.NewConsumer(data) + masterKey := MasterKey{} + + if err := fc.GenerateStruct(&masterKey); err != nil { + return + } + + _ = masterKey.Encrypt(data) + _ = masterKey.EncryptIfNeeded(data) + }) +} diff --git a/internal/decryptors/sops/kustomize-controller/pgp/testdata/private.gpg b/internal/decryptors/sops/kustomize-controller/pgp/testdata/private.gpg new file mode 100644 index 0000000..f3ca23e --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/pgp/testdata/private.gpg @@ -0,0 +1,81 @@ +-----BEGIN PGP PRIVATE KEY BLOCK----- + +lQVYBGJGqrsBDAC7OxFP6Z2E+AkVZpQySjLFAeYJWdnadx0GOHnckOOFkQvVJauz +9KibgzLUkO9h0oIoP7dLyPEiRPhKgmbrktyCDfysvNeKCgI5XemJCJqCmwA/vWwp +GnVltcgsVVjVZ3vvD8VMfhKF77pkmMDj7mnCPw9x39R8SVpe2K9RO0QLk/Dt+o8t +MO+sXTz4ba4aMdjJvMoaoQKw6RXAouZa4H09i6tiAgXrRLxQDxJ58sGg/ZCWa5G4 +aI6PdObY41fzQlcobtifCbktbICVb1Ms1s0iZWttFmr0oTSkJTv3FPWhf6n126w4 +LEkF9d6YW+/0H9cqXa4GMfxXg4XBmJNJfYkLDVUlbp3xi+I+Lg1Sit6QlqkW93EW +etpYPK1KmDcW3IA6ausYnkyrcQbt1m5/hh9KJoQb6He/RytXEBxp90+v9y7THZGr +2U49ZEHQg6DAIj4j1p9NAGgqjKr9am6yk2pvpK3ZWmHQ6CZfCiBrEPCvdmEhrx4U +lj6wyd00YJknpDkAEQEAAQAL/iU3C+1g55TvAks1LP7D/cxn4LP6HpHMfEHoxtwf +FoJNftcamkL2Pe9PSDK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hjru2f3z85YAqOXmQUGYKrQZL2T9NE2mQnXL0n+ +sgS+XwT2h+fdCBJHJYmboxXpxC02xHY= +=G8JF +-----END PGP PRIVATE KEY BLOCK----- diff --git a/internal/decryptors/sops/kustomize-controller/pgp/testdata/public.gpg b/internal/decryptors/sops/kustomize-controller/pgp/testdata/public.gpg new file mode 100644 index 0000000..c59ba01 --- /dev/null +++ b/internal/decryptors/sops/kustomize-controller/pgp/testdata/public.gpg @@ -0,0 +1,41 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQGNBGJGqrsBDAC7OxFP6Z2E+AkVZpQySjLFAeYJWdnadx0GOHnckOOFkQvVJauz +9KibgzLUkO9h0oIoP7dLyPEiRPhKgmbrktyCDfysvNeKCgI5XemJCJqCmwA/vWwp +GnVltcgsVVjVZ3vvD8VMfhKF77pkmMDj7mnCPw9x39R8SVpe2K9RO0QLk/Dt+o8t +MO+sXTz4ba4aMdjJvMoaoQKw6RXAouZa4H09i6tiAgXrRLxQDxJ58sGg/ZCWa5G4 +aI6PdObY41fzQlcobtifCbktbICVb1Ms1s0iZWttFmr0oTSkJTv3FPWhf6n126w4 +LEkF9d6YW+/0H9cqXa4GMfxXg4XBmJNJfYkLDVUlbp3xi+I+Lg1Sit6QlqkW93EW +etpYPK1KmDcW3IA6ausYnkyrcQbt1m5/hh9KJoQb6He/RytXEBxp90+v9y7THZGr +2U49ZEHQg6DAIj4j1p9NAGgqjKr9am6yk2pvpK3ZWmHQ6CZfCiBrEPCvdmEhrx4U +lj6wyd00YJknpDkAEQEAAbQVRmx1eCA8c29wc0BmbHV4Y2QuaW8+iQHOBBMBCAA4 +FiEEtZ2vRp6MlIE4kBpklzIHXqIhp+oFAmJGqrsCGwMFCwkIBwIGFQoJCAsCBBYC +AwECHgECF4AACgkQlzIHXqIhp+qaagwAmpAZLDnyPcZHFdieKCpBJQz8zzFZVnrr +pXoB20vEerKxCQ8XUeI1KRVSJQ6fPMcDLq6QGZMCXcc1i1o/DRrluWdLN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OXcSbAeoy4xP9DE3lJzlBVrBEPfr4v/K4VjMr4wr2z2n +ln/1WZOw78pDFxo+K5i5vm+wnfwDGxpKI8RUK1djVAfRHcBgyHu0IZb6qHJ/whnL +KeSI4hmajw92tLBGcEJYY+8diokSvtzkskPRFhkXBH66M+GvmZq8RFXOIXYR9Siv +feVrm+lrH4IP5ct4xBpaisZ6AU3rASmgahDWs/XTG0z63FTv/DR+RgdoTO9B+dE3 +hBU2D8SBDHtT4fKSUAzfq0ZiCPYJEXmqb4paG/6KnKZ+YCeCuM0ypwzXm5eLUwXd +QYUbtCRspQGql4r1R8biWdkodxLCF99yAvpyXPWYZ+uIIQm/D0J++UubtEMzab8x +HEWvbI1CCkgkWheANUK2EEK4fV0gy+GAJgB+sghjNMrZkosmVO/c7xIJN/VmGOu7 +Z/fPzlgCo5eZBQZgqtBkvZP00TaZCdcvSf6yBL5fBPaH590IEkcliZujFenELTbE +dg== +=05GI +-----END PGP PUBLIC KEY BLOCK----- diff --git a/internal/decryptors/sops/sops.go b/internal/decryptors/sops/sops.go new file mode 100644 index 0000000..f3f137b --- /dev/null +++ b/internal/decryptors/sops/sops.go @@ -0,0 +1,397 @@ +package sops + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + "sync" + "time" + + "github.com/bedag/subst/internal/decryptors" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/age" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/awskms" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/azkv" + intkeyservice "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/keyservice" + "github.com/bedag/subst/internal/decryptors/sops/kustomize-controller/pgp" + "go.mozilla.org/sops/v3" + "go.mozilla.org/sops/v3/aes" + "go.mozilla.org/sops/v3/cmd/sops/common" + "go.mozilla.org/sops/v3/cmd/sops/formats" + "go.mozilla.org/sops/v3/keyservice" + k8serrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" +) + +const ( + // DecryptionProviderSOPS is the SOPS provider name. + DecryptionProviderSOPS = "sops" + // DecryptionPGPExt is the extension of the file containing an armored PGP + // key. + DecryptionPGPExt = ".asc" + // DecryptionAgeExt is the extension of the file containing an age key + // file. + DecryptionAgeExt = ".agekey" + // DecryptionVaultTokenFileName is the name of the file containing the + // Hashicorp Vault token. + DecryptionVaultTokenFileName = "sops.vault-token" + // DecryptionAWSKmsFile is the name of the file containing the AWS KMS + // credentials. + DecryptionAWSKmsFile = "sops.aws-kms" + // DecryptionAzureAuthFile is the name of the file containing the Azure + // credentials. + DecryptionAzureAuthFile = "sops.azure-kv" + // DecryptionGCPCredsFile is the name of the file containing the GCP + // credentials. + DecryptionGCPCredsFile = "sops.gcp-kms" + // maxEncryptedFileSize is the max allowed file size in bytes of an encrypted + // file. + maxEncryptedFileSize int64 = 5 << 20 + // unsupportedFormat is used to signal no sopsFormatToMarkerBytes format was + // detected by detectFormatFromMarkerBytes. + unsupportedFormat = formats.Format(-1) +) + +var ( + // sopsFormatToString is the counterpart to + // https://github.com/mozilla/sops/blob/v3.7.2/cmd/sops/formats/formats.go#L16 + sopsFormatToString = map[formats.Format]string{ + formats.Binary: "binary", + formats.Dotenv: "dotenv", + formats.Ini: "INI", + formats.Json: "JSON", + formats.Yaml: "YAML", + } + // sopsFormatToMarkerBytes contains a list of formats and their byte + // order markers, used to detect if a Secret data field is SOPS' encrypted. + sopsFormatToMarkerBytes = map[formats.Format][]byte{ + // formats.Binary is a JSON envelop at encrypted rest + formats.Binary: []byte("\"mac\": \"ENC["), + formats.Dotenv: []byte("sops_mac=ENC["), + formats.Ini: []byte("[sops]"), + formats.Json: []byte("\"mac\": \"ENC["), + formats.Yaml: []byte("mac: ENC["), + } +) + +// Decryptor performs decryption operations for a v1.Kustomization. +// The only supported decryption provider at present is +// DecryptionProviderSOPS. +type SOPSDecryptor struct { + // maxFileSize is the max size in bytes a file is allowed to have to be + // decrypted. Defaults to maxEncryptedFileSize. + maxFileSize int64 + // checkSopsMac instructs the decryptor to perform the SOPS data integrity + // check using the MAC. Not enabled by default, as arbitrary data gets + // injected into most resources, causing the integrity check to fail. + // Mostly kept around for feature completeness and documentation purposes. + checkSopsMac bool + + // gnuPGHome is the absolute path of the GnuPG home directory used to + // decrypt PGP data. When empty, the systems' GnuPG keyring is used. + // When set, ImportKeys() imports found PGP keys into this keyring. + gnuPGHome pgp.GnuPGHome + // ageIdentities is the set of age identities available to the decryptor. + ageIdentities age.ParsedIdentities + // vaultToken is the Hashicorp Vault token used to authenticate towards + // any Vault server. + vaultToken string + // awsCredsProvider is the AWS credentials provider object used to authenticate + // towards any AWS KMS. + awsCredsProvider *awskms.CredsProvider + // azureToken is the Azure credential token used to authenticate towards + // any Azure Key Vault. + azureToken *azkv.Token + // gcpCredsJSON is the JSON credential file of the service account used to + // authenticate towards any GCP KMS. + gcpCredsJSON []byte + + // keyServices are the SOPS keyservice.KeyServiceClient's available to the + // decryptor. + keyServices []keyservice.KeyServiceClient + localServiceOnce sync.Once + + // Interface decryptor config + Config decryptors.DecryptorConfig +} + +// NewDecryptor creates a new Decryptor for the given kustomization. +// gnuPGHome can be empty, in which case the systems' keyring is used. +func NewSOPSDecryptor(config decryptors.DecryptorConfig, gnuPGHome string) *SOPSDecryptor { + return &SOPSDecryptor{ + maxFileSize: maxEncryptedFileSize, + gnuPGHome: pgp.GnuPGHome(gnuPGHome), + Config: config, + } +} + +// NewTempDecryptor creates a new Decryptor, with a temporary GnuPG +// home directory to Decryptor.ImportKeys() into. +func NewSOPSTempDecryptor(config decryptors.DecryptorConfig) (*SOPSDecryptor, func(), error) { + gnuPGHome, err := pgp.NewGnuPGHome() + if err != nil { + return nil, nil, fmt.Errorf("cannot create keyring: %w", err) + } + cleanup := func() { _ = os.RemoveAll(gnuPGHome.String()) } + return NewSOPSDecryptor(config, gnuPGHome.String()), cleanup, nil +} + +// Only call this for Temporary Decryptors +func (d *SOPSDecryptor) RemoveKeyRing() error { + return os.RemoveAll(string(d.gnuPGHome)) +} + +// IsEncrypted returns true if the given data is encrypted by SOPS. +func (d *SOPSDecryptor) IsEncrypted(data []byte) (bool, error) { + if len(data) == 0 { + return false, nil + } + + jdata, err := decryptors.UnmarshalJSONorYAML(data) + if err != nil { + return false, err + } + + sopsField := jdata["sops"] + if sopsField == nil || sopsField == "" { + return false, nil + } + return true, nil +} + +// Read reads the input data, decrypts it, and returns the decrypted data. +func (d *SOPSDecryptor) Decrypt(data []byte) (content map[string]interface{}, err error) { + + content, err = decryptors.UnmarshalJSONorYAML(data) + if err != nil { + return nil, err + } + + if !d.Config.SkipDecrypt { + jcontent, err := json.Marshal(content) + if err != nil { + return nil, err + } + + data, err = d.SopsDecryptWithFormat(jcontent, formats.Json, formats.Json) + if err != nil { + return nil, err + } + + content, err = decryptors.UnmarshalJSONorYAML(data) + if err != nil { + return nil, err + } + } + + delete(content, "sops") + return content, nil +} + +// AddGPGKey adds given GPG key to the decryptor's keyring. +func (d *SOPSDecryptor) AddGPGKey(key []byte) error { + return d.gnuPGHome.Import(key) +} + +// AddAgeKey to the decryptor's identities. +func (d *SOPSDecryptor) AddAgeKey(key []byte) error { + return d.ageIdentities.Import(string(key)) +} + +// SetVaultToken sets the Vault token for the decryptor. +func (d *SOPSDecryptor) SetVaultToken(token []byte) { + vtoken := string(token) + vtoken = strings.Trim(strings.TrimSpace(vtoken), "\n") + d.vaultToken = vtoken +} + +// SetAWSCredentials adds AWS credentials for the decryptor. +// Reference: https://github.com/getsops/sops#aws-kms-encryption-context +func (d *SOPSDecryptor) SetAWSCredentials(token []byte) (err error) { + d.awsCredsProvider, err = awskms.LoadCredsProviderFromYaml(token) + return err +} + +// SetAzureAuthFile adds AWS credentials for the decryptor. +func (d *SOPSDecryptor) SetAzureCredentials(config []byte) (err error) { + conf := azkv.AADConfig{} + if err = azkv.LoadAADConfigFromBytes(config, &conf); err != nil { + return err + } + if d.azureToken, err = azkv.TokenFromAADConfig(conf); err != nil { + return err + } + + return nil +} + +// SetGCPCredentials adds GCP credentials for the decryptor. +func (d *SOPSDecryptor) SetGCPCredentials(config []byte) { + d.gcpCredsJSON = bytes.Trim(config, "\n") +} + +func (d *SOPSDecryptor) KeysFromSecret(secretName string, namespace string, client *kubernetes.Clientset, ctx context.Context) (err error) { + // Retrieve Secret + keySecret, err := client.CoreV1().Secrets(namespace).Get(ctx, secretName, metav1.GetOptions{}) + if k8serrors.IsNotFound(err) { + return &decryptors.MissingKubernetesSecret{Secret: secretName, Namespace: namespace} + } else if err != nil { + return err + } + + // Exract all keys from secret + for name, value := range keySecret.Data { + switch filepath.Ext(name) { + case DecryptionPGPExt: + if err = d.AddGPGKey(value); err != nil { + return fmt.Errorf("failed to import data from %s decryption Secret '%s': %w", name, secretName, err) + } + case DecryptionAgeExt: + if err = d.AddAgeKey(value); err != nil { + return fmt.Errorf("failed to import data from %s decryption Secret '%s': %w", name, secretName, err) + } + case filepath.Ext(DecryptionVaultTokenFileName): + // Make sure we have the absolute name + if name == DecryptionVaultTokenFileName { + d.SetVaultToken(value) + } + case filepath.Ext(DecryptionAWSKmsFile): + if name == DecryptionAWSKmsFile { + if d.SetAWSCredentials(value); err != nil { + return fmt.Errorf("failed to import data from %s decryption Secret '%s': %w", name, secretName, err) + } + } + case filepath.Ext(DecryptionAzureAuthFile): + if name == DecryptionAzureAuthFile { + if err = d.SetAzureCredentials(value); err != nil { + return fmt.Errorf("failed to import data from %s decryption Secret '%s': %w", name, secretName, err) + } + } + case filepath.Ext(DecryptionGCPCredsFile): + if name == DecryptionGCPCredsFile { + d.SetGCPCredentials(value) + } + } + } + + return nil +} + +// SopsDecryptWithFormat attempts to load a SOPS encrypted file using the store +// for the input format, gathers the data key for it from the key service, +// and then decrypts the file data with the retrieved data key. +// It returns the decrypted bytes in the provided output format, or an error. +func (d *SOPSDecryptor) SopsDecryptWithFormat(data []byte, inputFormat, outputFormat formats.Format) (_ []byte, err error) { + defer func() { + // It was discovered that malicious input and/or output instructions can + // make SOPS panic. Recover from this panic and return as an error. + if r := recover(); r != nil { + err = fmt.Errorf("failed to emit encrypted %s file as decrypted %s: %v", + sopsFormatToString[inputFormat], sopsFormatToString[outputFormat], r) + } + }() + + store := common.StoreForFormat(inputFormat) + + tree, err := store.LoadEncryptedFile(data) + if err != nil { + return nil, sopsUserErr(fmt.Sprintf("failed to load encrypted %s data", sopsFormatToString[inputFormat]), err) + } + + for _, group := range tree.Metadata.KeyGroups { + // Sort MasterKeys in the group so offline ones are tried first + sort.SliceStable(group, func(i, j int) bool { + return intkeyservice.IsOfflineMethod(group[i]) && !intkeyservice.IsOfflineMethod(group[j]) + }) + } + + metadataKey, err := tree.Metadata.GetDataKeyWithKeyServices(d.keyServiceServer()) + if err != nil { + return nil, sopsUserErr("cannot get sops data key", err) + } + + cipher := aes.NewCipher() + mac, err := tree.Decrypt(metadataKey, cipher) + if err != nil { + return nil, sopsUserErr("error decrypting sops tree", err) + } + + if d.checkSopsMac { + // Compute the hash of the cleartext tree and compare it with + // the one that was stored in the document. If they match, + // integrity was preserved + // Ref: go.mozilla.org/sops/v3/decrypt/decrypt.go + originalMac, err := cipher.Decrypt( + tree.Metadata.MessageAuthenticationCode, + metadataKey, + tree.Metadata.LastModified.Format(time.RFC3339), + ) + if err != nil { + return nil, sopsUserErr("failed to verify sops data integrity", err) + } + if originalMac != mac { + // If the file has an empty MAC, display "no MAC" + if originalMac == "" { + originalMac = "no MAC" + } + return nil, fmt.Errorf("failed to verify sops data integrity: expected mac '%s', got '%s'", originalMac, mac) + } + } + + outputStore := common.StoreForFormat(outputFormat) + out, err := outputStore.EmitPlainFile(tree.Branches) + if err != nil { + return nil, sopsUserErr(fmt.Sprintf("failed to emit encrypted %s file as decrypted %s", + sopsFormatToString[inputFormat], sopsFormatToString[outputFormat]), err) + } + return out, err +} + +// keyServiceServer returns the SOPS (local) key service clients used to serve +// decryption requests. loadKeyServiceServers() is only configured on the first +// call. +func (d *SOPSDecryptor) keyServiceServer() []keyservice.KeyServiceClient { + d.localServiceOnce.Do(func() { + d.loadKeyServiceServers() + }) + return d.keyServices +} + +// loadKeyServiceServers loads the SOPS (local) key service clients used to +// serve decryption requests for the current set of Decryptor +// credentials. +func (d *SOPSDecryptor) loadKeyServiceServers() { + serverOpts := []intkeyservice.ServerOption{ + intkeyservice.WithGnuPGHome(d.gnuPGHome), + intkeyservice.WithVaultToken(d.vaultToken), + intkeyservice.WithAgeIdentities(d.ageIdentities), + intkeyservice.WithGCPCredsJSON(d.gcpCredsJSON), + } + if d.azureToken != nil { + serverOpts = append(serverOpts, intkeyservice.WithAzureToken{Token: d.azureToken}) + } + serverOpts = append(serverOpts, intkeyservice.WithAWSKeys{CredsProvider: d.awsCredsProvider}) + server := intkeyservice.NewServer(serverOpts...) + d.keyServices = append(make([]keyservice.KeyServiceClient, 0), keyservice.NewCustomLocalClient(server)) +} + +func sopsUserErr(msg string, err error) error { + if userErr, ok := err.(sops.UserError); ok { + err = fmt.Errorf(userErr.UserError()) + } + return fmt.Errorf("%s: %w", msg, err) +} + +func detectFormatFromMarkerBytes(b []byte) formats.Format { + for k, v := range sopsFormatToMarkerBytes { + if bytes.Contains(b, v) { + return k + } + } + return unsupportedFormat +} diff --git a/internal/decryptors/sops/sops_test.go b/internal/decryptors/sops/sops_test.go new file mode 100644 index 0000000..3d54353 --- /dev/null +++ b/internal/decryptors/sops/sops_test.go @@ -0,0 +1,74 @@ +package sops + +import ( + "os" + "path/filepath" + "testing" + + "github.com/bedag/subst/internal/decryptors" + "github.com/stretchr/testify/assert" +) + +func testdataPath() string { + basePath, _ := os.Getwd() + hackDirPath := filepath.Join(basePath, "testdata") + return hackDirPath +} + +func TestSOPSIsEncrypted(t *testing.T) { + d, _ := os.ReadFile(filepath.Join(testdataPath(), "secret-pgp.yaml")) + + decryptor := NewSOPSDecryptor(decryptors.DecryptorConfig{}, "") + isEncrypted, err := decryptor.IsEncrypted(d) + + assert.NoError(t, err, "Expected no error when checking if content is encrypted") + assert.True(t, isEncrypted, "Expected the content to be identified as encrypted") +} + +func TestSOPSIsNotEncrypted(t *testing.T) { + d, _ := os.ReadFile(filepath.Join(testdataPath(), "secret.yaml")) + + decryptor := NewSOPSDecryptor(decryptors.DecryptorConfig{}, "") + isEncrypted, err := decryptor.IsEncrypted(d) + + assert.NoError(t, err, "Expected no error when checking if content is encrypted") + assert.False(t, isEncrypted, "Expected the content to be identified as not encrypted") +} + +func TestSOPSGPGEncryption(t *testing.T) { + private, _ := os.ReadFile(filepath.Join(testdataPath(), "pgp.asc")) + d, _ := os.ReadFile(filepath.Join(testdataPath(), "secret-pgp.yaml")) + + decryptor, cleanup, err := NewSOPSTempDecryptor(decryptors.DecryptorConfig{}) + assert.NoError(t, err, "Expected no error when initializing decryptor") + defer cleanup() + + err = decryptor.AddGPGKey([]byte(private)) + assert.NoError(t, err, "Expected no error when adding GPG Key") + + enc, err := decryptor.Decrypt(d) + assert.NoError(t, err, "Expected no error when decrypting content") + + sData := enc["stringData"].(map[string]interface{}) + assert.Equal(t, "VERY_SECRET", sData["database_password"], "Expected the database_password to be decrypted") + assert.Equal(t, "MUCH_SECURE", sData["database_user"], "Expected the database_user to be decrypted") +} + +func TestSOPSAgeEncryption(t *testing.T) { + private, _ := os.ReadFile(filepath.Join(testdataPath(), "age.agekey")) + d, _ := os.ReadFile(filepath.Join(testdataPath(), "secret-age.yaml")) + + decryptor, cleanup, err := NewSOPSTempDecryptor(decryptors.DecryptorConfig{}) + assert.NoError(t, err, "Expected no error when initializing decryptor") + defer cleanup() + + err = decryptor.AddAgeKey([]byte(private)) + assert.NoError(t, err, "Expected no error when adding Age Key") + + enc, err := decryptor.Decrypt(d) + assert.NoError(t, err, "Expected no error when decrypting content") + + sData := enc["stringData"].(map[string]interface{}) + assert.Equal(t, "VERY_SECRET", sData["database_password"], "Expected the database_password to be decrypted") + assert.Equal(t, "MUCH_SECURE", sData["database_user"], "Expected the database_user to be decrypted") +} diff --git a/internal/decryptors/sops/testdata/.sops.pub.asc b/internal/decryptors/sops/testdata/.sops.pub.asc new file mode 100644 index 0000000..b612848 --- /dev/null +++ b/internal/decryptors/sops/testdata/.sops.pub.asc @@ -0,0 +1,64 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGTTkNABEACuzgIJVS2zxl1ZyNqQmkXVT+glShUnTQzNUgDWd6iiqbVq2NQO +1EUnEYBU0iEKLhX2Rul+7tyjRP1Sd3/vyoKr+GJUpk196u/NFupHiJUd6VFxy1h8 ++ES2W+sGEnGvOvCIVJJbfWOuarakxOT0eesm8hsqZv0TwzSN8MAzut3aGUxAYOPH +CM5UBfE7dnLVESpVRz5e17vGKPXc6y+hgDRXaCTnDCOoLdmMnJjuSn8XzynVLq8S +iSSOCE2S/B3rKHU7swsnsI9iL+0LBtCcHkuuMjcsCFMJ9B1oDNGwiVtSVvq6NYE8 +BOf1LDOzb+f97eeBJuOOjWVNflPgSVYkaAhqqC+kYeAcYLYfeLauTu3L1P8H3UUI +WReGA+f0K+imzUzAlVbNTpE4bVVivn/teb92yS/S2qNwBTmhGDjDqaUQwIiJzmFd +Wa+PG4/5qGehP82u8yqHGcXqCVaHyK6cHO4Mb6walohiX8BJbAAohJAXJ+fepIzs +byU9shU5gTotJQKl5/mmYRwywiGtIhBXfqs6T4Kp++BKsO1EaGYyMUN56BsSG2A1 +7T5XsP2C716P4ZBEjiePIEHrVGZurhRPoNX/7SYjsz8WlhbjXHUlVwT8AeUqakL9 +Ix1KPqF3IJlS7KaHy+ab39MwCJNI3e7Ehkl4h/vQU3rx33JatxSa4RRd+QARAQAB +tCB0ZXN0LWRhdGEuZGVjcnlwdG9ycyAodGVzdCBkYXRhKYkCUgQTAQgAPBYhBLAR +AtgSRoZ8S8JNhj5yhr7oZePEBQJk05DQAxsvBAULCQgHAgIiAgYVCgkICwIEFgID +AQIeBwIXgAAKCRA+coa+6GXjxGuQEACEAM5PiSxlz87la2ERR9ETS96a0brkcu3t +BQIMYe2MtS9oVejcbPWjPyuh/eiSejUt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KU0P+FDotYEACsOgiKKOAsYZtBHjPQ +pb2VNY4ynEu108rIfS1KTu+G85AacJvF/lqEPASzwPLfvJnNo7DAHOFgza9FE1o0 +lp6OhCZmH3Xtm6bryVGR+JA6taNHzdv8lBGhugLFA3F7bnQZwKr3Udu+3i2+h2MY +ZRkd46S+qirNEfi5hte57a7RvS1w/E8apG57vfZNv75MlJpeRKCYcIEAVinrkyJs +rnUtVfeL5ZmZ5/LAJ8pJE7YtdoEDfuKvhyXDkKJquM3L+bZYvCqqR/thOJsuBahc +h06hvJRkfNNSnb7LgcxgRGgOh+z+R8ACQhW0N5MosYRBp0iG8CA13qbqCoEuH4F+ +4njX9AZpgjtxC5+WkhXSoeQ5o8rxf8b1CzRLSW81mXxL1NTmWxBf+jcpcyz3oDfn +jbmlbr9wIclpBh2Da5oVDmFAKltu7HQC7PycROlYFpYXPGwIehWwKdOlMrnjUeRg +ZR2Xl6QTo527FY3pjr6AKoKBRaBpy3MX98g78B/muw86rxsI4YhcMldWOsFeQkGL +1pWi2U0t5D9m4L1uD93h8A4HEaRfIWbumiDOHIBGEW7jsZLgouLYq9IV16DBO18F +n44fe8KneOYhPT1HSU2/X2y586QqTezvM2ZV0wEF/GQ4KsiOtI6Xregb+A0hWtXg +c73ZHZESEa+qNjfYk7pCGr3vew== +=N/nc +-----END PGP PUBLIC KEY BLOCK----- + diff --git a/internal/decryptors/sops/testdata/.sops.yaml b/internal/decryptors/sops/testdata/.sops.yaml new file mode 100644 index 0000000..806e003 --- /dev/null +++ b/internal/decryptors/sops/testdata/.sops.yaml @@ -0,0 +1,9 @@ +# creation rules are evaluated sequentially, the first match wins +creation_rules: + # files using age + - path_regex: \-age.yaml$ + encrypted_regex: ^(data|stringData)$ + age: age1p0wmaw5vk8f00753t3frs4rev0du4vqdkz7sx53ml98lrcsrnuqqwwp4tl + # fallback to PGP + - encrypted_regex: ^(data|stringData)$ + pgp: B01102D81246867C4BC24D863E7286BEE865E3C4 \ No newline at end of file diff --git a/internal/decryptors/sops/testdata/age.agekey b/internal/decryptors/sops/testdata/age.agekey new file mode 100644 index 0000000..8f54bea --- /dev/null +++ b/internal/decryptors/sops/testdata/age.agekey @@ -0,0 +1,3 @@ +# created: 2023-08-09T15:30:46+02:00 +# public key: age1p0wmaw5vk8f00753t3frs4rev0du4vqdkz7sx53ml98lrcsrnuqqwwp4tl +AGE-SECRET-KEY-1JZFAV45XK9RFDCHD7JG5R5T5R68SY7GTGVLQ9KSZRTLV8K6JFFJQMY6LCY diff --git a/internal/decryptors/sops/testdata/pgp.asc b/internal/decryptors/sops/testdata/pgp.asc new file mode 100644 index 0000000..d1d272c --- /dev/null +++ b/internal/decryptors/sops/testdata/pgp.asc @@ -0,0 +1,180 @@ +-----BEGIN PGP PRIVATE KEY BLOCK----- + +lQcYBGTTkNABEACuzgIJVS2zxl1ZyNqQmkXVT+glShUnTQzNUgDWd6iiqbVq2NQO +1EUnEYBU0iEKLhX2Rul+7tyjRP1Sd3/vyoKr+GJUpk196u/NFupHiJUd6VFxy1h8 ++ES2W+sGEnGvOvCIVJJbfWOuarakxOT0eesm8hsqZv0TwzSN8MAzut3aGUxAYOPH +CM5UBfE7dnLVESpVRz5e17vGKPXc6y+hgDRXaCTnDCOoLdmMnJjuSn8XzynVLq8S +iSSOCE2S/B3rKHU7swsnsI9iL+0LBtCcHkuuMjcsCFMJ9B1oDNGwiVtSVvq6NYE8 +BOf1LDOzb+f97eeBJuOOjWVNflPgSVYkaAhqqC+kYeAcYLYfeLauTu3L1P8H3UUI +WReGA+f0K+imzUzAlVbNTpE4bVVivn/teb92yS/S2qNwBTmhGDjDqaUQwIiJzmFd +Wa+PG4/5qGehP82u8yqHGcXqCVaHyK6cHO4Mb6walohiX8BJbAAohJAXJ+fepIzs +byU9shU5gTotJQKl5/mmYRwywiGtIhBXfqs6T4Kp++BKsO1EaGYyMUN56BsSG2A1 +7T5XsP2C716P4ZBEjiePIEHrVGZurhRPoNX/7SYjsz8WlhbjXHUlVwT8AeUqakL9 +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HQJqp4oMfhQYVVY1KabobyT4c12N5pZ7A5iI9i30DRfzRF/N +saW269VznkiIl/Dm1QW6iAJSmYrrPkQH+gNQTSfBXzaZ6nshw10Qb1vwyasatjJc +HFXnoOESb9AivcyLN4x9lz/JdqThstzKtaKU0P+FDotYEACsOgiKKOAsYZtBHjPQ +pb2VNY4ynEu108rIfS1KTu+G85AacJvF/lqEPASzwPLfvJnNo7DAHOFgza9FE1o0 +lp6OhCZmH3Xtm6bryVGR+JA6taNHzdv8lBGhugLFA3F7bnQZwKr3Udu+3i2+h2MY +ZRkd46S+qirNEfi5hte57a7RvS1w/E8apG57vfZNv75MlJpeRKCYcIEAVinrkyJs +rnUtVfeL5ZmZ5/LAJ8pJE7YtdoEDfuKvhyXDkKJquM3L+bZYvCqqR/thOJsuBahc +h06hvJRkfNNSnb7LgcxgRGgOh+z+R8ACQhW0N5MosYRBp0iG8CA13qbqCoEuH4F+ +4njX9AZpgjtxC5+WkhXSoeQ5o8rxf8b1CzRLSW81mXxL1NTmWxBf+jcpcyz3oDfn +jbmlbr9wIclpBh2Da5oVDmFAKltu7HQC7PycROlYFpYXPGwIehWwKdOlMrnjUeRg +ZR2Xl6QTo527FY3pjr6AKoKBRaBpy3MX98g78B/muw86rxsI4YhcMldWOsFeQkGL +1pWi2U0t5D9m4L1uD93h8A4HEaRfIWbumiDOHIBGEW7jsZLgouLYq9IV16DBO18F +n44fe8KneOYhPT1HSU2/X2y586QqTezvM2ZV0wEF/GQ4KsiOtI6Xregb+A0hWtXg +c73ZHZESEa+qNjfYk7pCGr3vew== +=N/nc +-----END PGP PUBLIC KEY BLOCK----- diff --git a/internal/decryptors/sops/testdata/secret-age.yaml b/internal/decryptors/sops/testdata/secret-age.yaml new file mode 100644 index 0000000..c11d750 --- /dev/null +++ b/internal/decryptors/sops/testdata/secret-age.yaml @@ -0,0 +1,27 @@ +apiVersion: v1 +kind: Secret +metadata: + name: sops-age +stringData: + database_password: ENC[AES256_GCM,data:I9QUte/BtTaii6o=,iv:vaSxFo7yqfpOvWGUIfM8Aj+B25de7dYyCSF9dXeKOiU=,tag:deIwuIktYEKn2ufNKRSYyw==,type:str] + database_user: ENC[AES256_GCM,data:SOpbzI0uFndBExA=,iv:icQb5nb8KnjK6dnOdxvLQDIQHycY67y3oQMmT9dSjOc=,tag:fj+4a2T5YtCDIy/yoFaZkw==,type:str] +sops: + kms: [] + gcp_kms: [] + azure_kv: [] + hc_vault: [] + age: + - recipient: age1p0wmaw5vk8f00753t3frs4rev0du4vqdkz7sx53ml98lrcsrnuqqwwp4tl + enc: | + -----BEGIN AGE ENCRYPTED FILE----- + YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSAvMW9LZmtvWUFXaFVQZkFq + ZHFwV2oyYWhHeWIxMkM2ZkRWcSt4b2FpQmt3CmVYY3N6c002MTJWSHpBbDVuVW5B + UlVQcGg2UG1uSFJGOEt5QWVPUjRLUVEKLS0tIEpwamNScUdlY2NqemFlOGJ3Sm53 + YnVzaEVFL1JqMlpBc3NxQmtBRVlGZmsKVJ7n7Lgk4dhWu3FK33gxbldVhcMegKpC + i/2y+Ukg12cu1LpeU4GUqpIy96LzPYnfwjR15S5JhVRGs49b0hfJmw== + -----END AGE ENCRYPTED FILE----- + lastmodified: "2023-08-09T13:31:49Z" + mac: ENC[AES256_GCM,data:XL5SwWzi0gYXSkFSWupvKYoXvyhrtyYELgy6hSqeDzrGO80XCgPY8+WOktlPu1d1FUb/F2Ez0RPoWROpyalVk3IkxADenCZ1JopTN8HZfMaBM6YxFqrAZ0mpqXVjK4LqxT+4kFojYChoU+RVEBexuhUFuQjFfQSFJ9bHo+WhlrU=,iv:bsxugaX/iczLKF6d5aDfztlO3iOmfWjBl00gRP33VsE=,tag:hL8lN0wXqG+95Yc+DaHRSg==,type:str] + pgp: [] + encrypted_regex: ^(data|stringData)$ + version: 3.7.2 diff --git a/internal/decryptors/sops/testdata/secret-pgp.yaml b/internal/decryptors/sops/testdata/secret-pgp.yaml new file mode 100644 index 0000000..c95e53e --- /dev/null +++ b/internal/decryptors/sops/testdata/secret-pgp.yaml @@ -0,0 +1,39 @@ +apiVersion: v1 +kind: Secret +metadata: + name: sops-pgp +stringData: + database_password: ENC[AES256_GCM,data:xap6r9CPuHN3T/c=,iv:oZ8gcWTlKWRBjW85h4ugCdTmzG4Ak1WsPAH69O6DYQs=,tag:kJYNlYCGvQX9aZYMq+0IRg==,type:str] + database_user: ENC[AES256_GCM,data:Wx5woeKL4Zs1EIM=,iv:fE7GCyPRUvMHbUtLDPSQqMn297Cls6LKVgnRnC2+2dA=,tag:NfsPXTXBAi5WClj4wW3Jyg==,type:str] +sops: + kms: [] + gcp_kms: [] + azure_kv: [] + hc_vault: [] + age: [] + lastmodified: "2023-08-09T13:29:15Z" + mac: ENC[AES256_GCM,data:CXNyGQZ74EFPYgTPzPfplyDjTXksqbShtli3y+gC/0FYaCi2nngjIj6nV5ibcnuHpCwjnJvkCp9vzfhamZn8LfO5qznLCZifZ2Wf9rjzmVPCVLNlxqyz50NKeRWveWoNqr/G1Z1rMadjARfCWtf1atFJyTx+XSDmR7dMh/qwPqY=,iv:kDelUNjBkTbyvSDwYKNhKAbJCNhTNxzQiPDUGfbKzKI=,tag:s4mXaSWpH3xqAgYcjJPULQ==,type:str] + pgp: + - created_at: "2023-08-09T13:29:14Z" + enc: | + -----BEGIN PGP MESSAGE----- + + hQIMA0RuT4C0qyryAQ//flqFS2clVtcKTxbzn5Ravj7v2/R/RY62HmBmxBoRVELS + OuFNqhxGsa9efrDgdQQKSsOxsEXTeTcZuJRGZvHHBaWZsWfvPN1Tfcm7RGTI6eIy + Qlb9r4X5D47oQdkN8LnK7JgV93ZIN4wLc2CnRFjSRz2bam3sImhhckBd6KZgQk9g + Zhf/+cGxp+sSM1MnHobVHabtLwEnks3stdJc/A5Gmo9W5NkGihGlfhNtaKOFXT8r + cmi/uOvEU6tDH61eIbmwECYF4m2VrI52ukyavPloo26VmpM7lCYB5I+RCWT+MsIk + 5U+iws4Ud/xbQ1sGMw2riPofde5rOKAzMAeJQl7ZHbUCgwjjVnlAMVw17Zr2ohEc + 6ZR2BbbJYZEZTsAWXstnyTZvTINRBXAg48Eh+Pp1bj0hAIV9ek7ffFeGSijw833C + EjAxgtiAZ7bs8o4PyUUa+QqsCvzDo8I6Z1xdTkmGBN12+jHUYNlsFy1iYlSWgZmC + CLkHKUKD8gWbNGRriuvSve6ZYbVt2u53llxJJaTYHdNAloQ8cX5BvI2Lbplyej+W + fCGdGq/ZA6xe8WhwE6X2kGD4GMGk5yrCvFeZRoemwiUAC6vrixVrhIPfexzFp35X + RqIR8hWRX6UIEMfig7egnBRzQ5GG5GymdYnfibAgZGqdIE6jDjQTtY4TogcLRHLU + aAEJAhAwoOvLNjNtH7jhvAmH683O0Qy21oaUMZSWz0NQZL6aeWn+F84iYtQcQ/eL + KR1ndRrGgI9BU5PEPudWgIAWY6EZN+ujazRdM4hp/ZPJhi71gIDW3HDNxK+/3oJ1 + vTjeGkz5RIOy + =BHWN + -----END PGP MESSAGE----- + fp: B01102D81246867C4BC24D863E7286BEE865E3C4 + encrypted_regex: ^(data|stringData)$ + version: 3.7.2 diff --git a/internal/decryptors/sops/testdata/secret.yaml b/internal/decryptors/sops/testdata/secret.yaml new file mode 100644 index 0000000..8866b74 --- /dev/null +++ b/internal/decryptors/sops/testdata/secret.yaml @@ -0,0 +1,7 @@ +apiVersion: v1 +kind: Secret +metadata: + name: secret +stringData: + database_password: "VERY_SECRET" + database_user: "MUCH_SECURE" \ No newline at end of file diff --git a/internal/decryptors/utils.go b/internal/decryptors/utils.go new file mode 100644 index 0000000..37f06e3 --- /dev/null +++ b/internal/decryptors/utils.go @@ -0,0 +1,29 @@ +package decryptors + +import ( + "encoding/json" + "fmt" + + "gopkg.in/yaml.v3" +) + +type MissingKubernetesSecret struct { + Secret string + Namespace string +} + +func (e *MissingKubernetesSecret) Error() string { + return fmt.Sprintf("Secret not found: %s/%s", e.Namespace, e.Secret) +} + +func UnmarshalJSONorYAML(data []byte) (map[string]interface{}, error) { + var result map[string]interface{} + err := json.Unmarshal(data, &result) + if err != nil { + err = yaml.Unmarshal(data, &result) + if err != nil { + return nil, err + } + } + return result, nil +} diff --git a/pkg/subst/build.go b/pkg/subst/build.go index c6b6b50..59deea5 100644 --- a/pkg/subst/build.go +++ b/pkg/subst/build.go @@ -4,12 +4,12 @@ import ( "context" "fmt" - decrypt "github.com/buttahtoast/pkg/decryptors" - ejson "github.com/buttahtoast/pkg/decryptors/ejson" - sops "github.com/buttahtoast/pkg/decryptors/sops" - "github.com/buttahtoast/subst/internal/kustomize" - "github.com/buttahtoast/subst/internal/utils" - "github.com/buttahtoast/subst/pkg/config" + decrypt "github.com/bedag/subst/internal/decryptors" + ejson "github.com/bedag/subst/internal/decryptors/ejson" + sops "github.com/bedag/subst/internal/decryptors/sops" + "github.com/bedag/subst/internal/kustomize" + "github.com/bedag/subst/internal/utils" + "github.com/bedag/subst/pkg/config" "github.com/sirupsen/logrus" "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/clientcmd" diff --git a/pkg/subst/resources.go b/pkg/subst/resources.go index aec092b..7d7c2b3 100644 --- a/pkg/subst/resources.go +++ b/pkg/subst/resources.go @@ -4,7 +4,7 @@ import ( "fmt" "log" - "github.com/buttahtoast/subst/internal/utils" + "github.com/bedag/subst/internal/utils" "sigs.k8s.io/kustomize/api/provider" ) diff --git a/pkg/subst/substitutions.go b/pkg/subst/substitutions.go index 467bfb0..a498eb2 100644 --- a/pkg/subst/substitutions.go +++ b/pkg/subst/substitutions.go @@ -8,9 +8,9 @@ import ( "regexp" "text/template" - decrypt "github.com/buttahtoast/pkg/decryptors" - "github.com/buttahtoast/subst/internal/utils" - "github.com/buttahtoast/subst/internal/wrapper" + decrypt "github.com/bedag/subst/internal/decryptors" + "github.com/bedag/subst/internal/utils" + "github.com/bedag/subst/internal/wrapper" "github.com/geofffranks/spruce" "github.com/sirupsen/logrus" "sigs.k8s.io/kustomize/api/resmap" diff --git a/subst.rb b/subst.rb index a98ad57..efe8d7e 100644 --- a/subst.rb +++ b/subst.rb @@ -10,7 +10,7 @@ class Subst < Formula on_macos do if Hardware::CPU.intel? - url "https://github.com/buttahtoast/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_darwin_amd64.tar.gz" + url "https://github.com/bedag/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_darwin_amd64.tar.gz" sha256 "dfd31dc2e0f2373baf52732a2674bb45b297f4beb2aa3111847e48b191506e05" def install @@ -18,7 +18,7 @@ def install end end if Hardware::CPU.arm? - url "https://github.com/buttahtoast/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_darwin_arm64.tar.gz" + url "https://github.com/bedag/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_darwin_arm64.tar.gz" sha256 "8407cb57e0457d95ebbd005afdff05aa060a13112223773dcdda5400b3013755" def install @@ -29,7 +29,7 @@ def install on_linux do if Hardware::CPU.arm? && Hardware::CPU.is_64_bit? - url "https://github.com/buttahtoast/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_arm64.tar.gz" + url "https://github.com/bedag/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_arm64.tar.gz" sha256 "718eb07b606178f731d803dddd5c938bbddf53fe12c4f56212cfc2d81650a1a5" def install @@ -37,7 +37,7 @@ def install end end if Hardware::CPU.intel? - url "https://github.com/buttahtoast/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_amd64.tar.gz" + url "https://github.com/bedag/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_amd64.tar.gz" sha256 "36fb49ca08918c2e117de8431fa3e6650406ec94393b80add18e71b4d91b8d12" def install @@ -45,7 +45,7 @@ def install end end if Hardware::CPU.arm? && !Hardware::CPU.is_64_bit? - url "https://github.com/buttahtoast/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_armv6.tar.gz" + url "https://github.com/bedag/subst/releases/download/v0.0.1-alpha9/subst_0.0.1-alpha9_linux_armv6.tar.gz" sha256 "7d4e84438f9d1442a99bbd9cef161f8f641ffe67174ea1bc47dcba8098f1ad26" def install diff --git a/subst/cmd/discover.go b/subst/cmd/discover.go index 59f79f7..5c3871c 100644 --- a/subst/cmd/discover.go +++ b/subst/cmd/discover.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/MakeNowJust/heredoc" - "github.com/buttahtoast/subst/pkg/config" + "github.com/bedag/subst/pkg/config" "github.com/spf13/cobra" ) diff --git a/subst/cmd/render.go b/subst/cmd/render.go index 7a14601..2c5e579 100644 --- a/subst/cmd/render.go +++ b/subst/cmd/render.go @@ -5,9 +5,9 @@ import ( "time" "github.com/MakeNowJust/heredoc" - "github.com/buttahtoast/subst/internal/utils" - "github.com/buttahtoast/subst/pkg/config" - "github.com/buttahtoast/subst/pkg/subst" + "github.com/bedag/subst/internal/utils" + "github.com/bedag/subst/pkg/config" + "github.com/bedag/subst/pkg/subst" "github.com/sirupsen/logrus" "github.com/spf13/cobra" flag "github.com/spf13/pflag" diff --git a/subst/cmd/substitutions.go b/subst/cmd/substitutions.go index 770f629..7f31d78 100644 --- a/subst/cmd/substitutions.go +++ b/subst/cmd/substitutions.go @@ -4,9 +4,9 @@ import ( "fmt" "github.com/MakeNowJust/heredoc" - "github.com/buttahtoast/subst/internal/utils" - "github.com/buttahtoast/subst/pkg/config" - "github.com/buttahtoast/subst/pkg/subst" + "github.com/bedag/subst/internal/utils" + "github.com/bedag/subst/pkg/config" + "github.com/bedag/subst/pkg/subst" "github.com/spf13/cobra" ) diff --git a/subst/main.go b/subst/main.go index 151423c..1cce116 100644 --- a/subst/main.go +++ b/subst/main.go @@ -1,7 +1,7 @@ package main import ( - "github.com/buttahtoast/subst/subst/cmd" + "github.com/bedag/subst/subst/cmd" ) func main() {