This repository has been archived by the owner on Feb 16, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 21
Integrated Terraform State Backend #285
Draft
jpcoenen
wants to merge
11
commits into
develop
Choose a base branch
from
feature/tf-state-backend
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from 9 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
cddc3ae
Add MVP of tfstate backend to secrethub run
jpcoenen c44cb03
Fix build on darwin
jpcoenen 8d0f107
Use provided lock instead of generating one
jpcoenen c212ff9
Update procspy
jpcoenen faf8d56
Give user feedback when repo/dir cannot be found
jpcoenen 72631ec
Improve error outputting to user
jpcoenen ed9d05c
Remove unused state compression
jpcoenen ab96e77
Fix linting issue
jpcoenen 4adba31
Make compilable on windows-386
jpcoenen 2483234
Add check to make sure provided path is a directory
jpcoenen 31af872
Make returned error message more explanatory
jpcoenen File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
package tfstate | ||
|
||
import ( | ||
"fmt" | ||
"io" | ||
) | ||
|
||
type Backend interface { | ||
Serve() error | ||
} | ||
|
||
type prefixWriter struct { | ||
io.Writer | ||
prefix string | ||
} | ||
|
||
func (l prefixWriter) Write(p []byte) (int, error) { | ||
_, err := fmt.Fprintf(l.Writer, "%s%s", l.prefix, p) | ||
return len(p), err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,185 @@ | ||
// +build !windows !386 | ||
|
||
package tfstate | ||
|
||
import ( | ||
"bytes" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"io/ioutil" | ||
"net/http" | ||
"os" | ||
|
||
"github.com/secrethub/secrethub-go/internals/api" | ||
"github.com/secrethub/secrethub-go/pkg/secrethub" | ||
"github.com/secrethub/secrethub-go/pkg/secretpath" | ||
) | ||
|
||
type backend struct { | ||
client secrethub.ClientInterface | ||
port uint16 | ||
logger io.Writer | ||
} | ||
|
||
func New(client secrethub.ClientInterface, port uint16, logger io.Writer) Backend { | ||
return &backend{ | ||
client: client, | ||
port: port, | ||
logger: prefixWriter{ | ||
Writer: logger, | ||
prefix: "[SecretHub]: ", | ||
}, | ||
} | ||
} | ||
|
||
func (b *backend) Serve() error { | ||
server := &http.Server{ | ||
Addr: fmt.Sprintf("127.0.0.1:%d", b.port), | ||
Handler: http.HandlerFunc(b.Handle), | ||
} | ||
err := server.ListenAndServe() | ||
if err != nil && err != http.ErrServerClosed { | ||
return err | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (b *backend) Handle(w http.ResponseWriter, r *http.Request) { | ||
resp, err := b.handle(r) | ||
if err != nil { | ||
w.WriteHeader(http.StatusInternalServerError) | ||
fmt.Fprintf(b.logger, "Encountered an unexpected error: %s\n", err) | ||
return | ||
} | ||
w.WriteHeader(resp.code) | ||
fmt.Fprintf(w, resp.body) | ||
} | ||
|
||
type statusResponse struct { | ||
code int | ||
body string | ||
} | ||
|
||
func (b *backend) respondError(statusCode int, format string, a ...interface{}) *statusResponse { | ||
msg := fmt.Sprintf(format, a...) | ||
fmt.Fprintf(b.logger, "%s\n", msg) | ||
return &statusResponse{ | ||
code: statusCode, | ||
body: msg, | ||
} | ||
} | ||
|
||
func (b *backend) handle(r *http.Request) (*statusResponse, error) { | ||
isChild, err := connectionFromChildProcess(os.Getpid(), r) | ||
if err != nil { | ||
return nil, err | ||
} | ||
if !isChild { | ||
return b.respondError(http.StatusForbidden, "can only be reached from a process spawned with secrethub run"), nil | ||
} | ||
|
||
body, err := ioutil.ReadAll(r.Body) | ||
if err != nil { | ||
return nil, fmt.Errorf("reading request body: %s", err) | ||
} | ||
|
||
path, password, ok := r.BasicAuth() | ||
if !ok { | ||
return b.respondError(http.StatusBadRequest, "set the SecretHub path to the state as the username"), nil | ||
} | ||
|
||
if secretpath.Count(path) < 2 { | ||
return b.respondError(http.StatusBadRequest, "set user to a valid repository or directory, got: %s", path), nil | ||
} | ||
|
||
statePath := secretpath.Join(path, "state") | ||
lockPath := secretpath.Join(path, "lock") | ||
passwordPath := secretpath.Join(path, "password") | ||
|
||
secret, err := b.client.Secrets().ReadString(passwordPath) | ||
if err != nil && !api.IsErrNotFound(err) { | ||
return nil, err | ||
} else if err == nil { | ||
if password == "" { | ||
return b.respondError(http.StatusUnauthorized, "password stored at %s should be set as auth password", passwordPath), nil | ||
} | ||
if password != secret { | ||
return b.respondError(http.StatusForbidden, "provided password does not password stored at %s", passwordPath), nil | ||
} | ||
} | ||
|
||
switch r.Method { | ||
case http.MethodGet: | ||
secret, err := b.client.Secrets().Read(statePath) | ||
if api.IsErrNotFound(err) { | ||
return &statusResponse{code: http.StatusNotFound}, nil | ||
} else if err != nil { | ||
return nil, err | ||
} | ||
|
||
return &statusResponse{ | ||
code: http.StatusOK, | ||
body: string(secret.Data), | ||
}, nil | ||
case http.MethodPost: | ||
_, err = b.client.Secrets().Write(statePath, body) | ||
if api.IsErrNotFound(err) { | ||
return b.respondError(http.StatusNotFound, err.Error()), nil | ||
} else if err != nil { | ||
return nil, err | ||
} | ||
return &statusResponse{ | ||
code: http.StatusOK, | ||
}, nil | ||
case "LOCK": | ||
currentLock, err := b.client.Secrets().Versions().GetWithData(lockPath + ":1") | ||
if err == nil { | ||
return &statusResponse{ | ||
code: http.StatusLocked, | ||
body: string(currentLock.Data), | ||
}, nil | ||
} else if !api.IsErrNotFound(err) { | ||
return nil, err | ||
} | ||
|
||
res, err := b.client.Secrets().Write(lockPath, body) | ||
if api.IsErrNotFound(err) { | ||
return b.respondError(http.StatusNotFound, err.Error()), nil | ||
} else if err != nil { | ||
return nil, err | ||
} | ||
if res.Version != 1 { | ||
return &statusResponse{ | ||
code: http.StatusLocked, | ||
}, nil | ||
} | ||
return &statusResponse{ | ||
code: http.StatusOK, | ||
}, nil | ||
|
||
case "UNLOCK": | ||
secret, err := b.client.Secrets().Read(lockPath) | ||
if api.IsErrNotFound(err) { | ||
return &statusResponse{ | ||
code: http.StatusOK, | ||
body: "not locked", | ||
}, nil | ||
} | ||
|
||
if len(body) > 0 && !bytes.Equal(body, secret.Data) { | ||
return b.respondError(http.StatusBadRequest, "incorrect lock"), nil | ||
} | ||
|
||
err = b.client.Secrets().Delete(lockPath) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &statusResponse{ | ||
code: http.StatusOK, | ||
}, nil | ||
default: | ||
return nil, errors.New("received an unexpected request") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
// +build windows,386 | ||
|
||
package tfstate | ||
|
||
import ( | ||
"errors" | ||
"io" | ||
|
||
"github.com/secrethub/secrethub-go/pkg/secrethub" | ||
) | ||
|
||
type notSupportedBackend struct { | ||
} | ||
|
||
func New(client secrethub.ClientInterface, port uint16, logger io.Writer) Backend { | ||
return ¬SupportedBackend{} | ||
} | ||
|
||
func (b *notSupportedBackend) Serve() error { | ||
return errors.New("tfstate backend currently not supported on Windows i386") | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
// +build !windows !386 | ||
|
||
package tfstate | ||
|
||
import ( | ||
"net" | ||
"net/http" | ||
"strconv" | ||
"strings" | ||
|
||
"github.com/mitchellh/go-ps" | ||
) | ||
|
||
func connectionFromChildProcess(pid int, r *http.Request) (bool, error) { | ||
split := strings.Split(r.RemoteAddr, ":") | ||
host := net.ParseIP(split[0]) | ||
port64, err := strconv.ParseUint(split[1], 10, 16) | ||
if err != nil { | ||
return false, err | ||
} | ||
port := uint16(port64) | ||
|
||
socks, err := tcpSocks() | ||
if err != nil { | ||
return false, err | ||
} | ||
for _, c := range socks { | ||
if c.LocalAddress.Equal(host) && c.LocalPort == port { | ||
nextProcess := c.Process.PID | ||
for { | ||
if nextProcess == pid { | ||
return true, nil | ||
} | ||
if nextProcess == 1 { | ||
break | ||
} | ||
parent, err := ps.FindProcess(nextProcess) | ||
if err != nil { | ||
return false, err | ||
} | ||
if parent == nil { | ||
break | ||
} | ||
|
||
nextProcess = parent.PPid() | ||
} | ||
} | ||
} | ||
return false, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
package tfstate | ||
|
||
import ( | ||
"net" | ||
) | ||
|
||
type Connection struct { | ||
LocalAddress net.IP | ||
LocalPort uint16 | ||
RemoteAddress net.IP | ||
RemotePort uint16 | ||
Process | ||
} | ||
|
||
type Process struct { | ||
PID int | ||
Name string | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
provided password does not password stored at %s
=>provided password does not match the password stored at %s
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch 👌