diff --git a/.circleci/config.yml b/.circleci/config.yml new file mode 100644 index 0000000..4f3020c --- /dev/null +++ b/.circleci/config.yml @@ -0,0 +1,21 @@ +version: 2 +build_common: &build + steps: + - checkout + - run: make build +jobs: + build_golang_1.11: + <<: *build + docker: + - image: circleci/golang:1.11 + build_golang_1.12: + <<: *build + docker: + - image: circleci/golang:1.12 + +workflows: + version: 2 + build: + jobs: + - build_golang_1.11 + - build_golang_1.12 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a51f29c --- /dev/null +++ b/.gitignore @@ -0,0 +1,12 @@ +# Go +secrethub-http-proxy +*.exe +*.exe~ +*.dll +*.so +*.dylib +dist/ + +# IDE +.vscode +.idea diff --git a/.goreleaser.yml b/.goreleaser.yml new file mode 100644 index 0000000..ed86d19 --- /dev/null +++ b/.goreleaser.yml @@ -0,0 +1,25 @@ +builds: + - binary: secrethub-http-proxy + main: ./cmd/secrethub-http-proxy/main.go + env: + - CGO_ENABLED=0 + goos: + - linux + - darwin + - windows + goarch: + - amd64 + - 386 + ignore: + - goos: darwin + goarch: 386 + +archive: + name_template: "{{ .ProjectName }}-{{ .Os }}-{{ .Arch }}" + replacements: + darwin: macOS + format_overrides: + - goos: windows + format: zip + files: + - LICENSE diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1674e38 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,21 @@ +FROM golang:1.12-alpine as build_base +WORKDIR /build +ENV GO111MODULE=on +RUN apk add --update git +COPY go.mod . +COPY go.sum . +RUN go mod download + +FROM build_base as build +RUN apk add --update make +COPY . . +RUN make build + +FROM alpine +COPY --from=build /build/secrethub-http-proxy /usr/bin/secrethub-http-proxy +RUN apk add --no-cache ca-certificates && \ + update-ca-certificates + +EXPOSE 8080 + +CMD secrethub-http-proxy -C ${SECRETHUB_CREDENTIAL:-$(cat /secrethub/credential)} -P ${SECRETHUB_CREDENTIAL_PASSPHRASE:-""} -h 0.0.0.0 -p 8080 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + 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] + + 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/Makefile b/Makefile new file mode 100644 index 0000000..2745b07 --- /dev/null +++ b/Makefile @@ -0,0 +1,2 @@ +build: + go build ./cmd/secrethub-http-proxy diff --git a/README.md b/README.md index 95552da..6cd5c8c 100644 --- a/README.md +++ b/README.md @@ -1 +1,127 @@ -# secrethub-clientd +

+ SecretHub +

+

+ HTTP ProxyBETA +

+ +[![GoDoc](https://godoc.org/github.com/secrethub/secrethub-http-proxy?status.svg)][godoc] +[![CircleCI](https://circleci.com/gh/secrethub/secrethub-http-proxy.svg)][circleci] +[![Go Report Card](https://goreportcard.com/badge/github.com/secrethub/secrethub-http-proxy)][goreportcard] +[![Version]( https://img.shields.io/github/release/secrethub/secrethub-http-proxy.svg)][latest-version] +[![Discord](https://img.shields.io/badge/chat-on%20discord-7289da.svg?logo=discord)][discord] + +The SecretHub HTTP Proxy adds a RESTful interface to the [SecretHub Client](https://github.com/secrethub/secrethub-go). +Apps can this way still use SecretHub, without having to directly include the client as a binary dependency. + +You can configure it with a SecretHub credential at start, thereby removing the need of passing it in on every request. + +> [SecretHub](https://secrethub.io) is a developer tool to help you keep database passwords, API tokens, and other secrets out of IT automation scripts. + +### A note on security + +The SecretHub HTTP Proxy opens up the configured SecretHub account over HTTP. +This moves the responsibility of securing your secrets to the domain of network security, which comes with its own risks. +So use this with caution and make sure the credential you pass in only has access to only those secrets it needs. + +It is recommended to [create a service account](https://secrethub.io/docs/reference/service-command/), tightly control it with [access rules](https://secrethub.io/docs/reference/acl-command/), and use the service credential instead of your own SecretHub account. + +``` +secrethub service init my-org/my-repo --permission read --desc my-app +``` + +## Installation + +### Binary + +Download and extract the [latest release](https://github.com/secrethub/secrethub-http-proxy/releases/latest) of the SecretHub HTTP Proxy. Start it with your SecretHub credential: + +``` +./secrethub-http-proxy -C $(cat ~/.secrethub/credential) -p 8080 +``` + +If upon signup you've chosen to lock your credential with a passphrase, you will get prompted for your passphrase. + +### Docker + +You can also run the proxy as a [Docker container](https://hub.docker.com/r/secrethub/http-proxy). +Assuming you have a SecretHub credential stored in the default `$HOME/.secrethub` location, you can run it with the credential mounted as a volume: + +``` +docker run -p 127.0.0.1:8080:8080 --name secrethub -v $HOME/.secrethub:/secrethub secrethub/http-proxy +``` + +You can also pass in the credential as an environment variable: + +``` +docker run -p 127.0.0.1:8080:8080 --name secrethub -e SECRETHUB_CREDENTIAL=$(cat $HOME/.secrethub/credential) secrethub/http-proxy +``` + +If upon signup you've chosen to lock your credential with a passphrase, run the container with `-it` to get prompted for your passphrase. + +``` +docker run -it -p 127.0.0.1:8080:8080 --name secrethub -e SECRETHUB_CREDENTIAL=$(cat $HOME/.secrethub/credential) secrethub/http-proxy +``` + +Alternatively, the passphrase can be sourced from the `SECRETHUB_CREDENTIAL_PASSPHRASE` environment variable. + +## Usage + +With the proxy up and running, you can perform the following HTTP requests: + +### `/v1beta/secrets/raw/:path` + +Example: + +``` +/v1beta/secrets/raw/my-org/my-repo/my-secret +``` + +#### `GET` + +Returns the secret contents as bytes. + +#### `POST` + +Creates or updates a secret. Expects the secret contents as bytes. + +#### `DELETE` + +Deletes the entire secret and its history. + +## BETA + +This project is currently in beta and we'd love your feedback! Check out the [issues](https://github.com/secrethub/secrethub-http-proxy/issues) and feel free to suggest cool ideas, use cases, or improvements. + +Because it's still in beta, you can expect to see some changes introduced. Pull requests are very welcome. + +## Terraform State Backend + +For those of you using [Terraform](https://www.terraform.io), the SecretHub HTTP Proxy can function as a [Terraform Backend](https://www.terraform.io/docs/backends/index.html) for your `.tfstate`. +Read more about this on our [blog post](). + +## Development + +Get the source code: + +``` +git clone https://github.com/secrethub/secrethub-http-proxy +``` + +To build the binary from source, use: + +``` +make build +``` + +To build the Docker image from scratch, you can use: + +``` +docker build -t secrethub-http-proxy . +``` + +[godoc]: https://godoc.org/github.com/secrethub/secrethub-http-proxy +[circleci]: https://circleci.com/gh/secrethub/secrethub-http-proxy +[discord]: https://discord.gg/NWmxVeb +[latest-version]: https://github.com/secrethub/secrethub-http-proxy/releases/latest +[goreportcard]: https://goreportcard.com/report/github.com/secrethub/secrethub-http-proxy diff --git a/cmd/secrethub-http-proxy/main.go b/cmd/secrethub-http-proxy/main.go new file mode 100644 index 0000000..e7341a0 --- /dev/null +++ b/cmd/secrethub-http-proxy/main.go @@ -0,0 +1,120 @@ +package main + +import ( + "flag" + "fmt" + "net/http" + "os" + "os/signal" + "syscall" + + "github.com/secrethub/secrethub-http-proxy/pkg/restproxy" + "github.com/secrethub/secrethub-go/pkg/secrethub" + "golang.org/x/crypto/ssh/terminal" +) + +var ( + credential string + credentialPassphrase string + port int + host string + client secrethub.Client +) + +func init() { + flag.StringVar(&credential, "C", "", "(Required) SecretHub credential") + flag.StringVar(&credentialPassphrase, "P", "", "Passphrase to unlock SecretHub credential") + flag.IntVar(&port, "p", 8080, "Port to listen on") + flag.StringVar(&host, "h", "127.0.0.1", "Host to listen on") + flag.Parse() + + if credential == "" { + flag.Usage() + exit(fmt.Errorf("credential is required")) + } + + cred, err := findCredential(credential, credentialPassphrase) + if err != nil { + exit(err) + } + + client = secrethub.NewClient(cred, nil) +} + +func findCredential(credential string, passphrase string) (secrethub.Credential, error) { + parser := secrethub.NewCredentialParser(secrethub.DefaultCredentialDecoders) + + encoded, err := parser.Parse(credential) + if err != nil { + return nil, err + } + + if encoded.IsEncrypted() { + if passphrase == "" { + passphrase, err = promptPassword() + if err != nil { + return nil, err + } + } + + key, err := secrethub.NewPassBasedKey([]byte(passphrase)) + if err != nil { + return nil, err + } + + credential, err := encoded.DecodeEncrypted(key) + if err != nil { + return nil, err + } + + return credential, err + } + + return encoded.Decode() +} + +func main() { + proxy := restproxy.NewRESTProxy(client, host, port) + + go gracefulShutdown(proxy) + + log("SecretHub REST proxy started, press ^C to stop it") + err := proxy.Start() + if err != nil && err != http.ErrServerClosed { + exit(err) + } +} + +func promptPassword() (string, error) { + fmt.Printf("Please put in the passphrase to unlock your credential:") + password, err := terminal.ReadPassword(int(syscall.Stdin)) + fmt.Println() + if err != nil { + return "", err + } + + return string(password), nil +} + +func gracefulShutdown(proxy restproxy.ClientProxy) { + sigint := make(chan os.Signal, 1) + + signal.Notify(sigint, os.Interrupt) + signal.Notify(sigint, syscall.SIGTERM) + <-sigint + + log("Shutting down gracefully...") + err := proxy.Stop() + if err != nil { + exit(err) + } +} + +func exit(err error) { + fmt.Printf("secrethub-http-proxy: error: %v\n", err) + os.Exit(1) +} + +func log(message string) { + fmt.Printf("secrethub-http-proxy: %v\n", message) +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..83ed8d3 --- /dev/null +++ b/go.mod @@ -0,0 +1,8 @@ +module github.com/secrethub/secrethub-http-proxy + +require ( + github.com/gorilla/mux v1.7.0 + github.com/secrethub/secrethub-go v0.18.0 + golang.org/x/crypto v0.0.0-20190225124518-7f87c0fbb88b + golang.org/x/sys v0.0.0-20190329044733-9eb1bfa1ce65 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..d13b7e0 --- /dev/null +++ b/go.sum @@ -0,0 +1,39 @@ +bitbucket.org/zombiezen/cardcpx v0.0.0-20150417151802-902f68ff43ef h1:Y5Zf3CYdrdGE7GOuK/MNN98GS1V8mOfeiJlISrKUcEo= +bitbucket.org/zombiezen/cardcpx v0.0.0-20150417151802-902f68ff43ef/go.mod h1:ZJR5FpaQx7Bt2bzIV3gBaCInI1+kG949WhNYYlRr8eA= +github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf h1:eg0MeVzsP1G42dRafH3vf+al2vQIJU0YHX+1Tw87oco= +github.com/asaskevich/govalidator v0.0.0-20180720115003-f9ffefc3facf/go.mod h1:lB+ZfQJz7igIIfQNfa7Ml4HSf2uFQQRzpGGRXenZAgY= +github.com/certifi/gocertifi v0.0.0-20190105021004-abcd57078448 h1:8tNk6SPXzLDnATTrWoI5Bgw9s/x4uf0kmBpk21NZgI4= +github.com/certifi/gocertifi v0.0.0-20190105021004-abcd57078448/go.mod h1:GJKEexRPVJrBSOjoqN5VNOIKJ5Q3RViH6eu3puDRwx4= +github.com/docker/go-units v0.3.3 h1:Xk8S3Xj5sLGlG5g67hJmYMmUgXv5N4PhkjJHHqrwnTk= +github.com/docker/go-units v0.3.3/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk= +github.com/getsentry/raven-go v0.2.0 h1:no+xWJRb5ZI7eE8TWgIq1jLulQiIoLG0IfYxv5JYMGs= +github.com/getsentry/raven-go v0.2.0/go.mod h1:KungGk8q33+aIAZUIVWZDr2OfAEBsO49PX4NzFV5kcQ= +github.com/go-chi/chi v4.0.1+incompatible h1:RSRC5qmFPtO90t7pTL0DBMNpZFsb/sHF3RXVlDgFisA= +github.com/go-chi/chi v4.0.1+incompatible/go.mod h1:eB3wogJHnLi3x/kFX2A+IbTBlXxmMeXJVKy9tTv1XzQ= +github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= +github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= +github.com/gorilla/mux v1.7.0 h1:tOSd0UKHQd6urX6ApfOn4XdBMY6Sh1MfxV3kmaazO+U= +github.com/gorilla/mux v1.7.0/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs= +github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348 h1:MtvEpTB6LX3vkb4ax0b5D2DHbNAUsen0Gx5wZoq3lV4= +github.com/kylelemons/godebug v0.0.0-20170820004349-d65d576e9348/go.mod h1:B69LEHPfb2qLo0BaaOLcbitczOKLWTsrBG9LczfCD4k= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= +github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww= +github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0= +github.com/secrethub/secrethub-go v0.17.0 h1:AlRbFlLofhzY7Onv1QRI0u0iB4UTr8PCrNW5rnvsiHE= +github.com/secrethub/secrethub-go v0.17.0/go.mod h1:gqrxdTNcVowCy/Bo49Y+7En12aV24wnoG3ktUF9xW/k= +github.com/secrethub/secrethub-go v0.18.0 h1:6Jm3d/UjaWgOoduZX9S1MjiXG+zyVsxkpQ5RxLRucRs= +github.com/secrethub/secrethub-go v0.18.0/go.mod h1:gqrxdTNcVowCy/Bo49Y+7En12aV24wnoG3ktUF9xW/k= +golang.org/x/crypto v0.0.0-20190225124518-7f87c0fbb88b h1:+/WWzjwW6gidDJnMKWLKLX1gxn7irUTF1fLpQovfQ5M= +golang.org/x/crypto v0.0.0-20190225124518-7f87c0fbb88b/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4= +golang.org/x/sys v0.0.0-20190329044733-9eb1bfa1ce65 h1:hOY+O8MxdkPV10pNf7/XEHaySCiPKxixMKUshfHsGn0= +golang.org/x/sys v0.0.0-20190329044733-9eb1bfa1ce65/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= diff --git a/pkg/restproxy/rest_proxy.go b/pkg/restproxy/rest_proxy.go new file mode 100644 index 0000000..1eacbdd --- /dev/null +++ b/pkg/restproxy/rest_proxy.go @@ -0,0 +1,141 @@ +package restproxy + +import ( + "context" + "fmt" + "io" + "io/ioutil" + "log" + "net/http" + + "github.com/gorilla/mux" + "github.com/secrethub/secrethub-go/internals/api" + "github.com/secrethub/secrethub-go/internals/errio" + "github.com/secrethub/secrethub-go/pkg/secrethub" +) + +// ClientProxy gives the SecretHub Client a certain communication layer +type ClientProxy interface { + Start() error + Stop() error +} + +type restProxy struct { + ClientProxy + client secrethub.Client + server *http.Server +} + +// NewRESTProxy creates a proxy for the SecretHub Client, giving it a RESTful interface +func NewRESTProxy(client secrethub.Client, host string, port int) ClientProxy { + if port == 0 { + port = 8080 + } + + router := mux.NewRouter() + proxy := &restProxy{ + client: client, + server: &http.Server{ + Addr: fmt.Sprintf("%v:%d", host, port), + Handler: router, + }, + } + proxy.addRoutes(router) + + return proxy +} + +func (p *restProxy) addRoutes(r *mux.Router) { + v := r.PathPrefix("/v1beta/").Subrouter() + + v.PathPrefix("/secrets/").Handler( + http.StripPrefix("/v1beta/secrets/raw/", http.HandlerFunc(p.handleSecret)), + ) +} + +// Start starts the SecretHub REST proxy, starting an HTTP server +func (p *restProxy) Start() error { + return p.server.ListenAndServe() +} + +// Stop stops the SecretHub REST proxy, stopping the HTTP server +func (p *restProxy) Stop() error { + return p.server.Shutdown(context.Background()) +} + +func (p *restProxy) handleSecret(w http.ResponseWriter, r *http.Request) { + path := r.URL.Path + err := api.ValidateSecretPath(path) + if err != nil { + writeError(w, err, http.StatusBadRequest) + return + } + + switch r.Method { + case "GET": + secret, err := p.client.Secrets().Versions().GetWithData(path) + if err != nil { + writeError(w, err, 0) + return + } + + w.WriteHeader(http.StatusOK) + _, err = w.Write(secret.Data) + if err != nil { + log.Printf("failed to write HTTP response: %s", err) + } + case "POST": + secret, err := ioutil.ReadAll(r.Body) + if err != nil { + writeError(w, err, http.StatusInternalServerError) + return + } + + _, err = p.client.Secrets().Write(path, secret) + if err != nil { + statusCode := 0 + switch err { + case secrethub.ErrCannotWriteToVersion, + secrethub.ErrEmptySecret, + secrethub.ErrSecretTooBig: + statusCode = http.StatusBadRequest + } + + writeError(w, err, statusCode) + return + } + + w.WriteHeader(http.StatusCreated) + case "DELETE": + err := p.client.Secrets().Versions().Delete(path) + if err != nil { + writeError(w, err, 0) + return + } + + w.WriteHeader(http.StatusOK) + default: + w.Header().Add("Allow", "GET, POST, DELETE") + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + +// writeError writes an error message and HTTP status code to the ResponseWriter. +// The HTTP status code is derived from the error, unless overriden by the statusCode argument. +func writeError(w http.ResponseWriter, err error, statusCode int) { + if statusCode == 0 { + if err, ok := err.(errio.PublicStatusError); ok { + statusCode = err.StatusCode + } + + if statusCode == 0 { + statusCode = http.StatusInternalServerError + } + } + + w.WriteHeader(statusCode) + _, err = io.WriteString(w, err.Error()) + if err != nil { + log.Printf("failed to write error to HTTP response: %s", err) + } +}