Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added CORS to the yopass-server API #2510

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ $ yopass-server -h
--redis string Redis URL (default "redis://localhost:6379/0")
--tls-cert string path to TLS certificate
--tls-key string path to TLS key
--cors allow an origin to interact with the API (defaults to self)
```

Encrypted secrets can be stored either in Memcached or Redis by changing the `--database` flag.
Expand Down
3 changes: 2 additions & 1 deletion cmd/yopass-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func init() {
pflag.String("tls-cert", "", "path to TLS certificate")
pflag.String("tls-key", "", "path to TLS key")
pflag.Bool("force-onetime-secrets", false, "reject non onetime secrets from being created")
pflag.String("cors", "", "allow an origin to interact with the API (defaults to self)")
pflag.CommandLine.AddGoFlag(&flag.Flag{Name: "log-level", Usage: "Log level", Value: &logLevel})

viper.AutomaticEnv()
Expand Down Expand Up @@ -74,7 +75,7 @@ func main() {
key := viper.GetString("tls-key")
quit := make(chan os.Signal, 1)

y := server.New(db, viper.GetInt("max-length"), registry, viper.GetBool("force-onetime-secrets"), logger)
y := server.New(db, viper.GetInt("max-length"), registry, viper.GetBool("force-onetime-secrets"), logger, viper.GetString("cors"))
yopassSrv := &http.Server{
Addr: fmt.Sprintf("%s:%d", viper.GetString("address"), viper.GetInt("port")),
Handler: y.HTTPHandler(),
Expand Down
19 changes: 13 additions & 6 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,11 @@ type Server struct {
registry *prometheus.Registry
forceOneTimeSecrets bool
logger *zap.Logger
cors string
}

// New is the main way of creating the server.
func New(db Database, maxLength int, r *prometheus.Registry, forceOneTimeSecrets bool, logger *zap.Logger) Server {
func New(db Database, maxLength int, r *prometheus.Registry, forceOneTimeSecrets bool, logger *zap.Logger, cors string) Server {
if logger == nil {
logger = zap.NewNop()
}
Expand All @@ -36,12 +37,13 @@ func New(db Database, maxLength int, r *prometheus.Registry, forceOneTimeSecrets
registry: r,
forceOneTimeSecrets: forceOneTimeSecrets,
logger: logger,
cors: cors,
}
}

// createSecret creates secret
func (y *Server) createSecret(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Origin", y.cors)

decoder := json.NewDecoder(request.Body)
var s yopass.Secret
Expand Down Expand Up @@ -95,7 +97,7 @@ func (y *Server) createSecret(w http.ResponseWriter, request *http.Request) {

// getSecret from database
func (y *Server) getSecret(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Origin", y.cors)
w.Header().Set("Cache-Control", "private, no-cache")

secretKey := mux.Vars(request)["key"]
Expand All @@ -120,7 +122,7 @@ func (y *Server) getSecret(w http.ResponseWriter, request *http.Request) {

// deleteSecret from database
func (y *Server) deleteSecret(w http.ResponseWriter, request *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Origin", y.cors)

deleted, err := y.db.Delete(mux.Vars(request)["key"])
if err != nil {
Expand All @@ -138,8 +140,9 @@ func (y *Server) deleteSecret(w http.ResponseWriter, request *http.Request) {

// optionsSecret handle the Options http method by returning the correct CORS headers
func (y *Server) optionsSecret(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", strings.Join([]string{http.MethodGet, http.MethodDelete, http.MethodOptions}, ","))
w.Header().Set("Access-Control-Allow-Origin", y.cors)
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Methods", strings.Join([]string{http.MethodGet, http.MethodPost, http.MethodDelete, http.MethodOptions}, ","))
}

// HTTPHandler containing all routes
Expand All @@ -148,15 +151,19 @@ func (y *Server) HTTPHandler() http.Handler {
mx.Use(newMetricsMiddleware(y.registry))

mx.HandleFunc("/secret", y.createSecret).Methods(http.MethodPost)
mx.HandleFunc("/secret", y.optionsSecret).Methods(http.MethodOptions)
mx.HandleFunc("/secret/"+keyParameter, y.getSecret).Methods(http.MethodGet)
mx.HandleFunc("/secret/"+keyParameter, y.deleteSecret).Methods(http.MethodDelete)
mx.HandleFunc("/secret/"+keyParameter, y.optionsSecret).Methods(http.MethodOptions)

mx.HandleFunc("/file", y.createSecret).Methods(http.MethodPost)
mx.HandleFunc("/file", y.optionsSecret).Methods(http.MethodOptions)
mx.HandleFunc("/file/"+keyParameter, y.getSecret).Methods(http.MethodGet)
mx.HandleFunc("/file/"+keyParameter, y.deleteSecret).Methods(http.MethodDelete)
mx.HandleFunc("/file/"+keyParameter, y.optionsSecret).Methods(http.MethodOptions)

mx.Use(mux.CORSMethodMiddleware(mx))

mx.PathPrefix("/").Handler(http.FileServer(http.Dir("public")))
return handlers.CustomLoggingHandler(nil, SecurityHeadersHandler(mx), httpLogFormatter(y.logger))
}
Expand Down
12 changes: 6 additions & 6 deletions pkg/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func TestCreateSecret(t *testing.T) {
t.Run(fmt.Sprintf(tc.name), func(t *testing.T) {
req, _ := http.NewRequest("POST", "/secret", tc.body)
rr := httptest.NewRecorder()
y := New(tc.db, tc.maxLength, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := New(tc.db, tc.maxLength, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
y.createSecret(rr, req)
var s yopass.Secret
json.Unmarshal(rr.Body.Bytes(), &s)
Expand Down Expand Up @@ -161,7 +161,7 @@ func TestOneTimeEnforcement(t *testing.T) {
t.Run(fmt.Sprintf(tc.name), func(t *testing.T) {
req, _ := http.NewRequest("POST", "/secret", tc.body)
rr := httptest.NewRecorder()
y := New(&mockDB{}, 100, prometheus.NewRegistry(), tc.requireOneTime, zaptest.NewLogger(t))
y := New(&mockDB{}, 100, prometheus.NewRegistry(), tc.requireOneTime, zaptest.NewLogger(t), "")
y.createSecret(rr, req)
var s yopass.Secret
json.Unmarshal(rr.Body.Bytes(), &s)
Expand Down Expand Up @@ -205,7 +205,7 @@ func TestGetSecret(t *testing.T) {
t.Fatal(err)
}
rr := httptest.NewRecorder()
y := New(tc.db, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := New(tc.db, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
y.getSecret(rr, req)
cacheControl := rr.Header().Get("Cache-Control")
if cacheControl != "private, no-cache" {
Expand Down Expand Up @@ -256,7 +256,7 @@ func TestDeleteSecret(t *testing.T) {
t.Fatal(err)
}
rr := httptest.NewRecorder()
y := New(tc.db, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := New(tc.db, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
y.deleteSecret(rr, req)
var s struct {
Message string `json:"message"`
Expand Down Expand Up @@ -286,7 +286,7 @@ func TestMetrics(t *testing.T) {
path: "/secret/invalid-key-format",
},
}
y := New(&mockDB{}, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := New(&mockDB{}, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
h := y.HTTPHandler()

for _, r := range requests {
Expand Down Expand Up @@ -359,7 +359,7 @@ func TestSecurityHeaders(t *testing.T) {
},
}

y := New(&mockDB{}, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := New(&mockDB{}, 1, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
h := y.HTTPHandler()

t.Parallel()
Expand Down
7 changes: 4 additions & 3 deletions pkg/yopass/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,19 @@ package yopass_test
import (
"errors"
"fmt"
"go.uber.org/zap/zaptest"
"net/http/httptest"
"testing"

"go.uber.org/zap/zaptest"

"github.com/jhaals/yopass/pkg/server"
"github.com/jhaals/yopass/pkg/yopass"
"github.com/prometheus/client_golang/prometheus"
)

func TestFetch(t *testing.T) {
db := testDB(map[string]string{})
y := server.New(&db, 1024, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := server.New(&db, 1024, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
ts := httptest.NewServer(y.HTTPHandler())
defer ts.Close()

Expand Down Expand Up @@ -46,7 +47,7 @@ func TestFetchInvalidServer(t *testing.T) {
}
func TestStore(t *testing.T) {
db := testDB(map[string]string{})
y := server.New(&db, 1024, prometheus.NewRegistry(), false, zaptest.NewLogger(t))
y := server.New(&db, 1024, prometheus.NewRegistry(), false, zaptest.NewLogger(t), "")
ts := httptest.NewServer(y.HTTPHandler())
defer ts.Close()

Expand Down