diff --git a/Gopkg.lock b/Gopkg.lock index 87192e00..b97a44ce 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -3,6 +3,7 @@ [[projects]] branch = "master" + digest = "1:6103ab273af1420815a18e18beac470583d002e0e4b6b0d7fcdc002f9572d3b1" name = "github.com/Peripli/service-broker-proxy" packages = [ "pkg/config", @@ -11,12 +12,14 @@ "pkg/osb", "pkg/platform", "pkg/sbproxy", - "pkg/sm" + "pkg/sm", ] - revision = "8fe36b08cf14e0c39204f1f0dc1e4b6c9f0e01c5" + pruneopts = "" + revision = "179b726d66b7f3072d5f53eea0060df805e10845" [[projects]] branch = "master" + digest = "1:ddbe6d323fdf46da3f6dd75c8c0f646d9bc0d60a3436cc8a266d75c070f503ef" name = "github.com/Peripli/service-manager" packages = [ "api", @@ -38,34 +41,44 @@ "security", "security/basic", "security/oidc", - "storage" + "storage", ] - revision = "867632bb5ed70b67a07b0b70f0314e745a57ef23" + pruneopts = "" + revision = "11ca684ab38d0e30994ef0855b443c2ae232ab52" [[projects]] + digest = "1:d8ee1b165eb7f4fd9ada718e1e7eeb0bc1fd462592d0bd823df694443f448681" name = "github.com/coreos/go-oidc" packages = ["."] + pruneopts = "" revision = "1180514eaf4d9f38d0d19eef639a1d695e066e72" [[projects]] + digest = "1:55848e643a99a9dfceb19e090ce67111328fbb1780f34c62a0430994ff85fb90" name = "github.com/fatih/structs" packages = ["."] + pruneopts = "" revision = "a720dfa8df582c51dee1b36feabb906bde1588bd" version = "v1.0" [[projects]] + digest = "1:eb53021a8aa3f599d29c7102e65026242bdedce998a54837dc67f14b6a97c5fd" name = "github.com/fsnotify/fsnotify" packages = ["."] + pruneopts = "" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] + digest = "1:b13707423743d41665fd23f0c36b2f37bb49c30e94adb813319c44188a51ba22" name = "github.com/ghodss/yaml" packages = ["."] + pruneopts = "" revision = "0ca9ea5df5451ffdf184b4428c902747c2c11cd7" version = "v1.0.0" [[projects]] + digest = "1:9ab1b1c637d7c8f49e39d8538a650d7eb2137b076790cff69d160823b505964c" name = "github.com/gobwas/glob" packages = [ ".", @@ -75,107 +88,126 @@ "syntax/ast", "syntax/lexer", "util/runes", - "util/strings" + "util/strings", ] + pruneopts = "" revision = "5ccd90ef52e1e632236f7326478d4faa74f99438" version = "v0.2.3" [[projects]] + digest = "1:e823c0070e200c011e294c904475e64b4c2ff729aafc3dd2363c20890e88e3f5" name = "github.com/gofrs/uuid" packages = ["."] + pruneopts = "" revision = "d41eeda0759468834c84365a32d1b1ec4264c75f" version = "v3.1.0" [[projects]] + digest = "1:6e73003ecd35f4487a5e88270d3ca0a81bc80dc88053ac7e4dcfec5fba30d918" name = "github.com/gogo/protobuf" packages = [ "proto", - "sortkeys" + "sortkeys", ] + pruneopts = "" revision = "636bf0302bc95575d69441b25a2603156ffdddf1" version = "v1.1.1" [[projects]] branch = "master" + digest = "1:107b233e45174dbab5b1324201d092ea9448e58243ab9f039e4c0f332e121e3a" name = "github.com/golang/glog" packages = ["."] + pruneopts = "" revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998" [[projects]] + digest = "1:3dd078fda7500c341bc26cfbc6c6a34614f295a2457149fc1045cab767cbcf18" name = "github.com/golang/protobuf" packages = [ "proto", "ptypes", "ptypes/any", "ptypes/duration", - "ptypes/timestamp" + "ptypes/timestamp", ] + pruneopts = "" revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5" version = "v1.2.0" [[projects]] branch = "master" + digest = "1:1e5b1e14524ed08301977b7b8e10c719ed853cbf3f24ecb66fae783a46f207a6" name = "github.com/google/btree" packages = ["."] + pruneopts = "" revision = "4030bb1f1f0c35b30ca7009e9ebd06849dd45306" [[projects]] branch = "master" + digest = "1:754f77e9c839b24778a4b64422236d38515301d2baeb63113aa3edc42e6af692" name = "github.com/google/gofuzz" packages = ["."] + pruneopts = "" revision = "24818f796faf91cd76ec7bddd72458fbced7a6c1" [[projects]] + digest = "1:16b2837c8b3cf045fa2cdc82af0cf78b19582701394484ae76b2c3bc3c99ad73" name = "github.com/googleapis/gnostic" packages = [ "OpenAPIv2", "compiler", - "extensions" + "extensions", ] + pruneopts = "" revision = "7c663266750e7d82587642f65e60bc4083f1f84e" version = "v0.2.0" [[projects]] + digest = "1:dbbeb8ddb0be949954c8157ee8439c2adfd8dc1c9510eb44a6e58cb68c3dce28" name = "github.com/gorilla/context" packages = ["."] + pruneopts = "" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - name = "github.com/gorilla/handlers" - packages = ["."] - revision = "90663712d74cb411cbef281bc1e08c19d1a76145" - version = "v1.3.0" - -[[projects]] + digest = "1:aa016bbb412f496a7baed9e02787a60cd15c9a3edfa72da9c4a95d6cea610334" name = "github.com/gorilla/mux" packages = ["."] + pruneopts = "" revision = "53c1911da2b537f792e7cafcb446b05ffe33b996" version = "v1.6.1" [[projects]] branch = "master" + digest = "1:009a1928b8c096338b68b5822d838a72b4d8520715c1463614476359f3282ec8" name = "github.com/gregjones/httpcache" packages = [ ".", - "diskcache" + "diskcache", ] + pruneopts = "" revision = "9cad4c3443a7200dd6400aef47183728de563a38" [[projects]] - branch = "master" + digest = "1:8e3bd93036b4a925fe2250d3e4f38f21cadb8ef623561cd80c3c50c114b13201" name = "github.com/hashicorp/errwrap" packages = ["."] - revision = "d6c0cd88035724dd42e0f335ae30161c20575ecc" + pruneopts = "" + revision = "8a6fb523712970c966eefc6b39ed2c5e74880354" + version = "v1.0.0" [[projects]] - branch = "master" + digest = "1:72308fdd6d5ef61106a95be7ca72349a5565809042b6426a3cfb61d99483b824" name = "github.com/hashicorp/go-multierror" packages = ["."] - revision = "3d5d8f294aa03d8e98859feac328afbdf1ae0703" + pruneopts = "" + revision = "886a7fbe3eb1c874d46f623bfa70af45f425b3d1" + version = "v1.0.0" [[projects]] - branch = "master" + digest = "1:d14365c51dd1d34d5c79833ec91413bfbb166be978724f15701e17080dc06dec" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -187,29 +219,36 @@ "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + pruneopts = "" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" [[projects]] + digest = "1:b3c5b95e56c06f5aa72cb2500e6ee5f44fcd122872d4fec2023a488e561218bc" name = "github.com/hpcloud/tail" packages = [ ".", "ratelimiter", "util", "watch", - "winfile" + "winfile", ] + pruneopts = "" revision = "a30252cb686a21eb2d0b98132633053ec2f7f1e5" version = "v1.0.0" [[projects]] + digest = "1:b79fc583e4dc7055ed86742e22164ac41bf8c0940722dbcb600f1a3ace1a8cb5" name = "github.com/json-iterator/go" packages = ["."] + pruneopts = "" revision = "1624edc4454b8682399def8740d46db5e4362ba4" - version = "1.1.5" + version = "v1.1.5" [[projects]] + digest = "1:783dce2cae6d8a4ad98ae1a1debcd997572b769e45c65b1e48533b7cb5f08e28" name = "github.com/kubernetes-incubator/service-catalog" packages = [ "pkg/apis/servicecatalog", @@ -221,45 +260,54 @@ "pkg/client/clientset_generated/clientset/typed/servicecatalog/v1beta1", "pkg/client/clientset_generated/clientset/typed/settings/v1alpha1", "pkg/filter", - "pkg/svcat/service-catalog" + "pkg/svcat/service-catalog", ] + pruneopts = "N" revision = "f6f0e41fae6c4f1bdc5c507942ee7f1719555a19" version = "v0.1.27" [[projects]] + digest = "1:961dc3b1d11f969370533390fdf203813162980c858e1dabe827b60940c909a5" name = "github.com/magiconair/properties" packages = ["."] + pruneopts = "" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] - branch = "master" + digest = "1:5219b4506253ccc598f9340677162a42d6a78f340a4cc6df2d62db4d0593c4e9" name = "github.com/mitchellh/mapstructure" packages = ["."] - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" + pruneopts = "" + revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8" + version = "v1.0.0" [[projects]] + digest = "1:0c0ff2a89c1bb0d01887e1dac043ad7efbf3ec77482ef058ac423d13497e16fd" name = "github.com/modern-go/concurrent" packages = ["."] + pruneopts = "" revision = "bacd9c7ef1dd9b15be4a9909b8ac7a4e313eec94" version = "1.0.3" [[projects]] + digest = "1:e32bdbdb7c377a07a9a46378290059822efdce5c8d96fe71940d87cb4f918855" name = "github.com/modern-go/reflect2" packages = ["."] + pruneopts = "" revision = "4b7aa43c6742a2c18fdef89dd197aaae7dac7ccd" version = "1.0.1" [[projects]] branch = "master" + digest = "1:57eb9b1281b805a5ac973a015658f366eabfe3454c76c587ef135d6f5c6dcdca" name = "github.com/onrik/logrus" - packages = [ - "filename", - "formatter" - ] + packages = ["filename"] + pruneopts = "" revision = "ca0a758702be2ae04725ba88dcd27a71949faf33" [[projects]] + digest = "1:a7fd918fb5bd2188436785c0424f8a50b4addfedf37a2b14d796be2a927b8007" name = "github.com/onsi/ginkgo" packages = [ ".", @@ -279,12 +327,14 @@ "reporters/stenographer", "reporters/stenographer/support/go-colorable", "reporters/stenographer/support/go-isatty", - "types" + "types", ] + pruneopts = "" revision = "3774a09d95489ccaa16032e0770d08ea77ba6184" version = "v1.6.0" [[projects]] + digest = "1:3ecd0a37c4a90c12a97e31c398cdbc173824351aa891898ee178120bfe71c478" name = "github.com/onsi/gomega" packages = [ ".", @@ -298,108 +348,138 @@ "matchers/support/goraph/edge", "matchers/support/goraph/node", "matchers/support/goraph/util", - "types" + "types", ] - revision = "b6ea1ea48f981d0f615a154a45eabb9dd466556d" - version = "v1.4.1" + pruneopts = "" + revision = "7615b9433f86a8bdf29709bf288bc4fd0636a369" + version = "v1.4.2" [[projects]] + digest = "1:894aef961c056b6d85d12bac890bf60c44e99b46292888bfa66caf529f804457" name = "github.com/pelletier/go-toml" packages = ["."] + pruneopts = "" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] branch = "master" + digest = "1:c24598ffeadd2762552269271b3b1510df2d83ee6696c1e543a0ff653af494bc" name = "github.com/petar/GoLLRB" packages = ["llrb"] + pruneopts = "" revision = "53be0d36a84c2a886ca057d34b6aa4468df9ccb4" [[projects]] + digest = "1:b46305723171710475f2dd37547edd57b67b9de9f2a6267cafdd98331fd6897f" name = "github.com/peterbourgon/diskv" packages = ["."] + pruneopts = "" revision = "5f041e8faa004a95c88a202771f4cc3e991971e6" version = "v2.0.1" [[projects]] + digest = "1:7365acd48986e205ccb8652cc746f09c8b7876030d53710ea6ef7d0bd0dcd7ca" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] + digest = "1:188a4bd1220db10cdca1d8f74b20bcc7cf08c90385785fcca1bdf907a648cdd1" name = "github.com/pmorie/go-open-service-broker-client" packages = ["v2"] + pruneopts = "" revision = "dca737037ce636eb282e84e3a1c7479c9692e884" version = "0.0.10" [[projects]] branch = "master" + digest = "1:de5481dda0c081b66450e391bbb1a5c4435b13e3c0bbf0133ba1a5baeda7b7af" name = "github.com/pquerna/cachecontrol" packages = [ ".", - "cacheobject" + "cacheobject", ] + pruneopts = "" revision = "1555304b9b35fdd2b425bccf1a5613677705e7d0" [[projects]] branch = "master" + digest = "1:6ab228f39a195cb1dab3564a0f27dc24a52bb3a19fa58dd2967f1e7b2482d82b" name = "github.com/robfig/cron" packages = ["."] + pruneopts = "" revision = "b41be1df696709bb6395fe435af20370037c0b4c" [[projects]] + digest = "1:42a42c4bc67bed17f40fddf0f24d4403e25e7b96488456cf4248e6d16659d370" name = "github.com/sirupsen/logrus" packages = ["."] + pruneopts = "" revision = "d682213848ed68c0a260ca37d6dd5ace8423f5ba" version = "v1.0.4" [[projects]] + digest = "1:d0431c2fd72e39ee43ea7742322abbc200c3e704c9102c5c3c2e2e667095b0ca" name = "github.com/spf13/afero" packages = [ ".", - "mem" + "mem", ] - revision = "787d034dfe70e44075ccc060d346146ef53270ad" - version = "v1.1.1" + pruneopts = "" + revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd" + version = "v1.1.2" [[projects]] + digest = "1:d0b38ba6da419a6d4380700218eeec8623841d44a856bb57369c172fbf692ab4" name = "github.com/spf13/cast" packages = ["."] + pruneopts = "" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] - branch = "master" + digest = "1:9ceffa4ab5f7195ecf18b3a7fff90c837a9ed5e22e66d18069e4bccfe1f52aa0" name = "github.com/spf13/jwalterweatherman" packages = ["."] - revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2" + pruneopts = "" + revision = "4a4406e478ca629068e7768fc33f3f044173c0a6" + version = "v1.0.0" [[projects]] + digest = "1:8e243c568f36b09031ec18dff5f7d2769dcf5ca4d624ea511c8e3197dc3d352d" name = "github.com/spf13/pflag" packages = ["."] + pruneopts = "" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] + digest = "1:3dab237cd3263a290d771d133fed777bb56c22e380b00ebe92e6531d5c8d3d0c" name = "github.com/spf13/viper" packages = ["."] + pruneopts = "" revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" version = "v1.0.2" [[projects]] branch = "master" + digest = "1:61a86f0be8b466d6e3fbdabb155aaa4006137cb5e3fd3b949329d103fa0ceb0f" name = "golang.org/x/crypto" packages = [ "ed25519", "ed25519/internal/edwards25519", "pbkdf2", - "ssh/terminal" + "ssh/terminal", ] - revision = "614d502a4dac94afa3a6ce146bd1736da82514c6" + pruneopts = "" + revision = "0e37d006457bf46f9e6692014ba72ef82c33022c" [[projects]] branch = "master" + digest = "1:fbdbb6cf8db3278412c9425ad78b26bb8eb788181f26a3ffb3e4f216b314f86a" name = "golang.org/x/net" packages = [ "context", @@ -410,29 +490,35 @@ "http/httpguts", "http2", "http2/hpack", - "idna" + "idna", ] - revision = "922f4815f713f213882e8ef45e0d315b164d705c" + pruneopts = "" + revision = "26e67e76b6c3f6ce91f7c52def5af501b4e0f3a2" [[projects]] branch = "master" + digest = "1:b697592485cb412be4188c08ca0beed9aab87f36b86418e21acc4a3998f63734" name = "golang.org/x/oauth2" packages = [ ".", - "internal" + "internal", ] - revision = "f720f1faee02c1fb456408c22886169405f239aa" + pruneopts = "" + revision = "d2e6202438beef2727060aa7cabdd924d92ebfd9" [[projects]] branch = "master" + digest = "1:6f8f4a4fffbef9ef137261e37fd4da98981b978efeb79837434be05831bb87fc" name = "golang.org/x/sys" packages = [ "unix", - "windows" + "windows", ] - revision = "4ea2f632f6e912459fe60b26b1749377f0d889d5" + pruneopts = "" + revision = "ee1b12c67af419cf5a9be3bdbeea7fc1c5f32f11" [[projects]] + digest = "1:5acd3512b047305d49e8763eef7ba423901e85d5dd2fd1e71778a0ea8de10bd4" name = "golang.org/x/text" packages = [ "collate", @@ -460,18 +546,22 @@ "unicode/bidi", "unicode/cldr", "unicode/norm", - "unicode/rangetable" + "unicode/rangetable", ] + pruneopts = "" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] branch = "master" + digest = "1:55a681cb66f28755765fa5fa5104cbd8dc85c55c02d206f9f89566451e3fe1aa" name = "golang.org/x/time" packages = ["rate"] + pruneopts = "" revision = "fbb02b2291d28baffd63558aa44b4b56f178d650" [[projects]] + digest = "1:8c432632a230496c35a15cfdf441436f04c90e724ad99c8463ef0c82bbe93edb" name = "google.golang.org/appengine" packages = [ "internal", @@ -480,47 +570,59 @@ "internal/log", "internal/remote_api", "internal/urlfetch", - "urlfetch" + "urlfetch", ] - revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" - version = "v1.1.0" + pruneopts = "" + revision = "ae0ab99deb4dc413a2b4bd6c8bdd0eb67f1e4d06" + version = "v1.2.0" [[projects]] + digest = "1:eb53021a8aa3f599d29c7102e65026242bdedce998a54837dc67f14b6a97c5fd" name = "gopkg.in/fsnotify.v1" packages = ["."] + pruneopts = "" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" source = "https://github.com/fsnotify/fsnotify.git" version = "v1.4.7" [[projects]] + digest = "1:75fb3fcfc73a8c723efde7777b40e8e8ff9babf30d8c56160d01beffea8a95a6" name = "gopkg.in/inf.v0" packages = ["."] + pruneopts = "" revision = "d2d2541c53f18d2a059457998ce2876cc8e67cbf" version = "v0.9.1" [[projects]] + digest = "1:78c193a044c9c6f540da8158d8d8af12f3615d0261e7fa172e0cadcd05abd64f" name = "gopkg.in/square/go-jose.v2" packages = [ ".", "cipher", - "json" + "json", ] + pruneopts = "" revision = "8254d6c783765f38c8675fae4427a1fe73fbd09d" version = "v2.1.8" [[projects]] branch = "v1" + digest = "1:a96d16bd088460f2e0685d46c39bcf1208ba46e0a977be2df49864ec7da447dd" name = "gopkg.in/tomb.v1" packages = ["."] + pruneopts = "" revision = "dd632973f1e7218eb1089048e0798ec9ae7dceb8" [[projects]] + digest = "1:f0620375dd1f6251d9973b5f2596228cc8042e887cd7f827e4220bc1ce8c30e2" name = "gopkg.in/yaml.v2" packages = ["."] + pruneopts = "" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [[projects]] + digest = "1:f420c8548c93242d8e5dcfa5b34e0243883b4e660f65076e869daafac877144d" name = "k8s.io/api" packages = [ "admissionregistration/v1alpha1", @@ -551,12 +653,14 @@ "settings/v1alpha1", "storage/v1", "storage/v1alpha1", - "storage/v1beta1" + "storage/v1beta1", ] + pruneopts = "" revision = "072894a440bdee3a891dea811fe42902311cd2a3" version = "kubernetes-1.11.0" [[projects]] + digest = "1:b6b2fb7b4da1ac973b64534ace2299a02504f16bc7820cb48edb8ca4077183e1" name = "k8s.io/apimachinery" packages = [ "pkg/api/errors", @@ -593,12 +697,14 @@ "pkg/util/yaml", "pkg/version", "pkg/watch", - "third_party/forked/golang/reflect" + "third_party/forked/golang/reflect", ] + pruneopts = "" revision = "103fd098999dc9c0c88536f5c9ad2e5da39373ae" version = "kubernetes-1.11.0" [[projects]] + digest = "1:d04779a8de7d5465e0463bd986506348de5e89677c74777f695d3145a7a8d15e" name = "k8s.io/client-go" packages = [ "discovery", @@ -647,14 +753,30 @@ "util/cert", "util/connrotation", "util/flowcontrol", - "util/integer" + "util/integer", ] + pruneopts = "" revision = "7d04d0e2a0a1a4d4a1cd6baa432a2301492e4e65" version = "v8.0.0" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "4eebd76d4498f05d79921a7ef1c7fe7925fb4246c78a915bf7ad8560141c820b" + input-imports = [ + "github.com/Peripli/service-broker-proxy/pkg/middleware", + "github.com/Peripli/service-broker-proxy/pkg/platform", + "github.com/Peripli/service-broker-proxy/pkg/sbproxy", + "github.com/Peripli/service-manager/pkg/env", + "github.com/Peripli/service-manager/pkg/util", + "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1", + "github.com/kubernetes-incubator/service-catalog/pkg/client/clientset_generated/clientset", + "github.com/kubernetes-incubator/service-catalog/pkg/svcat/service-catalog", + "github.com/onsi/ginkgo", + "github.com/onsi/gomega", + "github.com/spf13/pflag", + "k8s.io/apimachinery/pkg/apis/meta/v1", + "k8s.io/client-go/kubernetes", + "k8s.io/client-go/rest", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/k8s/client.go b/k8s/client.go index 9431497a..98db1270 100644 --- a/k8s/client.go +++ b/k8s/client.go @@ -1,6 +1,7 @@ package k8s import ( + "context" "github.com/Peripli/service-broker-proxy/pkg/platform" "github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1" "github.com/kubernetes-incubator/service-catalog/pkg/svcat/service-catalog" @@ -60,7 +61,7 @@ func NewClient(config *ClientConfiguration) (*PlatformClient, error) { } // GetBrokers returns all service-brokers currently registered in kubernetes service-catalog. -func (b PlatformClient) GetBrokers() ([]platform.ServiceBroker, error) { +func (b PlatformClient) GetBrokers(ctx context.Context) ([]platform.ServiceBroker, error) { brokers, err := retrieveClusterServiceBrokers(b.cli) if err != nil { return nil, err @@ -78,7 +79,7 @@ func (b PlatformClient) GetBrokers() ([]platform.ServiceBroker, error) { } // CreateBroker registers a new broker in kubernetes service-catalog. -func (b PlatformClient) CreateBroker(r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) { +func (b PlatformClient) CreateBroker(ctx context.Context, r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) { broker := newServiceBroker(r.Name, r.BrokerURL, b.regSecretRef) broker.Spec.CommonServiceBrokerSpec.RelistBehavior = "Manual" @@ -94,12 +95,12 @@ func (b PlatformClient) CreateBroker(r *platform.CreateServiceBrokerRequest) (*p } // DeleteBroker deletes an existing broker in from kubernetes service-catalog. -func (b PlatformClient) DeleteBroker(r *platform.DeleteServiceBrokerRequest) error { +func (b PlatformClient) DeleteBroker(ctx context.Context, r *platform.DeleteServiceBrokerRequest) error { return deleteClusterServiceBroker(b.cli, r.Name, &v1.DeleteOptions{}) } // UpdateBroker updates a service broker in the kubernetes service-catalog. -func (b PlatformClient) UpdateBroker(r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) { +func (b PlatformClient) UpdateBroker(ctx context.Context, r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) { // Name and broker url are updateable broker := newServiceBroker(r.Name, r.BrokerURL, b.regSecretRef) @@ -116,7 +117,7 @@ func (b PlatformClient) UpdateBroker(r *platform.UpdateServiceBrokerRequest) (*p // Fetch the new catalog information from reach service-broker registered in kubernetes, // so that it is visible in the kubernetes service-catalog. -func (b PlatformClient) Fetch(serviceBroker *platform.ServiceBroker) error { +func (b PlatformClient) Fetch(ctx context.Context, serviceBroker *platform.ServiceBroker) error { return syncClusterServiceBroker(b.cli, serviceBroker.Name, 3) } diff --git a/k8s/client_test.go b/k8s/client_test.go index a4b2c78d..0e08e836 100644 --- a/k8s/client_test.go +++ b/k8s/client_test.go @@ -1,6 +1,7 @@ package k8s import ( + "context" "errors" "github.com/Peripli/service-broker-proxy/pkg/platform" @@ -19,7 +20,7 @@ import ( var _ = Describe("Kubernetes Broker Proxy", func() { var clientConfig *ClientConfiguration - + var ctx context.Context BeforeSuite(func() { os.Setenv("KUBERNETES_SERVICE_HOST", "test") os.Setenv("KUBERNETES_SERVICE_PORT", "1234") @@ -36,6 +37,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { clientConfig.Reg.Secret.Name = "secretName" clientConfig.Reg.Secret.Namespace = "secretNamespace" clientConfig.K8sClientCreateFunc = newSvcatSDK + ctx = context.TODO() }) Describe("New Client", func() { @@ -85,7 +87,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { Name: "fake-broker", BrokerURL: "http://fake.broker.url", } - createdBroker, err := platformClient.CreateBroker(requestBroker) + createdBroker, err := platformClient.CreateBroker(ctx, requestBroker) Expect(createdBroker.GUID).To(Equal("1234")) Expect(createdBroker.Name).To(Equal("fake-broker")) @@ -104,7 +106,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { } requestBroker := &platform.CreateServiceBrokerRequest{} - createdBroker, err := platformClient.CreateBroker(requestBroker) + createdBroker, err := platformClient.CreateBroker(ctx, requestBroker) Expect(createdBroker).To(BeNil()) Expect(err).To(Equal(errors.New("Error from service-catalog"))) @@ -127,7 +129,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { Name: "fake-broker", } - err = platformClient.DeleteBroker(requestBroker) + err = platformClient.DeleteBroker(ctx, requestBroker) Expect(err).To(BeNil()) }) @@ -144,7 +146,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { requestBroker := &platform.DeleteServiceBrokerRequest{} - err = platformClient.DeleteBroker(requestBroker) + err = platformClient.DeleteBroker(ctx, requestBroker) Expect(err).To(Equal(errors.New("Error deleting clusterservicebroker"))) }) @@ -173,7 +175,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { return brokers, nil } - brokers, err := platformClient.GetBrokers() + brokers, err := platformClient.GetBrokers(ctx) Expect(err).To(BeNil()) Expect(brokers).ToNot(BeNil()) @@ -194,7 +196,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { return brokers, nil } - brokers, err := platformClient.GetBrokers() + brokers, err := platformClient.GetBrokers(ctx) Expect(err).To(BeNil()) Expect(brokers).ToNot(BeNil()) @@ -211,7 +213,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { return nil, errors.New("Error getting clusterservicebrokers") } - brokers, err := platformClient.GetBrokers() + brokers, err := platformClient.GetBrokers(ctx) Expect(brokers).To(BeNil()) Expect(err).To(Equal(errors.New("Error getting clusterservicebrokers"))) @@ -247,7 +249,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { BrokerURL: "http://fake.broker.url", } - broker, err := platformClient.UpdateBroker(requestBroker) + broker, err := platformClient.UpdateBroker(ctx, requestBroker) Expect(err).To(BeNil()) Expect(broker.GUID).To(Equal("1234")) @@ -267,7 +269,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { requestBroker := &platform.UpdateServiceBrokerRequest{} - broker, err := platformClient.UpdateBroker(requestBroker) + broker, err := platformClient.UpdateBroker(ctx, requestBroker) Expect(broker).To(BeNil()) Expect(err).To(Equal(errors.New("Error updating clusterservicebroker"))) @@ -291,7 +293,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { return nil } - err = platformClient.Fetch(requestBroker) + err = platformClient.Fetch(ctx, requestBroker) Expect(err).To(BeNil()) }) @@ -307,7 +309,7 @@ var _ = Describe("Kubernetes Broker Proxy", func() { return errors.New("Error syncing service broker") } - err = platformClient.Fetch(requestBroker) + err = platformClient.Fetch(ctx, requestBroker) Expect(err).To(Equal(errors.New("Error syncing service broker"))) }) diff --git a/vendor/github.com/Peripli/service-broker-proxy/Gopkg.lock b/vendor/github.com/Peripli/service-broker-proxy/Gopkg.lock index b84f9f8d..a745ef08 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/Gopkg.lock +++ b/vendor/github.com/Peripli/service-broker-proxy/Gopkg.lock @@ -3,6 +3,7 @@ [[projects]] branch = "master" + digest = "1:6ec6d0750c43e57130fae9f09c997494efbd66e3c0d2c404eb012c112059a543" name = "github.com/Peripli/service-manager" packages = [ "api", @@ -19,32 +20,41 @@ "pkg/server", "pkg/types", "pkg/util", + "pkg/util/slice", "pkg/web", "security", "security/basic", "security/oidc", - "storage" + "storage", ] - revision = "c48beef856f9f591d5724698daf786a5d5b4bb1f" + pruneopts = "NT" + revision = "f9027b31347dd7bec45a5239544a647295383192" [[projects]] + digest = "1:f6e5e1bc64c2908167e6aa9a1fe0c084d515132a1c63ad5b6c84036aa06dc0c1" name = "github.com/coreos/go-oidc" packages = ["."] + pruneopts = "UT" revision = "1180514eaf4d9f38d0d19eef639a1d695e066e72" [[projects]] + digest = "1:ca82a3b99694824c627573c2a76d0e49719b4a9c02d1d85a2ac91f1c1f52ab9b" name = "github.com/fatih/structs" packages = ["."] + pruneopts = "UT" revision = "a720dfa8df582c51dee1b36feabb906bde1588bd" version = "v1.0" [[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "github.com/fsnotify/fsnotify" packages = ["."] + pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" version = "v1.4.7" [[projects]] + digest = "1:9ae31ce33b4bab257668963e844d98765b44160be4ee98cafc44637a213e530d" name = "github.com/gobwas/glob" packages = [ ".", @@ -54,43 +64,54 @@ "syntax/ast", "syntax/lexer", "util/runes", - "util/strings" + "util/strings", ] + pruneopts = "UT" revision = "5ccd90ef52e1e632236f7326478d4faa74f99438" version = "v0.2.3" +[[projects]] + digest = "1:26f2ad8a198a88c3605401186a6be538326e7fbf1f14cb3ef4e0027c4f755f2a" + name = "github.com/gofrs/uuid" + packages = ["."] + pruneopts = "UT" + revision = "d41eeda0759468834c84365a32d1b1ec4264c75f" + version = "v3.1.0" + [[projects]] branch = "master" + digest = "1:1ba1d79f2810270045c328ae5d674321db34e3aae468eb4233883b473c5c0467" name = "github.com/golang/glog" packages = ["."] + pruneopts = "UT" revision = "23def4e6c14b4da8ac2ed8007337bc5eb5007998" [[projects]] + digest = "1:97df918963298c287643883209a2c3f642e6593379f97ab400c2a2e219ab647d" name = "github.com/golang/protobuf" packages = ["proto"] + pruneopts = "UT" revision = "aa810b61a9c79d51363740d207bb46cf8e620ed5" version = "v1.2.0" [[projects]] + digest = "1:c79fb010be38a59d657c48c6ba1d003a8aa651fa56b579d959d74573b7dff8e1" name = "github.com/gorilla/context" packages = ["."] + pruneopts = "UT" revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" [[projects]] - name = "github.com/gorilla/handlers" - packages = ["."] - revision = "90663712d74cb411cbef281bc1e08c19d1a76145" - version = "v1.3.0" - -[[projects]] + digest = "1:88aa9e326e2bd6045a46e00a922954b3e1a9ac5787109f49ac85366df370e1e5" name = "github.com/gorilla/mux" packages = ["."] + pruneopts = "UT" revision = "53c1911da2b537f792e7cafcb446b05ffe33b996" version = "v1.6.1" [[projects]] - branch = "master" + digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -102,44 +123,52 @@ "hcl/token", "json/parser", "json/scanner", - "json/token" + "json/token", ] - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + pruneopts = "UT" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" [[projects]] + digest = "1:a1038ef593beb4771c8f0f9c26e8b00410acd800af5c6864651d9bf160ea1813" name = "github.com/hpcloud/tail" packages = [ ".", "ratelimiter", "util", "watch", - "winfile" + "winfile", ] + pruneopts = "UT" revision = "a30252cb686a21eb2d0b98132633053ec2f7f1e5" version = "v1.0.0" [[projects]] + digest = "1:c568d7727aa262c32bdf8a3f7db83614f7af0ed661474b24588de635c20024c7" name = "github.com/magiconair/properties" packages = ["."] + pruneopts = "UT" revision = "c2353362d570a7bfa228149c62842019201cfb71" version = "v1.8.0" [[projects]] - branch = "master" + digest = "1:645110e089152bd0f4a011a2648fbb0e4df5977be73ca605781157ac297f50c4" name = "github.com/mitchellh/mapstructure" packages = ["."] - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" + pruneopts = "UT" + revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8" + version = "v1.0.0" [[projects]] branch = "master" + digest = "1:4323c6f79178c6f811a0528b1b2eba03bad0cae33605636f1e38c8f907b5cbf7" name = "github.com/onrik/logrus" - packages = [ - "filename", - "formatter" - ] + packages = ["filename"] + pruneopts = "UT" revision = "ca0a758702be2ae04725ba88dcd27a71949faf33" [[projects]] + digest = "1:f37a92358921891d53d5375ff7fa57739ba65d5b3c311d96a460609bfc1b4999" name = "github.com/onsi/ginkgo" packages = [ ".", @@ -160,12 +189,14 @@ "reporters/stenographer", "reporters/stenographer/support/go-colorable", "reporters/stenographer/support/go-isatty", - "types" + "types", ] + pruneopts = "UT" revision = "3774a09d95489ccaa16032e0770d08ea77ba6184" version = "v1.6.0" [[projects]] + digest = "1:038734db8a70cdd73d4215081b22236e2aed3e65ca0727f6afd0ed839630e738" name = "github.com/onsi/gomega" packages = [ ".", @@ -179,130 +210,157 @@ "matchers/support/goraph/edge", "matchers/support/goraph/node", "matchers/support/goraph/util", - "types" + "types", ] + pruneopts = "UT" revision = "003f63b7f4cff3fc95357005358af2de0f5fe152" version = "v1.3.0" [[projects]] + digest = "1:95741de3af260a92cc5c7f3f3061e85273f5a81b5db20d4bd68da74bd521675e" name = "github.com/pelletier/go-toml" packages = ["."] + pruneopts = "UT" revision = "c01d1270ff3e442a8a57cddc1c92dc1138598194" version = "v1.2.0" [[projects]] + digest = "1:40e195917a951a8bf867cd05de2a46aaf1806c50cf92eebf4c16f78cd196f747" name = "github.com/pkg/errors" packages = ["."] + pruneopts = "UT" revision = "645ef00459ed84a119197bfb8d8205042c6df63d" version = "v0.8.0" [[projects]] + digest = "1:8658f775ba5edb37ede96d8ec9eaecdfe06bc4aef1776152070185e6513dc0cc" name = "github.com/pmorie/go-open-service-broker-client" packages = ["v2"] + pruneopts = "UT" revision = "dca737037ce636eb282e84e3a1c7479c9692e884" version = "0.0.10" [[projects]] branch = "master" + digest = "1:bd9efe4e0b0f768302a1e2f0c22458149278de533e521206e5ddc71848c269a0" name = "github.com/pquerna/cachecontrol" packages = [ ".", - "cacheobject" + "cacheobject", ] + pruneopts = "UT" revision = "1555304b9b35fdd2b425bccf1a5613677705e7d0" [[projects]] + branch = "master" + digest = "1:ed615c5430ecabbb0fb7629a182da65ecee6523900ac1ac932520860878ffcad" name = "github.com/robfig/cron" packages = ["."] + pruneopts = "UT" revision = "b41be1df696709bb6395fe435af20370037c0b4c" - version = "v1.1" - -[[projects]] - name = "github.com/satori/go.uuid" - packages = ["."] - revision = "36e9d2ebbde5e3f13ab2e25625fd453271d6522e" [[projects]] + digest = "1:5622116f2c79239f2d25d47b881e14f96a8b8c17b63b8a8326a38ee1a332b007" name = "github.com/sirupsen/logrus" packages = ["."] + pruneopts = "UT" revision = "d682213848ed68c0a260ca37d6dd5ace8423f5ba" version = "v1.0.4" [[projects]] + digest = "1:6a4a11ba764a56d2758899ec6f3848d24698d48442ebce85ee7a3f63284526cd" name = "github.com/spf13/afero" packages = [ ".", - "mem" + "mem", ] - revision = "787d034dfe70e44075ccc060d346146ef53270ad" - version = "v1.1.1" + pruneopts = "UT" + revision = "d40851caa0d747393da1ffb28f7f9d8b4eeffebd" + version = "v1.1.2" [[projects]] + digest = "1:516e71bed754268937f57d4ecb190e01958452336fa73dbac880894164e91c1f" name = "github.com/spf13/cast" packages = ["."] + pruneopts = "UT" revision = "8965335b8c7107321228e3e3702cab9832751bac" version = "v1.2.0" [[projects]] - branch = "master" + digest = "1:68ea4e23713989dc20b1bded5d9da2c5f9be14ff9885beef481848edd18c26cb" name = "github.com/spf13/jwalterweatherman" packages = ["."] - revision = "14d3d4c518341bea657dd8a226f5121c0ff8c9f2" + pruneopts = "UT" + revision = "4a4406e478ca629068e7768fc33f3f044173c0a6" + version = "v1.0.0" [[projects]] + digest = "1:9424f440bba8f7508b69414634aef3b2b3a877e522d8a4624692412805407bb7" name = "github.com/spf13/pflag" packages = ["."] + pruneopts = "UT" revision = "583c0c0531f06d5278b7d917446061adc344b5cd" version = "v1.0.1" [[projects]] + digest = "1:59e7dceb53b4a1e57eb1eb0bf9951ff0c25912df7660004a789b62b4e8cdca3b" name = "github.com/spf13/viper" packages = ["."] + pruneopts = "UT" revision = "b5e8006cbee93ec955a89ab31e0e3ce3204f3736" version = "v1.0.2" [[projects]] branch = "master" + digest = "1:8e241498e35f550e5192ee6b1f6ff2c0a7ffe81feff9541d297facffe1383979" name = "golang.org/x/crypto" packages = [ "ed25519", "ed25519/internal/edwards25519", "pbkdf2", - "ssh/terminal" + "ssh/terminal", ] - revision = "614d502a4dac94afa3a6ce146bd1736da82514c6" + pruneopts = "UT" + revision = "0e37d006457bf46f9e6692014ba72ef82c33022c" [[projects]] branch = "master" + digest = "1:776f93ea20a9ade276a67d5d201696461695b47811d28678aac8b686f7e86bed" name = "golang.org/x/net" packages = [ "context", "context/ctxhttp", "html", "html/atom", - "html/charset" + "html/charset", ] - revision = "922f4815f713f213882e8ef45e0d315b164d705c" + pruneopts = "UT" + revision = "161cd47e91fd58ac17490ef4d742dc98bb4cf60e" [[projects]] branch = "master" + digest = "1:363b547c971a2b07474c598b6e9ebcb238d556d8a27f37b3895ad20cd50e7281" name = "golang.org/x/oauth2" packages = [ ".", - "internal" + "internal", ] + pruneopts = "UT" revision = "d2e6202438beef2727060aa7cabdd924d92ebfd9" [[projects]] branch = "master" + digest = "1:374fc90fcb026e9a367e3fad29e988e5dd944b68ca3f24a184d77abc5307dda4" name = "golang.org/x/sys" packages = [ "unix", - "windows" + "windows", ] - revision = "3b58ed4ad3395d483fc92d5d14123ce2c3581fec" + pruneopts = "UT" + revision = "d0be0721c37eeb5299f245a996a483160fc36940" [[projects]] + digest = "1:4392fcf42d5cf0e3ff78c96b2acf8223d49e4fdc53eb77c99d2f8dfe4680e006" name = "golang.org/x/text" packages = [ "encoding", @@ -324,12 +382,14 @@ "runes", "transform", "unicode/cldr", - "unicode/norm" + "unicode/norm", ] + pruneopts = "UT" revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" version = "v0.3.0" [[projects]] + digest = "1:328b5e4f197d928c444a51a75385f4b978915c0e75521f0ad6a3db976c97a7d3" name = "google.golang.org/appengine" packages = [ "internal", @@ -338,43 +398,69 @@ "internal/log", "internal/remote_api", "internal/urlfetch", - "urlfetch" + "urlfetch", ] + pruneopts = "UT" revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" version = "v1.1.0" [[projects]] + digest = "1:abeb38ade3f32a92943e5be54f55ed6d6e3b6602761d74b4aab4c9dd45c18abd" name = "gopkg.in/fsnotify.v1" packages = ["."] + pruneopts = "UT" revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9" source = "https://github.com/fsnotify/fsnotify.git" version = "v1.4.7" [[projects]] + digest = "1:02d2c5be9a35ce750536e74af0d98aca806f225913a3ab28f285843d6283c70d" name = "gopkg.in/square/go-jose.v2" packages = [ ".", "cipher", - "json" + "json", ] + pruneopts = "UT" revision = "8254d6c783765f38c8675fae4427a1fe73fbd09d" version = "v2.1.8" [[projects]] branch = "v1" + digest = "1:0caa92e17bc0b65a98c63e5bc76a9e844cd5e56493f8fdbb28fad101a16254d9" name = "gopkg.in/tomb.v1" packages = ["."] + pruneopts = "UT" revision = "dd632973f1e7218eb1089048e0798ec9ae7dceb8" [[projects]] + digest = "1:342378ac4dcb378a5448dd723f0784ae519383532f5e70ade24132c4c8693202" name = "gopkg.in/yaml.v2" packages = ["."] + pruneopts = "UT" revision = "5420a8b6744d3b0345ab293f6fcba19c978f1183" version = "v2.2.1" [solve-meta] analyzer-name = "dep" analyzer-version = 1 - inputs-digest = "a10976151af6c7d11483e96c7a82bd3049fb42c4a3d047d0e287b4cf3ec5d0a8" + input-imports = [ + "github.com/Peripli/service-manager/api/filters", + "github.com/Peripli/service-manager/api/osb", + "github.com/Peripli/service-manager/pkg/env", + "github.com/Peripli/service-manager/pkg/log", + "github.com/Peripli/service-manager/pkg/server", + "github.com/Peripli/service-manager/pkg/types", + "github.com/Peripli/service-manager/pkg/util", + "github.com/Peripli/service-manager/pkg/web", + "github.com/onsi/ginkgo", + "github.com/onsi/ginkgo/extensions/table", + "github.com/onsi/gomega", + "github.com/pkg/errors", + "github.com/pmorie/go-open-service-broker-client/v2", + "github.com/robfig/cron", + "github.com/sirupsen/logrus", + "github.com/spf13/pflag", + ] solver-name = "gps-cdcl" solver-version = 1 diff --git a/vendor/github.com/Peripli/service-broker-proxy/Gopkg.toml b/vendor/github.com/Peripli/service-broker-proxy/Gopkg.toml index ca32d366..4edf33a2 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/Gopkg.toml +++ b/vendor/github.com/Peripli/service-broker-proxy/Gopkg.toml @@ -21,10 +21,6 @@ name = "github.com/sirupsen/logrus" version = "=1.0.4" -[[constraint]] - name = "github.com/onrik/logrus" - branch = "master" - [[constraint]] name = "github.com/onsi/ginkgo" version = "1.4.0" diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/logging/logging.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/logging/logging.go deleted file mode 100644 index 2763a5cb..00000000 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/logging/logging.go +++ /dev/null @@ -1,34 +0,0 @@ -package logging - -import ( - "github.com/onrik/logrus/filename" - "github.com/onrik/logrus/formatter" - "github.com/sirupsen/logrus" - "github.com/Peripli/service-manager/pkg/log" -) - -const ( - keyLogSource = "logSource" - logFormatJSON = "json" -) - -// Setup sets up the logrus logging for the proxy based on the provided parameters. -func Setup(settings *log.Settings) { - logrus.AddHook(&ErrorLocationHook{}) - hook := filename.NewHook() - hook.Field = keyLogSource - logrus.AddHook(hook) - level, err := logrus.ParseLevel(settings.Level) - if err != nil { - logrus.SetLevel(logrus.DebugLevel) - logrus.WithError(err).Error("Could not parse log level configuration") - } else { - logrus.SetLevel(level) - } - if settings.Format == logFormatJSON { - logrus.SetFormatter(&logrus.JSONFormatter{}) - } else { - textFormatter := formatter.New() - logrus.SetFormatter(textFormatter) - } -} diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/middleware/basic_auth.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/middleware/basic_auth.go index 05869f99..33110be5 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/middleware/basic_auth.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/middleware/basic_auth.go @@ -1,10 +1,10 @@ package middleware import ( + "github.com/Peripli/service-manager/pkg/log" "net/http" "github.com/Peripli/service-manager/pkg/util" - "github.com/sirupsen/logrus" ) const ( @@ -17,14 +17,15 @@ func BasicAuth(username, password string) func(handler http.Handler) http.Handle return func(handler http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !authorized(r, username, password) { - logrus.WithField("username", username).Debug(errorMessage) + logger := log.C(r.Context()) + logger.WithField("username", username).Debug(errorMessage) err := util.WriteJSON(w, http.StatusUnauthorized, &util.HTTPError{ ErrorType: notAuthorized, Description: errorMessage, StatusCode: http.StatusUnauthorized, }) if err != nil { - logrus.Error(err) + logger.Error(err) } return } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/osb/transport.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/osb/transport.go index f8f98a3b..46b1bfe4 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/osb/transport.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/osb/transport.go @@ -1,9 +1,10 @@ package osb import ( - "net/http" + "context" "github.com/Peripli/service-manager/api/osb" "github.com/Peripli/service-manager/pkg/types" + "net/http" ) // BrokerTransport implements osb.BrokerRoundTripper @@ -18,7 +19,7 @@ type BrokerTransport struct { var _ osb.BrokerRoundTripper = &BrokerTransport{} // Broker implements osb.BrokerRoundTripper and returns the coordinates of the broker with the specified id -func (b *BrokerTransport) Broker(brokerID string) (*types.Broker, error) { +func (b *BrokerTransport) Broker(ctx context.Context, brokerID string) (*types.Broker, error) { return &types.Broker{ BrokerURL: b.URL + "/" + brokerID, Credentials: &types.Credentials{ diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/catalog_fetcher.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/catalog_fetcher.go index 191cb886..be3ca447 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/catalog_fetcher.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/catalog_fetcher.go @@ -1,5 +1,7 @@ package platform +import "context" + // CatalogFetcher provides a way to add a hook for platform specific way of refetching the service broker catalog on each // run of the registration task. If the platform that this proxy represents already handles that, you don't // have to implement this interface @@ -7,5 +9,5 @@ package platform type CatalogFetcher interface { // Fetch contains the logic for platform specific catalog fetching for the provided service broker - Fetch(serviceBroker *ServiceBroker) error + Fetch(ctx context.Context, serviceBroker *ServiceBroker) error } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/client.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/client.go index a41c096e..c3ce932d 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/client.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/client.go @@ -1,17 +1,19 @@ package platform +import "context" + // Client provides the logic for calling into the underlying platform and performing platform specific operations //go:generate counterfeiter . Client type Client interface { // GetBrokers obtains the registered brokers in the platform - GetBrokers() ([]ServiceBroker, error) + GetBrokers(ctx context.Context) ([]ServiceBroker, error) // CreateBroker registers a new broker at the platform - CreateBroker(r *CreateServiceBrokerRequest) (*ServiceBroker, error) + CreateBroker(ctx context.Context, r *CreateServiceBrokerRequest) (*ServiceBroker, error) // DeleteBroker unregisters a broker from the platform - DeleteBroker(r *DeleteServiceBrokerRequest) error + DeleteBroker(ctx context.Context, r *DeleteServiceBrokerRequest) error // UpdateBroker updates a broker registration at the platform - UpdateBroker(r *UpdateServiceBrokerRequest) (*ServiceBroker, error) + UpdateBroker(ctx context.Context, r *UpdateServiceBrokerRequest) (*ServiceBroker, error) } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_catalog_fetcher.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_catalog_fetcher.go index b588f424..75be6ba8 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_catalog_fetcher.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_catalog_fetcher.go @@ -2,15 +2,17 @@ package platformfakes import ( + "context" "sync" "github.com/Peripli/service-broker-proxy/pkg/platform" ) type FakeCatalogFetcher struct { - FetchStub func(serviceBroker *platform.ServiceBroker) error + FetchStub func(ctx context.Context, serviceBroker *platform.ServiceBroker) error fetchMutex sync.RWMutex fetchArgsForCall []struct { + ctx context.Context serviceBroker *platform.ServiceBroker } fetchReturns struct { @@ -23,16 +25,17 @@ type FakeCatalogFetcher struct { invocationsMutex sync.RWMutex } -func (fake *FakeCatalogFetcher) Fetch(serviceBroker *platform.ServiceBroker) error { +func (fake *FakeCatalogFetcher) Fetch(ctx context.Context, serviceBroker *platform.ServiceBroker) error { fake.fetchMutex.Lock() ret, specificReturn := fake.fetchReturnsOnCall[len(fake.fetchArgsForCall)] fake.fetchArgsForCall = append(fake.fetchArgsForCall, struct { + ctx context.Context serviceBroker *platform.ServiceBroker - }{serviceBroker}) - fake.recordInvocation("Fetch", []interface{}{serviceBroker}) + }{ctx, serviceBroker}) + fake.recordInvocation("Fetch", []interface{}{ctx, serviceBroker}) fake.fetchMutex.Unlock() if fake.FetchStub != nil { - return fake.FetchStub(serviceBroker) + return fake.FetchStub(ctx, serviceBroker) } if specificReturn { return ret.result1 @@ -46,10 +49,10 @@ func (fake *FakeCatalogFetcher) FetchCallCount() int { return len(fake.fetchArgsForCall) } -func (fake *FakeCatalogFetcher) FetchArgsForCall(i int) *platform.ServiceBroker { +func (fake *FakeCatalogFetcher) FetchArgsForCall(i int) (context.Context, *platform.ServiceBroker) { fake.fetchMutex.RLock() defer fake.fetchMutex.RUnlock() - return fake.fetchArgsForCall[i].serviceBroker + return fake.fetchArgsForCall[i].ctx, fake.fetchArgsForCall[i].serviceBroker } func (fake *FakeCatalogFetcher) FetchReturns(result1 error) { diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_client.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_client.go index d4fbf945..fda3859f 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_client.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_client.go @@ -2,16 +2,19 @@ package platformfakes import ( + "context" "sync" "github.com/Peripli/service-broker-proxy/pkg/platform" ) type FakeClient struct { - GetBrokersStub func() ([]platform.ServiceBroker, error) + GetBrokersStub func(ctx context.Context) ([]platform.ServiceBroker, error) getBrokersMutex sync.RWMutex - getBrokersArgsForCall []struct{} - getBrokersReturns struct { + getBrokersArgsForCall []struct { + ctx context.Context + } + getBrokersReturns struct { result1 []platform.ServiceBroker result2 error } @@ -19,10 +22,11 @@ type FakeClient struct { result1 []platform.ServiceBroker result2 error } - CreateBrokerStub func(r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) + CreateBrokerStub func(ctx context.Context, r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) createBrokerMutex sync.RWMutex createBrokerArgsForCall []struct { - r *platform.CreateServiceBrokerRequest + ctx context.Context + r *platform.CreateServiceBrokerRequest } createBrokerReturns struct { result1 *platform.ServiceBroker @@ -32,10 +36,11 @@ type FakeClient struct { result1 *platform.ServiceBroker result2 error } - DeleteBrokerStub func(r *platform.DeleteServiceBrokerRequest) error + DeleteBrokerStub func(ctx context.Context, r *platform.DeleteServiceBrokerRequest) error deleteBrokerMutex sync.RWMutex deleteBrokerArgsForCall []struct { - r *platform.DeleteServiceBrokerRequest + ctx context.Context + r *platform.DeleteServiceBrokerRequest } deleteBrokerReturns struct { result1 error @@ -43,10 +48,11 @@ type FakeClient struct { deleteBrokerReturnsOnCall map[int]struct { result1 error } - UpdateBrokerStub func(r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) + UpdateBrokerStub func(ctx context.Context, r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) updateBrokerMutex sync.RWMutex updateBrokerArgsForCall []struct { - r *platform.UpdateServiceBrokerRequest + ctx context.Context + r *platform.UpdateServiceBrokerRequest } updateBrokerReturns struct { result1 *platform.ServiceBroker @@ -60,14 +66,16 @@ type FakeClient struct { invocationsMutex sync.RWMutex } -func (fake *FakeClient) GetBrokers() ([]platform.ServiceBroker, error) { +func (fake *FakeClient) GetBrokers(ctx context.Context) ([]platform.ServiceBroker, error) { fake.getBrokersMutex.Lock() ret, specificReturn := fake.getBrokersReturnsOnCall[len(fake.getBrokersArgsForCall)] - fake.getBrokersArgsForCall = append(fake.getBrokersArgsForCall, struct{}{}) - fake.recordInvocation("GetBrokers", []interface{}{}) + fake.getBrokersArgsForCall = append(fake.getBrokersArgsForCall, struct { + ctx context.Context + }{ctx}) + fake.recordInvocation("GetBrokers", []interface{}{ctx}) fake.getBrokersMutex.Unlock() if fake.GetBrokersStub != nil { - return fake.GetBrokersStub() + return fake.GetBrokersStub(ctx) } if specificReturn { return ret.result1, ret.result2 @@ -81,6 +89,12 @@ func (fake *FakeClient) GetBrokersCallCount() int { return len(fake.getBrokersArgsForCall) } +func (fake *FakeClient) GetBrokersArgsForCall(i int) context.Context { + fake.getBrokersMutex.RLock() + defer fake.getBrokersMutex.RUnlock() + return fake.getBrokersArgsForCall[i].ctx +} + func (fake *FakeClient) GetBrokersReturns(result1 []platform.ServiceBroker, result2 error) { fake.GetBrokersStub = nil fake.getBrokersReturns = struct { @@ -103,16 +117,17 @@ func (fake *FakeClient) GetBrokersReturnsOnCall(i int, result1 []platform.Servic }{result1, result2} } -func (fake *FakeClient) CreateBroker(r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) { +func (fake *FakeClient) CreateBroker(ctx context.Context, r *platform.CreateServiceBrokerRequest) (*platform.ServiceBroker, error) { fake.createBrokerMutex.Lock() ret, specificReturn := fake.createBrokerReturnsOnCall[len(fake.createBrokerArgsForCall)] fake.createBrokerArgsForCall = append(fake.createBrokerArgsForCall, struct { - r *platform.CreateServiceBrokerRequest - }{r}) - fake.recordInvocation("CreateBroker", []interface{}{r}) + ctx context.Context + r *platform.CreateServiceBrokerRequest + }{ctx, r}) + fake.recordInvocation("CreateBroker", []interface{}{ctx, r}) fake.createBrokerMutex.Unlock() if fake.CreateBrokerStub != nil { - return fake.CreateBrokerStub(r) + return fake.CreateBrokerStub(ctx, r) } if specificReturn { return ret.result1, ret.result2 @@ -126,10 +141,10 @@ func (fake *FakeClient) CreateBrokerCallCount() int { return len(fake.createBrokerArgsForCall) } -func (fake *FakeClient) CreateBrokerArgsForCall(i int) *platform.CreateServiceBrokerRequest { +func (fake *FakeClient) CreateBrokerArgsForCall(i int) (context.Context, *platform.CreateServiceBrokerRequest) { fake.createBrokerMutex.RLock() defer fake.createBrokerMutex.RUnlock() - return fake.createBrokerArgsForCall[i].r + return fake.createBrokerArgsForCall[i].ctx, fake.createBrokerArgsForCall[i].r } func (fake *FakeClient) CreateBrokerReturns(result1 *platform.ServiceBroker, result2 error) { @@ -154,16 +169,17 @@ func (fake *FakeClient) CreateBrokerReturnsOnCall(i int, result1 *platform.Servi }{result1, result2} } -func (fake *FakeClient) DeleteBroker(r *platform.DeleteServiceBrokerRequest) error { +func (fake *FakeClient) DeleteBroker(ctx context.Context, r *platform.DeleteServiceBrokerRequest) error { fake.deleteBrokerMutex.Lock() ret, specificReturn := fake.deleteBrokerReturnsOnCall[len(fake.deleteBrokerArgsForCall)] fake.deleteBrokerArgsForCall = append(fake.deleteBrokerArgsForCall, struct { - r *platform.DeleteServiceBrokerRequest - }{r}) - fake.recordInvocation("DeleteBroker", []interface{}{r}) + ctx context.Context + r *platform.DeleteServiceBrokerRequest + }{ctx, r}) + fake.recordInvocation("DeleteBroker", []interface{}{ctx, r}) fake.deleteBrokerMutex.Unlock() if fake.DeleteBrokerStub != nil { - return fake.DeleteBrokerStub(r) + return fake.DeleteBrokerStub(ctx, r) } if specificReturn { return ret.result1 @@ -177,10 +193,10 @@ func (fake *FakeClient) DeleteBrokerCallCount() int { return len(fake.deleteBrokerArgsForCall) } -func (fake *FakeClient) DeleteBrokerArgsForCall(i int) *platform.DeleteServiceBrokerRequest { +func (fake *FakeClient) DeleteBrokerArgsForCall(i int) (context.Context, *platform.DeleteServiceBrokerRequest) { fake.deleteBrokerMutex.RLock() defer fake.deleteBrokerMutex.RUnlock() - return fake.deleteBrokerArgsForCall[i].r + return fake.deleteBrokerArgsForCall[i].ctx, fake.deleteBrokerArgsForCall[i].r } func (fake *FakeClient) DeleteBrokerReturns(result1 error) { @@ -202,16 +218,17 @@ func (fake *FakeClient) DeleteBrokerReturnsOnCall(i int, result1 error) { }{result1} } -func (fake *FakeClient) UpdateBroker(r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) { +func (fake *FakeClient) UpdateBroker(ctx context.Context, r *platform.UpdateServiceBrokerRequest) (*platform.ServiceBroker, error) { fake.updateBrokerMutex.Lock() ret, specificReturn := fake.updateBrokerReturnsOnCall[len(fake.updateBrokerArgsForCall)] fake.updateBrokerArgsForCall = append(fake.updateBrokerArgsForCall, struct { - r *platform.UpdateServiceBrokerRequest - }{r}) - fake.recordInvocation("UpdateBroker", []interface{}{r}) + ctx context.Context + r *platform.UpdateServiceBrokerRequest + }{ctx, r}) + fake.recordInvocation("UpdateBroker", []interface{}{ctx, r}) fake.updateBrokerMutex.Unlock() if fake.UpdateBrokerStub != nil { - return fake.UpdateBrokerStub(r) + return fake.UpdateBrokerStub(ctx, r) } if specificReturn { return ret.result1, ret.result2 @@ -225,10 +242,10 @@ func (fake *FakeClient) UpdateBrokerCallCount() int { return len(fake.updateBrokerArgsForCall) } -func (fake *FakeClient) UpdateBrokerArgsForCall(i int) *platform.UpdateServiceBrokerRequest { +func (fake *FakeClient) UpdateBrokerArgsForCall(i int) (context.Context, *platform.UpdateServiceBrokerRequest) { fake.updateBrokerMutex.RLock() defer fake.updateBrokerMutex.RUnlock() - return fake.updateBrokerArgsForCall[i].r + return fake.updateBrokerArgsForCall[i].ctx, fake.updateBrokerArgsForCall[i].r } func (fake *FakeClient) UpdateBrokerReturns(result1 *platform.ServiceBroker, result2 error) { diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_service_access.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_service_access.go index 7d827930..1873980d 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_service_access.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/platformfakes/fake_service_access.go @@ -2,6 +2,7 @@ package platformfakes import ( + "context" "encoding/json" "sync" @@ -9,10 +10,11 @@ import ( ) type FakeServiceAccess struct { - EnableAccessForServiceStub func(context json.RawMessage, serviceGUID string) error + EnableAccessForServiceStub func(ctx context.Context, data json.RawMessage, serviceGUID string) error enableAccessForServiceMutex sync.RWMutex enableAccessForServiceArgsForCall []struct { - context json.RawMessage + ctx context.Context + data json.RawMessage serviceGUID string } enableAccessForServiceReturns struct { @@ -21,10 +23,11 @@ type FakeServiceAccess struct { enableAccessForServiceReturnsOnCall map[int]struct { result1 error } - EnableAccessForPlanStub func(context json.RawMessage, servicePlanGUID string) error + EnableAccessForPlanStub func(ctx context.Context, data json.RawMessage, servicePlanGUID string) error enableAccessForPlanMutex sync.RWMutex enableAccessForPlanArgsForCall []struct { - context json.RawMessage + ctx context.Context + data json.RawMessage servicePlanGUID string } enableAccessForPlanReturns struct { @@ -33,10 +36,11 @@ type FakeServiceAccess struct { enableAccessForPlanReturnsOnCall map[int]struct { result1 error } - DisableAccessForServiceStub func(context json.RawMessage, serviceGUID string) error + DisableAccessForServiceStub func(ctx context.Context, data json.RawMessage, serviceGUID string) error disableAccessForServiceMutex sync.RWMutex disableAccessForServiceArgsForCall []struct { - context json.RawMessage + ctx context.Context + data json.RawMessage serviceGUID string } disableAccessForServiceReturns struct { @@ -45,10 +49,11 @@ type FakeServiceAccess struct { disableAccessForServiceReturnsOnCall map[int]struct { result1 error } - DisableAccessForPlanStub func(context json.RawMessage, servicePlanGUID string) error + DisableAccessForPlanStub func(ctx context.Context, data json.RawMessage, servicePlanGUID string) error disableAccessForPlanMutex sync.RWMutex disableAccessForPlanArgsForCall []struct { - context json.RawMessage + ctx context.Context + data json.RawMessage servicePlanGUID string } disableAccessForPlanReturns struct { @@ -61,17 +66,18 @@ type FakeServiceAccess struct { invocationsMutex sync.RWMutex } -func (fake *FakeServiceAccess) EnableAccessForService(context json.RawMessage, serviceGUID string) error { +func (fake *FakeServiceAccess) EnableAccessForService(ctx context.Context, data json.RawMessage, serviceGUID string) error { fake.enableAccessForServiceMutex.Lock() ret, specificReturn := fake.enableAccessForServiceReturnsOnCall[len(fake.enableAccessForServiceArgsForCall)] fake.enableAccessForServiceArgsForCall = append(fake.enableAccessForServiceArgsForCall, struct { - context json.RawMessage + ctx context.Context + data json.RawMessage serviceGUID string - }{context, serviceGUID}) - fake.recordInvocation("EnableAccessForService", []interface{}{context, serviceGUID}) + }{ctx, data, serviceGUID}) + fake.recordInvocation("EnableAccessForService", []interface{}{ctx, data, serviceGUID}) fake.enableAccessForServiceMutex.Unlock() if fake.EnableAccessForServiceStub != nil { - return fake.EnableAccessForServiceStub(context, serviceGUID) + return fake.EnableAccessForServiceStub(ctx, data, serviceGUID) } if specificReturn { return ret.result1 @@ -85,10 +91,10 @@ func (fake *FakeServiceAccess) EnableAccessForServiceCallCount() int { return len(fake.enableAccessForServiceArgsForCall) } -func (fake *FakeServiceAccess) EnableAccessForServiceArgsForCall(i int) (json.RawMessage, string) { +func (fake *FakeServiceAccess) EnableAccessForServiceArgsForCall(i int) (context.Context, json.RawMessage, string) { fake.enableAccessForServiceMutex.RLock() defer fake.enableAccessForServiceMutex.RUnlock() - return fake.enableAccessForServiceArgsForCall[i].context, fake.enableAccessForServiceArgsForCall[i].serviceGUID + return fake.enableAccessForServiceArgsForCall[i].ctx, fake.enableAccessForServiceArgsForCall[i].data, fake.enableAccessForServiceArgsForCall[i].serviceGUID } func (fake *FakeServiceAccess) EnableAccessForServiceReturns(result1 error) { @@ -110,17 +116,18 @@ func (fake *FakeServiceAccess) EnableAccessForServiceReturnsOnCall(i int, result }{result1} } -func (fake *FakeServiceAccess) EnableAccessForPlan(context json.RawMessage, servicePlanGUID string) error { +func (fake *FakeServiceAccess) EnableAccessForPlan(ctx context.Context, data json.RawMessage, servicePlanGUID string) error { fake.enableAccessForPlanMutex.Lock() ret, specificReturn := fake.enableAccessForPlanReturnsOnCall[len(fake.enableAccessForPlanArgsForCall)] fake.enableAccessForPlanArgsForCall = append(fake.enableAccessForPlanArgsForCall, struct { - context json.RawMessage + ctx context.Context + data json.RawMessage servicePlanGUID string - }{context, servicePlanGUID}) - fake.recordInvocation("EnableAccessForPlan", []interface{}{context, servicePlanGUID}) + }{ctx, data, servicePlanGUID}) + fake.recordInvocation("EnableAccessForPlan", []interface{}{ctx, data, servicePlanGUID}) fake.enableAccessForPlanMutex.Unlock() if fake.EnableAccessForPlanStub != nil { - return fake.EnableAccessForPlanStub(context, servicePlanGUID) + return fake.EnableAccessForPlanStub(ctx, data, servicePlanGUID) } if specificReturn { return ret.result1 @@ -134,10 +141,10 @@ func (fake *FakeServiceAccess) EnableAccessForPlanCallCount() int { return len(fake.enableAccessForPlanArgsForCall) } -func (fake *FakeServiceAccess) EnableAccessForPlanArgsForCall(i int) (json.RawMessage, string) { +func (fake *FakeServiceAccess) EnableAccessForPlanArgsForCall(i int) (context.Context, json.RawMessage, string) { fake.enableAccessForPlanMutex.RLock() defer fake.enableAccessForPlanMutex.RUnlock() - return fake.enableAccessForPlanArgsForCall[i].context, fake.enableAccessForPlanArgsForCall[i].servicePlanGUID + return fake.enableAccessForPlanArgsForCall[i].ctx, fake.enableAccessForPlanArgsForCall[i].data, fake.enableAccessForPlanArgsForCall[i].servicePlanGUID } func (fake *FakeServiceAccess) EnableAccessForPlanReturns(result1 error) { @@ -159,17 +166,18 @@ func (fake *FakeServiceAccess) EnableAccessForPlanReturnsOnCall(i int, result1 e }{result1} } -func (fake *FakeServiceAccess) DisableAccessForService(context json.RawMessage, serviceGUID string) error { +func (fake *FakeServiceAccess) DisableAccessForService(ctx context.Context, data json.RawMessage, serviceGUID string) error { fake.disableAccessForServiceMutex.Lock() ret, specificReturn := fake.disableAccessForServiceReturnsOnCall[len(fake.disableAccessForServiceArgsForCall)] fake.disableAccessForServiceArgsForCall = append(fake.disableAccessForServiceArgsForCall, struct { - context json.RawMessage + ctx context.Context + data json.RawMessage serviceGUID string - }{context, serviceGUID}) - fake.recordInvocation("DisableAccessForService", []interface{}{context, serviceGUID}) + }{ctx, data, serviceGUID}) + fake.recordInvocation("DisableAccessForService", []interface{}{ctx, data, serviceGUID}) fake.disableAccessForServiceMutex.Unlock() if fake.DisableAccessForServiceStub != nil { - return fake.DisableAccessForServiceStub(context, serviceGUID) + return fake.DisableAccessForServiceStub(ctx, data, serviceGUID) } if specificReturn { return ret.result1 @@ -183,10 +191,10 @@ func (fake *FakeServiceAccess) DisableAccessForServiceCallCount() int { return len(fake.disableAccessForServiceArgsForCall) } -func (fake *FakeServiceAccess) DisableAccessForServiceArgsForCall(i int) (json.RawMessage, string) { +func (fake *FakeServiceAccess) DisableAccessForServiceArgsForCall(i int) (context.Context, json.RawMessage, string) { fake.disableAccessForServiceMutex.RLock() defer fake.disableAccessForServiceMutex.RUnlock() - return fake.disableAccessForServiceArgsForCall[i].context, fake.disableAccessForServiceArgsForCall[i].serviceGUID + return fake.disableAccessForServiceArgsForCall[i].ctx, fake.disableAccessForServiceArgsForCall[i].data, fake.disableAccessForServiceArgsForCall[i].serviceGUID } func (fake *FakeServiceAccess) DisableAccessForServiceReturns(result1 error) { @@ -208,17 +216,18 @@ func (fake *FakeServiceAccess) DisableAccessForServiceReturnsOnCall(i int, resul }{result1} } -func (fake *FakeServiceAccess) DisableAccessForPlan(context json.RawMessage, servicePlanGUID string) error { +func (fake *FakeServiceAccess) DisableAccessForPlan(ctx context.Context, data json.RawMessage, servicePlanGUID string) error { fake.disableAccessForPlanMutex.Lock() ret, specificReturn := fake.disableAccessForPlanReturnsOnCall[len(fake.disableAccessForPlanArgsForCall)] fake.disableAccessForPlanArgsForCall = append(fake.disableAccessForPlanArgsForCall, struct { - context json.RawMessage + ctx context.Context + data json.RawMessage servicePlanGUID string - }{context, servicePlanGUID}) - fake.recordInvocation("DisableAccessForPlan", []interface{}{context, servicePlanGUID}) + }{ctx, data, servicePlanGUID}) + fake.recordInvocation("DisableAccessForPlan", []interface{}{ctx, data, servicePlanGUID}) fake.disableAccessForPlanMutex.Unlock() if fake.DisableAccessForPlanStub != nil { - return fake.DisableAccessForPlanStub(context, servicePlanGUID) + return fake.DisableAccessForPlanStub(ctx, data, servicePlanGUID) } if specificReturn { return ret.result1 @@ -232,10 +241,10 @@ func (fake *FakeServiceAccess) DisableAccessForPlanCallCount() int { return len(fake.disableAccessForPlanArgsForCall) } -func (fake *FakeServiceAccess) DisableAccessForPlanArgsForCall(i int) (json.RawMessage, string) { +func (fake *FakeServiceAccess) DisableAccessForPlanArgsForCall(i int) (context.Context, json.RawMessage, string) { fake.disableAccessForPlanMutex.RLock() defer fake.disableAccessForPlanMutex.RUnlock() - return fake.disableAccessForPlanArgsForCall[i].context, fake.disableAccessForPlanArgsForCall[i].servicePlanGUID + return fake.disableAccessForPlanArgsForCall[i].ctx, fake.disableAccessForPlanArgsForCall[i].data, fake.disableAccessForPlanArgsForCall[i].servicePlanGUID } func (fake *FakeServiceAccess) DisableAccessForPlanReturns(result1 error) { diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/service_access.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/service_access.go index c4ef9035..c85fee2b 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/service_access.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/platform/service_access.go @@ -1,25 +1,27 @@ package platform -import "encoding/json" +import ( + "context" + "encoding/json" +) // ServiceAccess provides a way to add a hook for a platform specific way of enabling and disabling // service and plan access. //go:generate counterfeiter . ServiceAccess type ServiceAccess interface { - // EnableAccessForService enables the access to all plans of the service with the specified GUID - // for the entities in the context - EnableAccessForService(context json.RawMessage, serviceGUID string) error + // for the entities in the data + EnableAccessForService(ctx context.Context, data json.RawMessage, serviceGUID string) error // EnableAccessForPlan enables the access to the plan with the specified GUID for - // the entities in the context - EnableAccessForPlan(context json.RawMessage, servicePlanGUID string) error + // the entities in the data + EnableAccessForPlan(ctx context.Context, data json.RawMessage, servicePlanGUID string) error // DisableAccessForService disables the access to all plans of the service with the specified GUID - // for the entities in the context - DisableAccessForService(context json.RawMessage, serviceGUID string) error + // for the entities in the data + DisableAccessForService(ctx context.Context, data json.RawMessage, serviceGUID string) error // DisableAccessForPlan disables the access to the plan with the specified GUID for - // the entities in the context - DisableAccessForPlan(context json.RawMessage, servicePlanGUID string) error + // the entities in the data + DisableAccessForPlan(ctx context.Context, data json.RawMessage, servicePlanGUID string) error } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/reconcile_brokers.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/reconcile_brokers.go index d179e5e1..15cdd0bb 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/reconcile_brokers.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/reconcile_brokers.go @@ -1,6 +1,8 @@ package sbproxy import ( + "context" + "github.com/Peripli/service-manager/pkg/log" "sync" "strings" @@ -20,12 +22,13 @@ const ProxyBrokerPrefix = "sm-proxy-" // ReconcileBrokersTask type represents a registration task that takes care of propagating broker creations // and deletions to the platform. It reconciles the state of the proxy brokers in the platform to match // the desired state provided by the Service Manager. -//TODO if the reg credentials are changed (the ones under cf.reg) we need to update the already registered brokers +// TODO if the reg credentials are changed (the ones under cf.reg) we need to update the already registered brokers type ReconcileBrokersTask struct { group *sync.WaitGroup platformClient platform.Client smClient sm.Client proxyPath string + ctx context.Context } type serviceBrokerReg struct { @@ -34,39 +37,41 @@ type serviceBrokerReg struct { } // NewTask builds a new ReconcileBrokersTask -func NewTask(group *sync.WaitGroup, platformClient platform.Client, smClient sm.Client, proxyPath string) *ReconcileBrokersTask { +func NewTask(ctx context.Context, group *sync.WaitGroup, platformClient platform.Client, smClient sm.Client, proxyPath string) *ReconcileBrokersTask { return &ReconcileBrokersTask{ group: group, platformClient: platformClient, smClient: smClient, proxyPath: proxyPath, + ctx: ctx, } } // Run executes the registration task that is responsible for reconciling the state of the proxy brokers at the // platform with the brokers provided by the Service Manager func (r ReconcileBrokersTask) Run() { - logrus.Debug("STARTING scheduled reconciliation task...") + logger := log.C(r.ctx) + logger.Debug("STARTING scheduled reconciliation task...") r.group.Add(1) defer r.group.Done() r.run() - logrus.Debug("FINISHED scheduled reconciliation task...") + logger.Debug("FINISHED scheduled reconciliation task...") } func (r ReconcileBrokersTask) run() { // get all the registered proxy brokers from the platform brokersFromPlatform, err := r.getBrokersFromPlatform() if err != nil { - logrus.WithError(err).Error("An error occurred while obtaining already registered brokers") + log.C(r.ctx).WithError(err).Error("An error occurred while obtaining already registered brokers") return } // get all the brokers that are in SM and for which a proxy broker should be present in the platform brokersFromSM, err := r.getBrokersFromSM() if err != nil { - logrus.WithError(err).Error("An error occurred while obtaining brokers from Service Manager") + log.C(r.ctx).WithError(err).Error("An error occurred while obtaining brokers from Service Manager") return } @@ -95,8 +100,9 @@ func (r ReconcileBrokersTask) reconcileBrokers(existingBrokers []serviceBrokerRe } func (r ReconcileBrokersTask) getBrokersFromPlatform() ([]serviceBrokerReg, error) { - logrus.Debug("ReconcileBrokersTask task getting proxy brokers from platform...") - registeredBrokers, err := r.platformClient.GetBrokers() + logger := log.C(r.ctx) + logger.Debug("ReconcileBrokersTask task getting proxy brokers from platform...") + registeredBrokers, err := r.platformClient.GetBrokers(r.ctx) if err != nil { return nil, errors.Wrap(err, "error getting brokers from platform") } @@ -107,21 +113,22 @@ func (r ReconcileBrokersTask) getBrokersFromPlatform() ([]serviceBrokerReg, erro continue } - logrus.WithFields(logBroker(&broker)).Debug("ReconcileBrokersTask task FOUND registered proxy broker... ") + logger.WithFields(logBroker(&broker)).Debug("ReconcileBrokersTask task FOUND registered proxy broker... ") brokerReg := serviceBrokerReg{ ServiceBroker: broker, SmID: broker.BrokerURL[strings.LastIndex(broker.BrokerURL, "/")+1:], } brokersFromPlatform = append(brokersFromPlatform, brokerReg) } - logrus.Debugf("ReconcileBrokersTask task SUCCESSFULLY retrieved %d proxy brokers from platform", len(brokersFromPlatform)) + logger.Debugf("ReconcileBrokersTask task SUCCESSFULLY retrieved %d proxy brokers from platform", len(brokersFromPlatform)) return brokersFromPlatform, nil } func (r ReconcileBrokersTask) getBrokersFromSM() ([]serviceBrokerReg, error) { - logrus.Debug("ReconcileBrokersTask task getting brokers from Service Manager") + logger := log.C(r.ctx) + logger.Debug("ReconcileBrokersTask task getting brokers from Service Manager") - proxyBrokers, err := r.smClient.GetBrokers() + proxyBrokers, err := r.smClient.GetBrokers(r.ctx) if err != nil { return nil, errors.Wrap(err, "error getting brokers from SM") } @@ -134,72 +141,75 @@ func (r ReconcileBrokersTask) getBrokersFromSM() ([]serviceBrokerReg, error) { } brokersFromSM = append(brokersFromSM, brokerReg) } - logrus.Debugf("ReconcileBrokersTask task SUCCESSFULLY retrieved %d brokers from Service Manager", len(brokersFromSM)) + logger.Debugf("ReconcileBrokersTask task SUCCESSFULLY retrieved %d brokers from Service Manager", len(brokersFromSM)) return brokersFromSM, nil } func (r ReconcileBrokersTask) fetchBrokerCatalog(broker *platform.ServiceBroker) { if f, isFetcher := r.platformClient.(platform.CatalogFetcher); isFetcher { - - logrus.WithFields(logBroker(broker)).Debugf("ReconcileBrokersTask task refetching catalog for broker") - if err := f.Fetch(broker); err != nil { - logrus.WithFields(logBroker(broker)).WithError(err).Error("Error during fetching catalog...") + logger := log.C(r.ctx) + logger.WithFields(logBroker(broker)).Debugf("ReconcileBrokersTask task refetching catalog for broker") + if err := f.Fetch(r.ctx, broker); err != nil { + logger.WithFields(logBroker(broker)).WithError(err).Error("Error during fetching catalog...") } else { - logrus.WithFields(logBroker(broker)).Debug("ReconcileBrokersTask task SUCCESSFULLY refetched catalog for broker") + logger.WithFields(logBroker(broker)).Debug("ReconcileBrokersTask task SUCCESSFULLY refetched catalog for broker") } } } func (r ReconcileBrokersTask) createBrokerRegistration(broker *platform.ServiceBroker) { - logrus.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to create proxy for broker in platform...") + logger := log.C(r.ctx) + logger.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to create proxy for broker in platform...") createRequest := &platform.CreateServiceBrokerRequest{ Name: ProxyBrokerPrefix + broker.GUID, BrokerURL: r.proxyPath + "/" + broker.GUID, } - if _, err := r.platformClient.CreateBroker(createRequest); err != nil { - logrus.WithFields(logBroker(broker)).WithError(err).Error("Error during broker creation") + if _, err := r.platformClient.CreateBroker(r.ctx, createRequest); err != nil { + logger.WithFields(logBroker(broker)).WithError(err).Error("Error during broker creation") } else { - logrus.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task SUCCESSFULLY created proxy for broker at platform under name [%s] accessible at [%s]", createRequest.Name, createRequest.BrokerURL) + logger.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task SUCCESSFULLY created proxy for broker at platform under name [%s] accessible at [%s]", createRequest.Name, createRequest.BrokerURL) } } func (r ReconcileBrokersTask) deleteBrokerRegistration(broker *platform.ServiceBroker) { - logrus.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to delete broker from platform...") + logger := log.C(r.ctx) + logger.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to delete broker from platform...") deleteRequest := &platform.DeleteServiceBrokerRequest{ GUID: broker.GUID, Name: broker.Name, } - if err := r.platformClient.DeleteBroker(deleteRequest); err != nil { - logrus.WithFields(logBroker(broker)).WithError(err).Error("Error during broker deletion") + if err := r.platformClient.DeleteBroker(r.ctx, deleteRequest); err != nil { + logger.WithFields(logBroker(broker)).WithError(err).Error("Error during broker deletion") } else { - logrus.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task SUCCESSFULLY deleted proxy broker from platform with name [%s]", deleteRequest.Name) + logger.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task SUCCESSFULLY deleted proxy broker from platform with name [%s]", deleteRequest.Name) } } func (r ReconcileBrokersTask) enableServiceAccessVisibilities(broker *platform.ServiceBroker) { if f, isEnabler := r.platformClient.(platform.ServiceAccess); isEnabler { emptyContext := emptyContext() - logrus.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to enable service access for broker...") + logger := log.C(r.ctx) + logger.WithFields(logBroker(broker)).Info("ReconcileBrokersTask task attempting to enable service access for broker...") catalog := broker.Catalog if catalog == nil { - logrus.WithFields(logBroker(broker)).Error("Error enabling service access due to missing catalog details") + logger.WithFields(logBroker(broker)).Error("Error enabling service access due to missing catalog details") return } for _, service := range catalog.Services { - logrus.WithFields(logService(service)).Debug("ReconcileBrokersTask task attempting to enable service access for service...") - if err := f.EnableAccessForService(emptyContext, service.ID); err != nil { - logrus.WithFields(logService(service)).WithError(err).Errorf("Error enabling service access for service with ID=%s...", service.ID) + logger.WithFields(logService(service)).Debug("ReconcileBrokersTask task attempting to enable service access for service...") + if err := f.EnableAccessForService(r.ctx, emptyContext, service.ID); err != nil { + logger.WithFields(logService(service)).WithError(err).Errorf("Error enabling service access for service with ID=%s...", service.ID) } - logrus.WithFields(logService(service)).Debug("ReconcileBrokersTask task finished enabling service access for service...") + logger.WithFields(logService(service)).Debug("ReconcileBrokersTask task finished enabling service access for service...") } - logrus.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task finished enabling service access for broker") + logger.WithFields(logBroker(broker)).Infof("ReconcileBrokersTask task finished enabling service access for broker") } } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/sbproxy.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/sbproxy.go index 5dc9fa0c..6d216304 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/sbproxy.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/sbproxy/sbproxy.go @@ -1,6 +1,8 @@ package sbproxy import ( + "github.com/Peripli/service-broker-proxy/pkg/logging" + "github.com/Peripli/service-manager/pkg/log" "sync" "fmt" @@ -9,7 +11,6 @@ import ( "time" "github.com/Peripli/service-broker-proxy/pkg/config" - "github.com/Peripli/service-broker-proxy/pkg/logging" "github.com/Peripli/service-broker-proxy/pkg/osb" "github.com/Peripli/service-broker-proxy/pkg/platform" "github.com/Peripli/service-broker-proxy/pkg/sm" @@ -19,7 +20,6 @@ import ( "github.com/Peripli/service-manager/pkg/server" "github.com/Peripli/service-manager/pkg/web" "github.com/robfig/cron" - "github.com/sirupsen/logrus" "github.com/spf13/pflag" ) @@ -83,7 +83,8 @@ func New(ctx context.Context, env env.Environment, client platform.Client) *SMPr panic(err) } - logging.Setup(cfg.Log) + ctx = log.Configure(ctx, cfg.Log) + log.AddHook(&logging.ErrorLocationHook{}) api := &web.API{ Controllers: []web.Controller{ @@ -96,6 +97,9 @@ func New(ctx context.Context, env env.Environment, client platform.Client) *SMPr Password: cfg.Sm.Password, }), }, + Filters: []web.Filter{ + &filters.Logging{}, + }, } sbProxy := &SMProxyBuilder{ @@ -106,13 +110,13 @@ func New(ctx context.Context, env env.Environment, client platform.Client) *SMPr group: &group, } - regJob, err := defaultRegJob(&group, client, cfg.Sm, cfg.SelfURL) + regJob, err := defaultRegJob(ctx, &group, client, cfg.Sm, cfg.SelfURL) if err != nil { panic(err) } resyncSchedule := "@every " + cfg.Sm.ResyncPeriod.String() - logrus.Info("Brokers and Access resync schedule: ", resyncSchedule) + log.C(ctx).Info("Brokers and Access resync schedule: ", resyncSchedule) if err := cronScheduler.AddJob(resyncSchedule, regJob); err != nil { panic(err) @@ -138,26 +142,26 @@ func (smb *SMProxyBuilder) Build() *SMProxy { func (p *SMProxy) Run() { p.scheduler.Start() defer p.scheduler.Stop() - defer waitWithTimeout(p.group, p.Server.Config.ShutdownTimeout) + defer waitWithTimeout(p.ctx, p.group, p.Server.Config.ShutdownTimeout) - logrus.Info("Running SBProxy...") + log.C(p.ctx).Info("Running SBProxy...") p.Server.Run(p.ctx) } -func defaultRegJob(group *sync.WaitGroup, platformClient platform.Client, smConfig *sm.Settings, proxyHost string) (cron.Job, error) { +func defaultRegJob(ctx context.Context, group *sync.WaitGroup, platformClient platform.Client, smConfig *sm.Settings, proxyHost string) (cron.Job, error) { smClient, err := smConfig.CreateFunc(smConfig) if err != nil { return nil, err } - regTask := NewTask(group, platformClient, smClient, proxyHost+APIPrefix) + regTask := NewTask(ctx, group, platformClient, smClient, proxyHost+APIPrefix) return regTask, nil } // waitWithTimeout waits for a WaitGroup to finish for a certain duration and times out afterwards // WaitGroup parameter should be pointer or else the copy won't get notified about .Done() calls -func waitWithTimeout(group *sync.WaitGroup, timeout time.Duration) { +func waitWithTimeout(ctx context.Context, group *sync.WaitGroup, timeout time.Duration) { c := make(chan struct{}) go func() { defer close(c) @@ -165,9 +169,9 @@ func waitWithTimeout(group *sync.WaitGroup, timeout time.Duration) { }() select { case <-c: - logrus.Debug(fmt.Sprintf("Timeout WaitGroup %+v finished successfully", group)) + log.C(ctx).Debug(fmt.Sprintf("Timeout WaitGroup %+v finished successfully", group)) case <-time.After(timeout): - logrus.Fatal("Shutdown took more than ", timeout) + log.C(ctx).Fatal("Shutdown took more than ", timeout) close(c) } } diff --git a/vendor/github.com/Peripli/service-broker-proxy/pkg/sm/client.go b/vendor/github.com/Peripli/service-broker-proxy/pkg/sm/client.go index 30bc4083..a7dc99e4 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/pkg/sm/client.go +++ b/vendor/github.com/Peripli/service-broker-proxy/pkg/sm/client.go @@ -1,7 +1,9 @@ package sm import ( + "context" "fmt" + "github.com/Peripli/service-manager/pkg/log" "net/http" "time" @@ -9,7 +11,6 @@ import ( "github.com/Peripli/service-broker-proxy/pkg/platform" "github.com/Peripli/service-manager/pkg/util" "github.com/pkg/errors" - "github.com/sirupsen/logrus" ) // APIInternalBrokers is the SM API for obtaining the brokers for this proxy @@ -18,7 +19,7 @@ const APIInternalBrokers = "%s/v1/service_brokers" // Client provides the logic for calling into the Service Manager //go:generate counterfeiter . Client type Client interface { - GetBrokers() ([]platform.ServiceBroker, error) + GetBrokers(ctx context.Context) ([]platform.ServiceBroker, error) } type serviceManagerClient struct { @@ -56,10 +57,10 @@ func NewClient(config *Settings) (Client, error) { // GetBrokers calls the Service Manager in order to obtain all brokers t hat need to be registered // in the service broker proxy -func (c *serviceManagerClient) GetBrokers() ([]platform.ServiceBroker, error) { - logrus.Debugf("Getting brokers for proxy from Service Manager at %s", c.Config.URL) +func (c *serviceManagerClient) GetBrokers(ctx context.Context) ([]platform.ServiceBroker, error) { + log.C(ctx).Debugf("Getting brokers for proxy from Service Manager at %s", c.Config.URL) URL := fmt.Sprintf(APIInternalBrokers, c.Config.URL) - response, err := util.SendRequest(c.httpClient.Do, http.MethodGet, URL, map[string]string{"catalog": "true"}, nil) + response, err := util.SendRequest(ctx, c.httpClient.Do, http.MethodGet, URL, map[string]string{"catalog": "true"}, nil) if err != nil { return nil, errors.Wrap(err, "error getting brokers from Service Manager") } diff --git a/vendor/github.com/Peripli/service-broker-proxy/release-notes.md b/vendor/github.com/Peripli/service-broker-proxy/release-notes.md index 59c50300..823cc9d9 100644 --- a/vendor/github.com/Peripli/service-broker-proxy/release-notes.md +++ b/vendor/github.com/Peripli/service-broker-proxy/release-notes.md @@ -1,7 +1,7 @@ # Service Broker Proxy Release Notes -## init +## v0.1.0 -2018-02-28 +2018-09-19 -* Repository is created +* Initial version diff --git a/vendor/github.com/Peripli/service-manager/Gopkg.lock b/vendor/github.com/Peripli/service-manager/Gopkg.lock index c5722678..1f117830 100644 --- a/vendor/github.com/Peripli/service-manager/Gopkg.lock +++ b/vendor/github.com/Peripli/service-manager/Gopkg.lock @@ -148,14 +148,6 @@ revision = "08b5f424b9271eedf6f9f0ce86cb9396ed337a42" version = "v1.1.1" -[[projects]] - digest = "1:185a43b59a1f4e7ad4e7ccafb8a1538193d897a2a75be16dda093ec42ad231cf" - name = "github.com/gorilla/handlers" - packages = ["."] - pruneopts = "UT" - revision = "90663712d74cb411cbef281bc1e08c19d1a76145" - version = "v1.3.0" - [[projects]] digest = "1:88aa9e326e2bd6045a46e00a922954b3e1a9ac5787109f49ac85366df370e1e5" name = "github.com/gorilla/mux" @@ -165,8 +157,7 @@ version = "v1.6.1" [[projects]] - branch = "master" - digest = "1:a361611b8c8c75a1091f00027767f7779b29cb37c456a71b8f2604c88057ab40" + digest = "1:c0d19ab64b32ce9fe5cf4ddceba78d5bc9807f0016db6b1183599da3dcc24d10" name = "github.com/hashicorp/hcl" packages = [ ".", @@ -181,7 +172,8 @@ "json/token", ] pruneopts = "UT" - revision = "ef8a98b0bbce4a65b5aa4c368430a80ddc533168" + revision = "8cb6e5b959231cc1119e43259c4a608f9c51a241" + version = "v1.0.0" [[projects]] digest = "1:a1038ef593beb4771c8f0f9c26e8b00410acd800af5c6864651d9bf160ea1813" @@ -257,12 +249,12 @@ version = "v1.8.0" [[projects]] - branch = "master" - digest = "1:5ab79470a1d0fb19b041a624415612f8236b3c06070161a910562f2b2d064355" + digest = "1:645110e089152bd0f4a011a2648fbb0e4df5977be73ca605781157ac297f50c4" name = "github.com/mitchellh/mapstructure" packages = ["."] pruneopts = "UT" - revision = "f15292f7a699fcc1a38a80977f80a046874ba8ac" + revision = "fa473d140ef3c6adf42d6b391fe76707f1f243c8" + version = "v1.0.0" [[projects]] branch = "master" @@ -272,6 +264,14 @@ pruneopts = "UT" revision = "9ac6cf4d929b2fa8fd2d2e6dec5bb0feb4f4911d" +[[projects]] + branch = "master" + digest = "1:4323c6f79178c6f811a0528b1b2eba03bad0cae33605636f1e38c8f907b5cbf7" + name = "github.com/onrik/logrus" + packages = ["filename"] + pruneopts = "UT" + revision = "ca0a758702be2ae04725ba88dcd27a71949faf33" + [[projects]] digest = "1:42e29deef12327a69123b9cb2cb45fee4af5c12c2a23c6e477338279a052703f" name = "github.com/onsi/ginkgo" @@ -535,7 +535,7 @@ [[projects]] branch = "master" - digest = "1:3245eeb32b9e23f7ee41ce584ce75dca6f322c2be9ab2d9afcf8ca4758af7eff" + digest = "1:d46bff7a9e1dbdc74e63bc4eca8865f18eaa335755bbcd0773b5107b3b9407a6" name = "golang.org/x/net" packages = [ "context", @@ -547,7 +547,7 @@ "publicsuffix", ] pruneopts = "UT" - revision = "922f4815f713f213882e8ef45e0d315b164d705c" + revision = "8a410e7b638dca158bf9e766925842f6651ff828" [[projects]] branch = "master" @@ -562,14 +562,14 @@ [[projects]] branch = "master" - digest = "1:48774faa158e9eaee1ba45aad66434bb0345927b43756a24d4fe4c44ad79e307" + digest = "1:0dafafed83f125cdc945a014b2dec15e5b5d8cd2d77a2d1e3763120b08ab381b" name = "golang.org/x/sys" packages = [ "unix", "windows", ] pruneopts = "UT" - revision = "3b58ed4ad3395d483fc92d5d14123ce2c3581fec" + revision = "4910a1d54f876d7b22162a85f4d066d3ee649450" [[projects]] digest = "1:436b24586f8fee329e0dd65fd67c817681420cda1d7f934345c13fe78c212a73" @@ -674,12 +674,12 @@ "github.com/golang-migrate/migrate", "github.com/golang-migrate/migrate/database/postgres", "github.com/golang-migrate/migrate/source/file", - "github.com/gorilla/handlers", "github.com/gorilla/mux", "github.com/jmoiron/sqlx", "github.com/jmoiron/sqlx/types", "github.com/lib/pq", "github.com/mitchellh/mapstructure", + "github.com/onrik/logrus/filename", "github.com/onsi/ginkgo", "github.com/onsi/gomega", "github.com/onsi/gomega/ghttp", diff --git a/vendor/github.com/Peripli/service-manager/Gopkg.toml b/vendor/github.com/Peripli/service-manager/Gopkg.toml index 74d24ed3..60910166 100644 --- a/vendor/github.com/Peripli/service-manager/Gopkg.toml +++ b/vendor/github.com/Peripli/service-manager/Gopkg.toml @@ -4,10 +4,6 @@ go-tests = true unused-packages = true -[[constraint]] - name = "github.com/gorilla/handlers" - version = "=1.3.0" - # Backwards-incompatible change is introduced in mux 1.6.2 - gorilla/mux#338 [[constraint]] name = "github.com/gorilla/mux" @@ -17,6 +13,10 @@ name = "github.com/sirupsen/logrus" version = "1.0.4" +[[constraint]] + name = "github.com/onrik/logrus" + branch = "master" + [[constraint]] name = "github.com/onsi/ginkgo" version = "1.4.0" diff --git a/vendor/github.com/Peripli/service-manager/api/api.go b/vendor/github.com/Peripli/service-manager/api/api.go index 71a967ad..f4e1cfa5 100644 --- a/vendor/github.com/Peripli/service-manager/api/api.go +++ b/vendor/github.com/Peripli/service-manager/api/api.go @@ -24,6 +24,7 @@ import ( "github.com/Peripli/service-manager/api/broker" "github.com/Peripli/service-manager/api/catalog" + "github.com/Peripli/service-manager/api/filters" "github.com/Peripli/service-manager/api/filters/authn" "github.com/Peripli/service-manager/api/healthcheck" "github.com/Peripli/service-manager/api/info" @@ -116,6 +117,7 @@ func New(ctx context.Context, storage storage.Storage, settings *Settings, encry }, // Default filters - more filters can be registered using the relevant API methods Filters: []web.Filter{ + &filters.Logging{}, authn.NewBasicAuthnFilter(storage.Credentials(), encrypter), bearerAuthnFilter, authn.NewRequiredAuthnFilter(), diff --git a/vendor/github.com/Peripli/service-manager/api/api_test.go b/vendor/github.com/Peripli/service-manager/api/api_test.go index d77aea61..62fa09a2 100644 --- a/vendor/github.com/Peripli/service-manager/api/api_test.go +++ b/vendor/github.com/Peripli/service-manager/api/api_test.go @@ -21,7 +21,6 @@ import ( "testing" "github.com/Peripli/service-manager/api" - "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/storage/storagefakes" "github.com/Peripli/service-manager/test/common" . "github.com/onsi/ginkgo" @@ -35,21 +34,27 @@ func TestAPI(t *testing.T) { var _ = Describe("API", func() { var ( - API *web.API - err error mockedStorage *storagefakes.FakeStorage - ctx context.Context + server *common.OAuthServer ) + BeforeSuite(func() { + server = common.NewOAuthServer() + server.Start() + }) + + AfterSuite(func() { + server.Close() + }) + BeforeEach(func() { mockedStorage = &storagefakes.FakeStorage{} - ctx = context.TODO() - }) + Describe("New", func() { + It("returns no error if creation is successful", func() { - server := common.SetupFakeOAuthServer() - API, err = api.New(context.TODO(), mockedStorage, &api.Settings{ + _, err := api.New(context.TODO(), mockedStorage, &api.Settings{ TokenIssuerURL: server.URL, ClientID: "sm", }, nil) @@ -57,12 +62,11 @@ var _ = Describe("API", func() { }) It("returns an error if creation fails", func() { - API, err = api.New(context.TODO(), mockedStorage, &api.Settings{ + _, err := api.New(context.TODO(), mockedStorage, &api.Settings{ TokenIssuerURL: "http://invalidurl.com", ClientID: "invalidclient", }, nil) Expect(err).Should(HaveOccurred()) - }) }) }) diff --git a/vendor/github.com/Peripli/service-manager/api/broker/broker_controller.go b/vendor/github.com/Peripli/service-manager/api/broker/broker_controller.go index f650f433..ccb4b62b 100644 --- a/vendor/github.com/Peripli/service-manager/api/broker/broker_controller.go +++ b/vendor/github.com/Peripli/service-manager/api/broker/broker_controller.go @@ -17,12 +17,14 @@ package broker import ( + "context" "encoding/json" "fmt" "net/http" "strings" "time" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/security" osbc "github.com/pmorie/go-open-service-broker-client/v2" @@ -31,7 +33,6 @@ import ( "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/storage" "github.com/gofrs/uuid" - "github.com/sirupsen/logrus" ) const ( @@ -48,11 +49,12 @@ type Controller struct { var _ web.Controller = &Controller{} -func (c *Controller) createBroker(request *web.Request) (*web.Response, error) { - logrus.Debug("Creating new broker") +func (c *Controller) createBroker(r *web.Request) (*web.Response, error) { + ctx := r.Context() + log.C(ctx).Debug("Creating new broker") broker := &types.Broker{} - if err := util.BytesToObject(request.Body, broker); err != nil { + if err := util.BytesToObject(r.Body, broker); err != nil { return nil, err } @@ -67,16 +69,16 @@ func (c *Controller) createBroker(request *web.Request) (*web.Response, error) { broker.CreatedAt = currentTime broker.UpdatedAt = currentTime - catalog, err := c.getBrokerCatalog(broker) + catalog, err := c.getBrokerCatalog(ctx, broker) if err != nil { return nil, err } broker.Catalog = catalog - if err := transformBrokerCredentials(broker, c.Encrypter.Encrypt); err != nil { + if err := transformBrokerCredentials(ctx, broker, c.Encrypter.Encrypt); err != nil { return nil, err } - if err := c.BrokerStorage.Create(broker); err != nil { + if err := c.BrokerStorage.Create(ctx, broker); err != nil { return nil, util.HandleStorageError(err, "broker", broker.ID) } @@ -85,11 +87,12 @@ func (c *Controller) createBroker(request *web.Request) (*web.Response, error) { return util.NewJSONResponse(http.StatusCreated, broker) } -func (c *Controller) getBroker(request *web.Request) (*web.Response, error) { - brokerID := request.PathParams[reqBrokerID] - logrus.Debugf("Getting broker with id %s", brokerID) +func (c *Controller) getBroker(r *web.Request) (*web.Response, error) { + brokerID := r.PathParams[reqBrokerID] + ctx := r.Context() + log.C(ctx).Debugf("Getting broker with id %s", brokerID) - broker, err := c.BrokerStorage.Get(brokerID) + broker, err := c.BrokerStorage.Get(ctx, brokerID) if err != nil { return nil, util.HandleStorageError(err, "broker", brokerID) } @@ -99,14 +102,15 @@ func (c *Controller) getBroker(request *web.Request) (*web.Response, error) { return util.NewJSONResponse(http.StatusOK, broker) } -func (c *Controller) getAllBrokers(request *web.Request) (*web.Response, error) { - logrus.Debug("Getting all brokers") - brokers, err := c.BrokerStorage.GetAll() +func (c *Controller) getAllBrokers(r *web.Request) (*web.Response, error) { + ctx := r.Context() + log.C(ctx).Debug("Getting all brokers") + brokers, err := c.BrokerStorage.GetAll(ctx) if err != nil { return nil, err } - removeCatalog := strings.ToLower(request.FormValue(catalogParam)) != "true" + removeCatalog := strings.ToLower(r.FormValue(catalogParam)) != "true" for _, broker := range brokers { broker.Credentials = nil if removeCatalog { @@ -119,36 +123,38 @@ func (c *Controller) getAllBrokers(request *web.Request) (*web.Response, error) }) } -func (c *Controller) deleteBroker(request *web.Request) (*web.Response, error) { - brokerID := request.PathParams[reqBrokerID] - logrus.Debugf("Deleting broker with id %s", brokerID) +func (c *Controller) deleteBroker(r *web.Request) (*web.Response, error) { + brokerID := r.PathParams[reqBrokerID] + ctx := r.Context() + log.C(ctx).Debugf("Deleting broker with id %s", brokerID) - if err := c.BrokerStorage.Delete(brokerID); err != nil { + if err := c.BrokerStorage.Delete(ctx, brokerID); err != nil { return nil, util.HandleStorageError(err, "broker", brokerID) } return util.NewJSONResponse(http.StatusOK, map[string]int{}) } -func (c *Controller) patchBroker(request *web.Request) (*web.Response, error) { - brokerID := request.PathParams[reqBrokerID] - logrus.Debugf("Updating updateBroker with id %s", brokerID) +func (c *Controller) patchBroker(r *web.Request) (*web.Response, error) { + brokerID := r.PathParams[reqBrokerID] + ctx := r.Context() + log.C(ctx).Debugf("Updating updateBroker with id %s", brokerID) - broker, err := c.BrokerStorage.Get(brokerID) + broker, err := c.BrokerStorage.Get(ctx, brokerID) if err != nil { return nil, util.HandleStorageError(err, "broker", brokerID) } createdAt := broker.CreatedAt - if err := util.BytesToObject(request.Body, broker); err != nil { + if err := util.BytesToObject(r.Body, broker); err != nil { return nil, err } - if err := transformBrokerCredentials(broker, c.Encrypter.Encrypt); err != nil { + if err := transformBrokerCredentials(ctx, broker, c.Encrypter.Encrypt); err != nil { return nil, err } - catalog, err := c.getBrokerCatalog(broker) + catalog, err := c.getBrokerCatalog(ctx, broker) if err != nil { return nil, err } @@ -158,7 +164,7 @@ func (c *Controller) patchBroker(request *web.Request) (*web.Response, error) { broker.CreatedAt = createdAt broker.UpdatedAt = time.Now().UTC() - if err := c.BrokerStorage.Update(broker); err != nil { + if err := c.BrokerStorage.Update(ctx, broker); err != nil { return nil, util.HandleStorageError(err, "broker", brokerID) } @@ -168,14 +174,14 @@ func (c *Controller) patchBroker(request *web.Request) (*web.Response, error) { return util.NewJSONResponse(http.StatusOK, broker) } -func (c *Controller) getBrokerCatalog(broker *types.Broker) (json.RawMessage, error) { - osbClient, err := osbClient(c.OSBClientCreateFunc, broker) +func (c *Controller) getBrokerCatalog(ctx context.Context, broker *types.Broker) (json.RawMessage, error) { + osbClient, err := osbClient(ctx, c.OSBClientCreateFunc, broker) if err != nil { return nil, err } catalog, err := osbClient.GetCatalog() if err != nil { - return nil, err + return nil, fmt.Errorf("Error fetching catalog from broker %s: %v", broker.Name, err) } bytes, err := json.Marshal(catalog) @@ -186,9 +192,9 @@ func (c *Controller) getBrokerCatalog(broker *types.Broker) (json.RawMessage, er return json.RawMessage(bytes), nil } -func osbClient(createFunc osbc.CreateFunc, broker *types.Broker) (osbc.Client, error) { +func osbClient(ctx context.Context, createFunc osbc.CreateFunc, broker *types.Broker) (osbc.Client, error) { config := clientConfigForBroker(broker) - logrus.Debug("Building OSB client for serviceBroker with name: ", config.Name, " accessible at: ", config.URL) + log.C(ctx).Debug("Building OSB client for serviceBroker with name: ", config.Name, " accessible at: ", config.URL) return createFunc(config) } @@ -205,9 +211,9 @@ func clientConfigForBroker(broker *types.Broker) *osbc.ClientConfiguration { return config } -func transformBrokerCredentials(broker *types.Broker, transformationFunc func([]byte) ([]byte, error)) error { +func transformBrokerCredentials(ctx context.Context, broker *types.Broker, transformationFunc func(context.Context, []byte) ([]byte, error)) error { if broker.Credentials != nil { - transformedPassword, err := transformationFunc([]byte(broker.Credentials.Basic.Password)) + transformedPassword, err := transformationFunc(ctx, []byte(broker.Credentials.Basic.Password)) if err != nil { return err } diff --git a/vendor/github.com/Peripli/service-manager/api/catalog/catalog_controller.go b/vendor/github.com/Peripli/service-manager/api/catalog/catalog_controller.go index 0a6f6549..53d7e446 100644 --- a/vendor/github.com/Peripli/service-manager/api/catalog/catalog_controller.go +++ b/vendor/github.com/Peripli/service-manager/api/catalog/catalog_controller.go @@ -20,13 +20,14 @@ import ( "encoding/json" "net/http" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/storage" - "github.com/sirupsen/logrus" ) + // Controller catalog controller type Controller struct { BrokerStorage storage.Broker @@ -44,17 +45,18 @@ type aggregatedCatalog struct { Brokers []brokerServices `json:"brokers"` } -func (c *Controller) getCatalog(request *web.Request) (*web.Response, error) { - logrus.Debugf("Aggregating all broker catalogs") - brokers, err := c.BrokerStorage.GetAll() +func (c *Controller) getCatalog(r *web.Request) (*web.Response, error) { + ctx := r.Context() + log.C(ctx).Debugf("Aggregating all broker catalogs") + brokers, err := c.BrokerStorage.GetAll(ctx) if err != nil { return nil, err } resultServices := make([]brokerServices, 0, len(brokers)+1) - queryBrokerIDs := request.URL.Query()["broker_id"] + queryBrokerIDs := r.URL.Query()["broker_id"] if len(queryBrokerIDs) != 0 { - logrus.Debugf("Filtering based on the provided query parameters: %s", queryBrokerIDs) + log.C(ctx).Debugf("Filtering based on the provided query parameters: %s", queryBrokerIDs) filterBrokersByID(brokers, queryBrokerIDs, &resultServices) } else { retrieveAllBrokers(brokers, &resultServices) diff --git a/vendor/github.com/Peripli/service-manager/api/filters/authn/authn.go b/vendor/github.com/Peripli/service-manager/api/filters/authn/authn.go index a02886c1..b95dc9b9 100644 --- a/vendor/github.com/Peripli/service-manager/api/filters/authn/authn.go +++ b/vendor/github.com/Peripli/service-manager/api/filters/authn/authn.go @@ -19,7 +19,7 @@ var ( errUserNotFound = errors.New("user identity must be provided when allowing authentication") ) -// Middleware type represents an anthentication middleware +// Middleware type represents an authentication middleware type Middleware struct { authenticator security.Authenticator name string @@ -28,7 +28,8 @@ type Middleware struct { // Run represents the authentication middleware function that delegates the authentication // to the provided authenticator func (ba *Middleware) Run(request *web.Request, next web.Handler) (*web.Response, error) { - if _, ok := web.UserFromContext(request.Context()); ok { + ctx := request.Context() + if _, ok := web.UserFromContext(ctx); ok { return next.Handle(request) } @@ -49,7 +50,7 @@ func (ba *Middleware) Run(request *web.Request, next web.Handler) (*web.Response if user == nil { return nil, errUserNotFound } - request.Request = request.WithContext(web.NewContextWithUser(request.Context(), user)) + request.Request = request.WithContext(web.NewContextWithUser(ctx, user)) case security.Deny: return nil, errUnauthorized } diff --git a/vendor/github.com/Peripli/service-manager/api/filters/authn/authn_test.go b/vendor/github.com/Peripli/service-manager/api/filters/authn/authn_test.go index f7a7f50d..6c7301ab 100644 --- a/vendor/github.com/Peripli/service-manager/api/filters/authn/authn_test.go +++ b/vendor/github.com/Peripli/service-manager/api/filters/authn/authn_test.go @@ -228,7 +228,6 @@ var _ = Describe("Authn", func() { Describe("Authentication Required Middleware", func() { var ( - fakeHandler *webfakes.FakeHandler authnRequiredFilter *RequiredAuthnFilter ) @@ -237,7 +236,6 @@ var _ = Describe("Authn", func() { } BeforeEach(func() { - fakeHandler = &webfakes.FakeHandler{} authnRequiredFilter = NewRequiredAuthnFilter() }) diff --git a/vendor/github.com/Peripli/service-manager/api/filters/authn/required.go b/vendor/github.com/Peripli/service-manager/api/filters/authn/required.go index 8da53b4d..8434a576 100644 --- a/vendor/github.com/Peripli/service-manager/api/filters/authn/required.go +++ b/vendor/github.com/Peripli/service-manager/api/filters/authn/required.go @@ -1,9 +1,12 @@ package authn import ( + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/web" - "github.com/sirupsen/logrus" -) + ) + +// RequiredAuthenticationFilterName is the name of RequiredAuthenticationFilter +const RequiredAuthenticationFilterName = "RequiredAuthenticationFilter" // RequiredAuthnFilter type verifies that authentication has been performed for APIs that are secured type RequiredAuthnFilter struct { @@ -16,14 +19,15 @@ func NewRequiredAuthnFilter() *RequiredAuthnFilter { // Name implements the web.Filter interface and returns the identifier of the filter func (raf *RequiredAuthnFilter) Name() string { - return "RequiredAuthenticationFilter" + return RequiredAuthenticationFilterName } // Run implements web.Filter and represents the authentication middleware function that verifies the user is // authenticated func (raf *RequiredAuthnFilter) Run(request *web.Request, next web.Handler) (*web.Response, error) { - if _, ok := web.UserFromContext(request.Context()); !ok { - logrus.Error("No authenticated user found in request context during execution of filter ", raf.Name()) + ctx := request.Context() + if _, ok := web.UserFromContext(ctx); !ok { + log.C(ctx).Error("No authenticated user found in request context during execution of filter ", raf.Name()) return nil, errUnauthorized } diff --git a/vendor/github.com/Peripli/service-manager/api/filters/logging.go b/vendor/github.com/Peripli/service-manager/api/filters/logging.go new file mode 100644 index 00000000..a1af5cdd --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/api/filters/logging.go @@ -0,0 +1,59 @@ +/* + * Copyright 2018 The Service Manager Authors + * + * 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. + */ + +package filters + +import ( + "github.com/Peripli/service-manager/pkg/log" + "github.com/Peripli/service-manager/pkg/web" +) + +const ( + // LoggingFilterName is the name of the logging filter + LoggingFilterName = "LoggingFilter" +) + +// Logging is filter that configures logging per request. +type Logging struct { +} + +// Name implements the web.Filter interface and returns the identifier of the filter. +func (*Logging) Name() string { + return LoggingFilterName +} + +// Run represents the logging middleware function that processes the request and configures the request-scoped logging. +func (l *Logging) Run(req *web.Request, next web.Handler) (*web.Response, error) { + ctx := req.Context() + entry := log.C(ctx) + if correlationID := log.CorrelationIDForRequest(req.Request); correlationID != "" { + entry = entry.WithField(log.FieldCorrelationID, correlationID) + } + ctx = log.ContextWithLogger(ctx, entry) + req.Request = req.WithContext(ctx) + return next.Handle(req) +} + +// FilterMatchers implements the web.Filter interface and returns the conditions on which the filter should be executed. +func (*Logging) FilterMatchers() []web.FilterMatcher { + return []web.FilterMatcher{ + { + Matchers: []web.Matcher{ + web.Path("/**"), + }, + }, + } +} diff --git a/vendor/github.com/Peripli/service-manager/api/filters/logging_test.go b/vendor/github.com/Peripli/service-manager/api/filters/logging_test.go new file mode 100644 index 00000000..32360c95 --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/api/filters/logging_test.go @@ -0,0 +1,64 @@ +/* + * Copyright 2018 The Service Manager Authors + * + * 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. + */ + +package filters + +import ( + "net/http" + "testing" + + "github.com/Peripli/service-manager/pkg/log" + "github.com/Peripli/service-manager/pkg/web" + "github.com/Peripli/service-manager/pkg/web/webfakes" + . "github.com/onsi/ginkgo" + . "github.com/onsi/gomega" +) + +func TestHandler(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "API Filters Suite") +} + +var _ = Describe("Logging Filter", func() { + loggingFilter := &Logging{} + var request *web.Request + var handler *webfakes.FakeHandler + BeforeEach(func() { + request = &web.Request{Request: &http.Request{}} + request.Header = http.Header{} + handler = &webfakes.FakeHandler{} + }) + Describe("Correlation Id", func() { + Context("When none is provided in header", func() { + It("Should generate a new for logger", func() { + loggingFilter.Run(request, handler) + logger := log.C(request.Context()) + correlationId := logger.Data[log.FieldCorrelationID].(string) + Expect(correlationId).ToNot(BeEmpty()) + }) + }) + Context("When one is provided in header", func() { + It("Uses it for logger", func() { + expectedCorrelationId := "correlationId" + request.Header["X-Correlation-ID"] = []string{expectedCorrelationId} + loggingFilter.Run(request, handler) + logger := log.C(request.Context()) + correlationId := logger.Data[log.FieldCorrelationID].(string) + Expect(correlationId).To(Equal(expectedCorrelationId)) + }) + }) + }) +}) diff --git a/vendor/github.com/Peripli/service-manager/api/filters/recovery.go b/vendor/github.com/Peripli/service-manager/api/filters/recovery.go index 046a9b91..a8dbe4c0 100644 --- a/vendor/github.com/Peripli/service-manager/api/filters/recovery.go +++ b/vendor/github.com/Peripli/service-manager/api/filters/recovery.go @@ -1,23 +1,30 @@ package filters import ( - "github.com/gorilla/handlers" + "net/http" + "runtime/debug" + + "github.com/Peripli/service-manager/pkg/log" + "github.com/Peripli/service-manager/pkg/util" "github.com/gorilla/mux" - "github.com/sirupsen/logrus" ) // NewRecoveryMiddleware returns a standard mux middleware that provides panic recovery func NewRecoveryMiddleware() mux.MiddlewareFunc { - return handlers.RecoveryHandler( - handlers.PrintRecoveryStack(true), - handlers.RecoveryLogger(&recoveryHandlerLogger{}), - ) -} - -type recoveryHandlerLogger struct { -} - -// PrintLn prints panic message and stack to error output -func (r *recoveryHandlerLogger) Println(args ...interface{}) { - logrus.Errorln(args...) + return func(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + defer func() { + if err := recover(); err != nil { + httpError := &util.HTTPError{ + StatusCode: http.StatusInternalServerError, + Description: "Internal Server Error", + } + util.WriteError(httpError, w) + debug.PrintStack() + log.C(r.Context()).Error(err) + } + }() + handler.ServeHTTP(w, r) + }) + } } diff --git a/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller.go b/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller.go index e5f7f116..f4d7365b 100644 --- a/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller.go +++ b/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller.go @@ -19,12 +19,13 @@ package healthcheck import ( "net/http" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/storage" - "github.com/sirupsen/logrus" ) + // Controller platform controller type Controller struct { Storage storage.Storage @@ -47,14 +48,16 @@ var statusStorageFailureResponse = map[string]interface{}{ } // healthCheck handler for GET /v1/monitor/health -func (c *Controller) healthCheck(request *web.Request) (*web.Response, error) { - logrus.Debug("Performing health check...") +func (c *Controller) healthCheck(r *web.Request) (*web.Response, error) { + ctx := r.Context() + logger := log.C(ctx) + logger.Debug("Performing health check...") if err := c.Storage.Ping(); err != nil { - logrus.Debugf("storage.Ping failed: %s", err) + logger.Debugf("storage.Ping failed: %s", err) return util.NewJSONResponse(http.StatusServiceUnavailable, statusStorageFailureResponse) } - logrus.Debug("Successfully completed health check") + logger.Debug("Successfully completed health check") return util.NewJSONResponse(http.StatusOK, statusRunningResponse) } diff --git a/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller_test.go b/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller_test.go index 168cba55..10f46cb2 100644 --- a/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller_test.go +++ b/vendor/github.com/Peripli/service-manager/api/healthcheck/healthcheck_controller_test.go @@ -21,6 +21,7 @@ import ( "net/http" "testing" + "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/storage/storagefakes" . "github.com/onsi/ginkgo" @@ -47,7 +48,7 @@ var _ = Describe("Healthcheck controller", func() { Describe("healthCheck", func() { Context("when ping returns error", func() { It("should respond with 503", func() { - resp, err := createController(errors.New("expected")).healthCheck(nil) + resp, err := createController(errors.New("expected")).healthCheck(&web.Request{Request: &http.Request{}}) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusServiceUnavailable)) Expect(string(resp.Body)).To(Equal(string(unavailableResponse))) @@ -56,7 +57,7 @@ var _ = Describe("Healthcheck controller", func() { Context("when ping returns nil", func() { It("should respond with 200", func() { - resp, err := createController(nil).healthCheck(nil) + resp, err := createController(nil).healthCheck(&web.Request{Request: &http.Request{}}) Expect(err).ToNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) Expect(string(resp.Body)).To(Equal(string(availableResponse))) diff --git a/vendor/github.com/Peripli/service-manager/api/http_handler.go b/vendor/github.com/Peripli/service-manager/api/http_handler.go index b6af530e..170afe67 100644 --- a/vendor/github.com/Peripli/service-manager/api/http_handler.go +++ b/vendor/github.com/Peripli/service-manager/api/http_handler.go @@ -19,8 +19,7 @@ package api import ( "net/http" - "github.com/sirupsen/logrus" - + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/pkg/web" "github.com/gorilla/mux" @@ -73,7 +72,7 @@ func (h *HTTPHandler) serve(res http.ResponseWriter, req *http.Request) error { if err != nil { // HTTP headers and status are sent already // if we return an error, the error Handler will try to send them again - logrus.Error("Error sending response", err) + log.C(req.Context()).Error("Error sending response", err) } return nil } diff --git a/vendor/github.com/Peripli/service-manager/api/osb/osb_controller.go b/vendor/github.com/Peripli/service-manager/api/osb/osb_controller.go index 80a774f7..8820401f 100644 --- a/vendor/github.com/Peripli/service-manager/api/osb/osb_controller.go +++ b/vendor/github.com/Peripli/service-manager/api/osb/osb_controller.go @@ -17,22 +17,20 @@ package osb import ( + "bytes" + "context" "fmt" "io/ioutil" "net/http" + "net/http/httptest" + "net/http/httputil" "net/url" "regexp" - "net/http/httputil" - - "net/http/httptest" - - "bytes" - + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/pkg/web" - "github.com/sirupsen/logrus" ) var osbPathPattern = regexp.MustCompile("^" + web.OSBURL + "/[^/]+(/.*)$") @@ -41,7 +39,7 @@ var osbPathPattern = regexp.MustCompile("^" + web.OSBURL + "/[^/]+(/.*)$") type BrokerRoundTripper interface { http.RoundTripper - Broker(brokerID string) (*types.Broker, error) + Broker(ctx context.Context, brokerID string) (*types.Broker, error) } // Controller implements api.Controller by providing OSB API logic @@ -63,47 +61,48 @@ func NewController(fetcher BrokerRoundTripper) web.Controller { } } -func (c *controller) handler(request *web.Request) (*web.Response, error) { - logrus.Debug("Executing OSB operation: ", request.URL.Path) +func (c *controller) handler(r *web.Request) (*web.Response, error) { + ctx := r.Context() + logger := log.C(ctx) + logger.Debug("Executing OSB operation: ", r.URL.Path) - brokerID, ok := request.PathParams[BrokerIDPathParam] + brokerID, ok := r.PathParams[BrokerIDPathParam] if !ok { - logrus.Debugf("error creating OSB client: brokerID path parameter not found") + logger.Debugf("error creating OSB client: brokerID path parameter not found") return nil, &util.HTTPError{ ErrorType: "BadRequest", Description: "invalid broker id path parameter", StatusCode: http.StatusBadRequest, } } - logrus.Debugf("Obtained path parameter [brokerID = %s] from path params", brokerID) + logger.Debugf("Obtained path parameter [brokerID = %s] from path params", brokerID) - broker, err := c.fetcher.Broker(brokerID) + broker, err := c.fetcher.Broker(ctx, brokerID) if err != nil { return nil, err } targetBrokerURL, _ := url.Parse(broker.BrokerURL) - m := osbPathPattern.FindStringSubmatch(request.URL.Path) + m := osbPathPattern.FindStringSubmatch(r.URL.Path) if m == nil || len(m) < 2 { - return nil, fmt.Errorf("could not get OSB path from URL %s", request.URL.Path) + return nil, fmt.Errorf("could not get OSB path from URL %s", r.URL.Path) } - modifiedRequest := request.Request.WithContext(request.Context()) + modifiedRequest := r.Request.WithContext(ctx) modifiedRequest.SetBasicAuth(broker.Credentials.Basic.Username, broker.Credentials.Basic.Password) - modifiedRequest.Body = ioutil.NopCloser(bytes.NewReader(request.Body)) - modifiedRequest.ContentLength = int64(len(request.Body)) + modifiedRequest.Body = ioutil.NopCloser(bytes.NewReader(r.Body)) + modifiedRequest.ContentLength = int64(len(r.Body)) modifiedRequest.Host = targetBrokerURL.Host modifiedRequest.URL.Path = m[1] - logrus.Debugf("Forwarding OSB request to %s", modifiedRequest.URL) + logger.Debugf("Forwarding OSB r to %s", modifiedRequest.URL) proxy := httputil.NewSingleHostReverseProxy(targetBrokerURL) proxy.Transport = c.fetcher recorder := httptest.NewRecorder() proxy.ServeHTTP(recorder, modifiedRequest) - respBody, err := ioutil.ReadAll(recorder.Body) if err != nil { return nil, err @@ -114,6 +113,6 @@ func (c *controller) handler(request *web.Request) (*web.Response, error) { Header: recorder.HeaderMap, Body: respBody, } - logrus.Debugf("Service broker replied with status %d", resp.StatusCode) + logger.Debugf("Service broker replied with status %d", resp.StatusCode) return resp, nil } diff --git a/vendor/github.com/Peripli/service-manager/api/osb/transport.go b/vendor/github.com/Peripli/service-manager/api/osb/transport.go index f86d3e8b..9277ca0c 100644 --- a/vendor/github.com/Peripli/service-manager/api/osb/transport.go +++ b/vendor/github.com/Peripli/service-manager/api/osb/transport.go @@ -1,14 +1,15 @@ package osb import ( + "context" "net/http" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/security" "github.com/Peripli/service-manager/storage" - "github.com/sirupsen/logrus" -) + ) // BrokerTransport provides handler for the Service Manager OSB business logic type BrokerTransport struct { @@ -25,15 +26,15 @@ func (bt *BrokerTransport) RoundTrip(request *http.Request) (*http.Response, err } // Broker obtains the broker coordinates (auth and URL) -func (bt *BrokerTransport) Broker(brokerID string) (*types.Broker, error) { - broker, err := bt.BrokerStorage.Get(brokerID) +func (bt *BrokerTransport) Broker(ctx context.Context, brokerID string) (*types.Broker, error) { + broker, err := bt.BrokerStorage.Get(ctx, brokerID) if err != nil { - logrus.Debugf("Broker with id %s not found in storage", brokerID) + log.D().Debugf("Broker with id %s not found in storage", brokerID) return nil, util.HandleStorageError(err, "broker", brokerID) } password := broker.Credentials.Basic.Password - plaintextPassword, err := bt.Encrypter.Decrypt([]byte(password)) + plaintextPassword, err := bt.Encrypter.Decrypt(ctx, []byte(password)) if err != nil { return nil, err } diff --git a/vendor/github.com/Peripli/service-manager/api/platform/platform_controller.go b/vendor/github.com/Peripli/service-manager/api/platform/platform_controller.go index a5fda249..114e6e87 100644 --- a/vendor/github.com/Peripli/service-manager/api/platform/platform_controller.go +++ b/vendor/github.com/Peripli/service-manager/api/platform/platform_controller.go @@ -20,38 +20,42 @@ import ( "net/http" "time" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/security" "github.com/Peripli/service-manager/storage" "github.com/gofrs/uuid" - "github.com/sirupsen/logrus" ) -const reqPlatformID = "platform_id" +const ( + reqPlatformID = "platform_id" +) // Controller platform controller type Controller struct { PlatformStorage storage.Platform - Encrypter security.Encrypter + Encrypter security.Encrypter } var _ web.Controller = &Controller{} // createPlatform handler for POST /v1/platforms -func (c *Controller) createPlatform(request *web.Request) (*web.Response, error) { - logrus.Debug("Creating new platform") +func (c *Controller) createPlatform(r *web.Request) (*web.Response, error) { + ctx := r.Context() + logger := log.C(ctx) + logger.Debug("Creating new platform") platform := &types.Platform{} - if err := util.BytesToObject(request.Body, platform); err != nil { + if err := util.BytesToObject(r.Body, platform); err != nil { return nil, err } if platform.ID == "" { UUID, err := uuid.NewV4() if err != nil { - logrus.Error("Could not generate GUID") + logger.Error("Could not generate GUID") return nil, err } platform.ID = UUID.String() @@ -62,18 +66,18 @@ func (c *Controller) createPlatform(request *web.Request) (*web.Response, error) credentials, err := types.GenerateCredentials() if err != nil { - logrus.Error("Could not generate credentials for platform") + logger.Error("Could not generate credentials for platform") return nil, err } plainPassword := credentials.Basic.Password - transformedPassword, err := c.Encrypter.Encrypt([]byte(plainPassword)) + transformedPassword, err := c.Encrypter.Encrypt(ctx, []byte(plainPassword)) if err != nil { return nil, err } credentials.Basic.Password = string(transformedPassword) platform.Credentials = credentials - if err := c.PlatformStorage.Create(platform); err != nil { + if err := c.PlatformStorage.Create(ctx, platform); err != nil { return nil, util.HandleStorageError(err, "platform", platform.ID) } platform.Credentials.Basic.Password = plainPassword @@ -81,11 +85,12 @@ func (c *Controller) createPlatform(request *web.Request) (*web.Response, error) } // getPlatform handler for GET /v1/platforms/:platform_id -func (c *Controller) getPlatform(request *web.Request) (*web.Response, error) { - platformID := request.PathParams[reqPlatformID] - logrus.Debugf("Getting platform with id %s", platformID) +func (c *Controller) getPlatform(r *web.Request) (*web.Response, error) { + platformID := r.PathParams[reqPlatformID] + ctx := r.Context() + log.C(ctx).Debugf("Getting platform with id %s", platformID) - platform, err := c.PlatformStorage.Get(platformID) + platform, err := c.PlatformStorage.Get(ctx, platformID) if err = util.HandleStorageError(err, "platform", platformID); err != nil { return nil, err } @@ -94,9 +99,10 @@ func (c *Controller) getPlatform(request *web.Request) (*web.Response, error) { } // getAllPlatforms handler for GET /v1/platforms -func (c *Controller) getAllPlatforms(request *web.Request) (*web.Response, error) { - logrus.Debug("Getting all platforms") - platforms, err := c.PlatformStorage.GetAll() +func (c *Controller) getAllPlatforms(r *web.Request) (*web.Response, error) { + ctx := r.Context() + log.C(ctx).Debug("Getting all platforms") + platforms, err := c.PlatformStorage.GetAll(ctx) if err != nil { return nil, err } @@ -113,11 +119,12 @@ func (c *Controller) getAllPlatforms(request *web.Request) (*web.Response, error } // deletePlatform handler for DELETE /v1/platforms/:platform_id -func (c *Controller) deletePlatform(request *web.Request) (*web.Response, error) { - platformID := request.PathParams[reqPlatformID] - logrus.Debugf("Deleting platform with id %s", platformID) +func (c *Controller) deletePlatform(r *web.Request) (*web.Response, error) { + platformID := r.PathParams[reqPlatformID] + ctx := r.Context() + log.C(ctx).Debugf("Deleting platform with id %s", platformID) - if err := c.PlatformStorage.Delete(platformID); err != nil { + if err := c.PlatformStorage.Delete(ctx, platformID); err != nil { return nil, util.HandleStorageError(err, "platform", platformID) } @@ -126,18 +133,19 @@ func (c *Controller) deletePlatform(request *web.Request) (*web.Response, error) } // updatePlatform handler for PATCH /v1/platforms/:platform_id -func (c *Controller) patchPlatform(request *web.Request) (*web.Response, error) { - platformID := request.PathParams[reqPlatformID] - logrus.Debugf("Updating platform with id %s", platformID) +func (c *Controller) patchPlatform(r *web.Request) (*web.Response, error) { + platformID := r.PathParams[reqPlatformID] + ctx := r.Context() + log.C(ctx).Debugf("Updating platform with id %s", platformID) - platform, err := c.PlatformStorage.Get(platformID) + platform, err := c.PlatformStorage.Get(ctx, platformID) if err != nil { return nil, util.HandleStorageError(err, "platform", platformID) } createdAt := platform.CreatedAt - if err := util.BytesToObject(request.Body, platform); err != nil { + if err := util.BytesToObject(r.Body, platform); err != nil { return nil, err } @@ -145,7 +153,7 @@ func (c *Controller) patchPlatform(request *web.Request) (*web.Response, error) platform.CreatedAt = createdAt platform.UpdatedAt = time.Now().UTC() - if err := c.PlatformStorage.Update(platform); err != nil { + if err := c.PlatformStorage.Update(ctx, platform); err != nil { return nil, util.HandleStorageError(err, "platform", platformID) } diff --git a/vendor/github.com/Peripli/service-manager/cf/env.go b/vendor/github.com/Peripli/service-manager/cf/env.go index 7bb6733f..694097f4 100644 --- a/vendor/github.com/Peripli/service-manager/cf/env.go +++ b/vendor/github.com/Peripli/service-manager/cf/env.go @@ -17,13 +17,12 @@ package cf import ( - "fmt" - + "fmt" "os" "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/pkg/log" "github.com/cloudfoundry-community/go-cfenv" - "github.com/sirupsen/logrus" "github.com/spf13/cast" ) @@ -39,7 +38,7 @@ func SetCFOverrides(env env.Environment) error { pgServiceName := cast.ToString(env.Get("storage.name")) if pgServiceName == "" { - logrus.Warning("No PostgreSQL service name found") + log.D().Warning("No PostgreSQL service name found") return nil } service, err := cfEnv.Services.WithName(pgServiceName) diff --git a/vendor/github.com/Peripli/service-manager/deployment/cf/manifest.yml b/vendor/github.com/Peripli/service-manager/deployment/cf/manifest.yml index 755b747d..fdd17795 100644 --- a/vendor/github.com/Peripli/service-manager/deployment/cf/manifest.yml +++ b/vendor/github.com/Peripli/service-manager/deployment/cf/manifest.yml @@ -4,7 +4,7 @@ applications: buildpack: go_buildpack memory: 64M services: - - + - env: GOVERSION: go1.10 GOPACKAGENAME: github.com/Peripli/service-manager diff --git a/vendor/github.com/Peripli/service-manager/docs/plugins.md b/vendor/github.com/Peripli/service-manager/docs/plugins.md index a12baf36..147e483a 100644 --- a/vendor/github.com/Peripli/service-manager/docs/plugins.md +++ b/vendor/github.com/Peripli/service-manager/docs/plugins.md @@ -1,7 +1,7 @@ # Filters and Plugins The main extension points of the service manager are filters, plugins and controllers. The -interfaces that need to be implement in order to provide an extension point can be found +interfaces that need to be implemented in order to provide an extension point can be found in the `pkg/web` package. ## Filters @@ -9,7 +9,7 @@ in the `pkg/web` package. Filters provide means to intercept any HTTP request to the Service Manager. It allows adding custom logic before the request reaches the actual handler (HTTP Endpoint logic) and also before it returns the response. Filters can either propagate a request to the next filter -in the chain or stop the request and write their own response +in the chain or stop the request and write their own response. Service Manager HTTP endpoints are described in the [API Specification](https://github.com/Peripli/specification/blob/master/api.md). diff --git a/vendor/github.com/Peripli/service-manager/pkg/env/env.go b/vendor/github.com/Peripli/service-manager/pkg/env/env.go index 989957f0..ac6ffe46 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/env/env.go +++ b/vendor/github.com/Peripli/service-manager/pkg/env/env.go @@ -17,16 +17,14 @@ package env import ( + "flag" "fmt" + "os" "reflect" "strings" - "os" - - "flag" - + "github.com/Peripli/service-manager/pkg/log" "github.com/fatih/structs" - "github.com/sirupsen/logrus" "github.com/spf13/cast" "github.com/spf13/pflag" "github.com/spf13/viper" @@ -75,7 +73,7 @@ func EmptyFlagSet() *pflag.FlagSet { return set } -//CreatePFlags Creates pflags for the value structure and adds them in the provided set +// CreatePFlags Creates pflags for the value structure and adds them in the provided set func CreatePFlags(set *pflag.FlagSet, value interface{}) { properties := make(map[string]interface{}) traverseFields(value, "", properties) @@ -101,7 +99,7 @@ func New(set *pflag.FlagSet) (*ViperEnv, error) { set.VisitAll(func(flag *pflag.Flag) { if err := v.BindPFlag(flag.Name, flag); err != nil { - logrus.Panic(err) + log.D().Panic(err) } }) @@ -166,7 +164,7 @@ func (v *ViperEnv) setupConfigFile() error { if err := v.Viper.ReadInConfig(); err != nil { if err, ok := err.(viper.ConfigFileNotFoundError); ok { - logrus.Info("Config File was not found: ", err) + log.D().Info("Config File was not found: ", err) return nil } return fmt.Errorf("could not read configuration cfg: %s", err) diff --git a/vendor/github.com/Peripli/service-manager/pkg/log/context.go b/vendor/github.com/Peripli/service-manager/pkg/log/context.go new file mode 100644 index 00000000..d9cd8f23 --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/pkg/log/context.go @@ -0,0 +1,154 @@ +/* + * Copyright 2018 The Service Manager Authors + * + * 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. + */ + +package log + +import ( + "context" + "fmt" + "os" + "sync" + + "github.com/onrik/logrus/filename" + "github.com/sirupsen/logrus" +) + +type logKey struct{} + +var ( + supportedFormatters = map[string]logrus.Formatter{ + "json": &logrus.JSONFormatter{}, + "text": &logrus.TextFormatter{}, + } + regMutex = sync.Mutex{} + once = sync.Once{} + defaultEntry = logrus.NewEntry(logrus.StandardLogger()) + // C is an alias for ForContext + C = ForContext + // D is an alias for Default + D = Default +) + +const ( + // FieldComponentName is the key of the component field in the log message. + FieldComponentName = "component" + // FieldCorrelationID is the key of the correlation id field in the log message. + FieldCorrelationID = "correlation_id" +) + +// Settings type to be loaded from the environment +type Settings struct { + Level string + Format string +} + +// DefaultSettings returns default values for Log settings +func DefaultSettings() *Settings { + return &Settings{ + Level: "debug", + Format: "text", + } +} + +// Validate validates the logging settings +func (s *Settings) Validate() error { + if len(s.Level) == 0 { + return fmt.Errorf("validate Settings: LogLevel missing") + } + if len(s.Format) == 0 { + return fmt.Errorf("validate Settings: LogFormat missing") + } + return nil +} + +// Configure creates a new context with a logger using the provided settings. +func Configure(ctx context.Context, settings *Settings) context.Context { + once.Do(func() { + level, err := logrus.ParseLevel(settings.Level) + if err != nil { + panic(fmt.Sprintf("Could not parse log level configuration: %s", err)) + } + formatter, ok := supportedFormatters[settings.Format] + if !ok { + panic(fmt.Sprintf("Invalid log format: %s", settings.Format)) + } + logger := &logrus.Logger{ + Formatter: formatter, + Level: level, + Out: os.Stdout, + Hooks: make(logrus.LevelHooks), + } + hook := filename.NewHook() + hook.Field = FieldComponentName + logger.AddHook(hook) + defaultEntry = logrus.NewEntry(logger) + defaultEntry = defaultEntry.WithField(FieldCorrelationID, "-") + }) + return ContextWithLogger(ctx, defaultEntry) +} + +// ForContext retrieves the current logger from the context. +func ForContext(ctx context.Context) *logrus.Entry { + entry := ctx.Value(logKey{}) + if entry == nil { + // copy so that changes to the new entry do not reflect the default entry + entry = copyEntry(defaultEntry) + } + return entry.(*logrus.Entry) +} + +// Default returns the default logger +func Default() *logrus.Entry { + return ForContext(context.Background()) +} + +// ContextWithLogger returns a new context with the provided logger. +func ContextWithLogger(ctx context.Context, entry *logrus.Entry) context.Context { + return context.WithValue(ctx, logKey{}, entry) +} + +// RegisterFormatter registers a new logrus Formatter with the given name. +// Returns an error if there is a formatter with the same name. +func RegisterFormatter(name string, formatter logrus.Formatter) error { + regMutex.Lock() + defer regMutex.Unlock() + if _, exists := supportedFormatters[name]; exists { + return fmt.Errorf("Formatter with name %s is already registered", name) + } + supportedFormatters[name] = formatter + return nil +} + +// AddHook adds a hook to all loggers +func AddHook(hook logrus.Hook) { + defaultEntry.Logger.AddHook(hook) +} + +func copyEntry(entry *logrus.Entry) *logrus.Entry { + return &logrus.Entry{ + Logger: &logrus.Logger{ + Level: entry.Logger.Level, + Formatter: entry.Logger.Formatter, + Hooks: entry.Logger.Hooks, + Out: entry.Logger.Out, + }, + Level: entry.Level, + Data: entry.Data, + Time: entry.Time, + Message: entry.Message, + Buffer: entry.Buffer, + } +} diff --git a/vendor/github.com/Peripli/service-manager/pkg/log/log_test.go b/vendor/github.com/Peripli/service-manager/pkg/log/context_test.go similarity index 69% rename from vendor/github.com/Peripli/service-manager/pkg/log/log_test.go rename to vendor/github.com/Peripli/service-manager/pkg/log/context_test.go index be59077c..c595307a 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/log/log_test.go +++ b/vendor/github.com/Peripli/service-manager/pkg/log/context_test.go @@ -18,7 +18,10 @@ package log import ( + "context" + "fmt" "os" + "sync" "testing" . "github.com/onsi/ginkgo" @@ -64,7 +67,23 @@ var _ = Describe("log", func() { expectOutput("\"msg\":\"Test\"", "json") }) }) + }) + Describe("Register formatter", func() { + Context("When a formatter with such name is not registered", func() { + It("Registers it", func() { + name := "formatter_name" + err := RegisterFormatter(name, &logrus.TextFormatter{}) + Expect(err).ToNot(HaveOccurred()) + Expect(supportedFormatters[name]).ToNot(BeNil()) + }) + }) + Context("When a formatter with such name is registered", func() { + It("Returns an error", func() { + err := RegisterFormatter("text", &logrus.TextFormatter{}) + Expect(err).To(HaveOccurred()) + }) + }) }) }) @@ -79,19 +98,26 @@ func (wr *MyWriter) Write(p []byte) (n int, err error) { func expectPanic(settings *Settings) { wrapper := func() { - SetupLogging(settings) + configure(settings) } Expect(wrapper).To(Panic()) } func expectOutput(substring string, logFormat string) { w := &MyWriter{} - SetupLogging(&Settings{ + ctx := configure(&Settings{ Level: "debug", Format: logFormat, }) - logrus.SetOutput(w) - defer logrus.SetOutput(os.Stderr) // return default output - logrus.Debug("Test") + entry := ForContext(ctx) + entry.Logger.SetOutput(w) + defer entry.Logger.SetOutput(os.Stderr) // return default output + entry.Debug("Test") + fmt.Println(w.Data) Expect(w.Data).To(ContainSubstring(substring)) } + +func configure(settings *Settings) context.Context { + once = sync.Once{} + return Configure(context.TODO(), settings) +} diff --git a/vendor/github.com/Peripli/service-manager/pkg/log/log.go b/vendor/github.com/Peripli/service-manager/pkg/log/log.go deleted file mode 100644 index 811d471a..00000000 --- a/vendor/github.com/Peripli/service-manager/pkg/log/log.go +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2018 The Service Manager Authors - * - * 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. - */ - -// Package log contains logic for setting up logging for SM -package log - -import ( - "fmt" - - "github.com/Peripli/service-manager/pkg/env" - "github.com/sirupsen/logrus" -) - -// Settings type to be loaded from the environment -type Settings struct { - Level string - Format string -} - -// DefaultSettings returns default values for Log settings -func DefaultSettings() *Settings { - return &Settings{ - Level: "debug", - Format: "text", - } -} - -// NewSettings returns Server settings for the given enrivonment -func NewSettings(env env.Environment) (*Settings, error) { - config := &Settings{} - if err := env.Unmarshal(config); err != nil { - return nil, err - } - - return config, nil -} - -// Validate validates the logging settings -func (s *Settings) Validate() error { - if len(s.Level) == 0 { - return fmt.Errorf("validate Settings: LogLevel missing") - } - if len(s.Format) == 0 { - return fmt.Errorf("validate Settings: LogFormat missing") - } - return nil -} - -var supportedFormatters = map[string]logrus.Formatter{ - "json": &logrus.JSONFormatter{}, - "text": &logrus.TextFormatter{}, -} - -// SetupLogging configures logrus logging using the provided settings -func SetupLogging(settings *Settings) { - level, err := logrus.ParseLevel(settings.Level) - if err != nil { - panic(fmt.Sprintf("Could not parse log level configuration: %s", err.Error())) - } - logrus.SetLevel(level) - formatter, ok := supportedFormatters[settings.Format] - if !ok { - panic(fmt.Sprintf("Invalid log format: %s", settings.Format)) - } - logrus.SetFormatter(formatter) -} diff --git a/vendor/github.com/Peripli/service-manager/pkg/log/request.go b/vendor/github.com/Peripli/service-manager/pkg/log/request.go new file mode 100644 index 00000000..e984b3d2 --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/pkg/log/request.go @@ -0,0 +1,44 @@ +/* + * Copyright 2018 The Service Manager Authors + * + * 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. + */ + +package log + +import ( + "net/http" + + "github.com/Peripli/service-manager/pkg/util/slice" + "github.com/gofrs/uuid" +) + +// CorrelationIDHeaders are the headers whose values will be taken as a correlation id for incoming requests +var CorrelationIDHeaders = []string{"X-Correlation-ID", "X-CorrelationID", "X-ForRequest-ID"} + +// CorrelationIDForRequest returns checks the http headers for any of the supported correlation id headers. +// The first that matches is taken as the correlation id. If none exists a new one is generated. +func CorrelationIDForRequest(request *http.Request) string { + for key, val := range request.Header { + if slice.StringsAnyEquals(CorrelationIDHeaders, key) { + return val[0] + } + } + newCorrelationID := "" + uuids, err := uuid.NewV4() + if err == nil { + newCorrelationID = uuids.String() + request.Header.Set(CorrelationIDHeaders[0], newCorrelationID) + } + return newCorrelationID +} diff --git a/vendor/github.com/Peripli/service-manager/pkg/server/server.go b/vendor/github.com/Peripli/service-manager/pkg/server/server.go index d9eabf3f..8d127435 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/server/server.go +++ b/vendor/github.com/Peripli/service-manager/pkg/server/server.go @@ -26,9 +26,9 @@ import ( "github.com/Peripli/service-manager/api" "github.com/Peripli/service-manager/pkg/env" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/web" "github.com/gorilla/mux" - "github.com/sirupsen/logrus" ) // Settings type to be loaded from the environment @@ -77,7 +77,6 @@ type Server struct { *mux.Router Config *Settings - api *web.API } // New creates a new server with the provided REST api configuration and server configuration @@ -87,9 +86,18 @@ func New(config *Settings, api *web.API) *Server { registerControllers(api, router) return &Server{ - Config: config, Router: router, - api: api, + Config: config, + } +} + +func registerControllers(API *web.API, router *mux.Router) { + for _, ctrl := range API.Controllers { + for _, route := range ctrl.Routes() { + log.D().Debugf("Registering endpoint: %s %s", route.Endpoint.Method, route.Endpoint.Path) + handler := web.Filters(API.Filters).ChainMatching(route) + router.Handle(route.Endpoint.Path, api.NewHTTPHandler(handler)).Methods(route.Endpoint.Method) + } } } @@ -107,23 +115,13 @@ func (s *Server) Run(ctx context.Context) { startServer(ctx, handler, s.Config.ShutdownTimeout) } -func registerControllers(API *web.API, router *mux.Router) { - for _, ctrl := range API.Controllers { - for _, route := range ctrl.Routes() { - logrus.Debugf("Registering endpoint: %s %s", route.Endpoint.Method, route.Endpoint.Path) - handler := web.Filters(API.Filters).ChainMatching(route) - router.Handle(route.Endpoint.Path, api.NewHTTPHandler(handler)).Methods(route.Endpoint.Method) - } - } -} - func startServer(ctx context.Context, server *http.Server, shutdownTimeout time.Duration) { go gracefulShutdown(ctx, server, shutdownTimeout) - logrus.Infof("Listening on %s", server.Addr) + log.C(ctx).Infof("Listening on %s", server.Addr) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { - logrus.Fatal(err) + log.C(ctx).Fatal(err) } } @@ -132,14 +130,15 @@ func gracefulShutdown(ctx context.Context, server *http.Server, shutdownTimeout c, cancel := context.WithTimeout(context.Background(), shutdownTimeout) defer cancel() - logrus.Debugf("Shutdown with timeout: %s", shutdownTimeout) + logger := log.C(ctx) + logger.Debugf("Shutdown with timeout: %s", shutdownTimeout) if err := server.Shutdown(c); err != nil { - logrus.Error("Error: ", err) + logger.Error("Error: ", err) if err := server.Close(); err != nil { - logrus.Error("Error: ", err) + logger.Error("Error: ", err) } } else { - logrus.Debug("Server stopped") + logger.Debug("Server stopped") } } diff --git a/vendor/github.com/Peripli/service-manager/pkg/sm/sm.go b/vendor/github.com/Peripli/service-manager/pkg/sm/sm.go index 818f823a..067c519a 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/sm/sm.go +++ b/vendor/github.com/Peripli/service-manager/pkg/sm/sm.go @@ -26,6 +26,7 @@ import ( "github.com/Peripli/service-manager/api" "github.com/Peripli/service-manager/config" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/server" "github.com/Peripli/service-manager/security" "github.com/Peripli/service-manager/storage" @@ -34,9 +35,7 @@ import ( "github.com/Peripli/service-manager/api/filters" "github.com/Peripli/service-manager/cf" "github.com/Peripli/service-manager/pkg/env" - "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/web" - "github.com/sirupsen/logrus" "github.com/spf13/pflag" ) @@ -88,7 +87,7 @@ func New(ctx context.Context, env env.Environment) *ServiceManagerBuilder { http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: cfg.API.SkipSSLValidation} // setup logging - log.SetupLogging(cfg.Log) + ctx = log.Configure(ctx, cfg.Log) // setup smStorage smStorage, err := storage.Use(ctx, postgres.Storage, cfg.Storage.URI, []byte(cfg.API.Security.EncryptionKey)) @@ -142,21 +141,22 @@ func initializeSecureStorage(ctx context.Context, secureStorage storage.Security return err } keyFetcher := secureStorage.Fetcher() - encryptionKey, err := keyFetcher.GetEncryptionKey() + encryptionKey, err := keyFetcher.GetEncryptionKey(ctx) if err != nil { return err } if len(encryptionKey) == 0 { - logrus.Debug("No encryption key is present. Generating new one...") + logger := log.C(ctx) + logger.Debug("No encryption key is present. Generating new one...") newEncryptionKey := make([]byte, 32) if _, err := rand.Read(newEncryptionKey); err != nil { return fmt.Errorf("Could not generate encryption key: %v", err) } keySetter := secureStorage.Setter() - if err := keySetter.SetEncryptionKey(newEncryptionKey); err != nil { + if err := keySetter.SetEncryptionKey(ctx, newEncryptionKey); err != nil { return err } - logrus.Debug("Successfully generated new encryption key") + logger.Debug("Successfully generated new encryption key") } - return secureStorage.Unlock() + return secureStorage.Unlock(ctx) } diff --git a/vendor/github.com/Peripli/service-manager/pkg/util/api.go b/vendor/github.com/Peripli/service-manager/pkg/util/api.go index dfb6e874..63e1292b 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/util/api.go +++ b/vendor/github.com/Peripli/service-manager/pkg/util/api.go @@ -18,14 +18,13 @@ package util import ( - "encoding/json" + "encoding/json" "net/http" - "time" - "strings" + "time" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/web" - "github.com/sirupsen/logrus" ) var ( @@ -93,7 +92,7 @@ func BytesToObject(bytes []byte, object interface{}) error { func unmarshal(body []byte, value interface{}) error { err := json.Unmarshal(body, value) if err != nil { - logrus.Error("Failed to decode request body: ", err) + log.D().Error("Failed to decode request body: ", err) return &HTTPError{ ErrorType: "BadRequest", Description: "Failed to decode request body", diff --git a/vendor/github.com/Peripli/service-manager/pkg/util/client.go b/vendor/github.com/Peripli/service-manager/pkg/util/client.go index 96863bf3..ee8eb5e7 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/util/client.go +++ b/vendor/github.com/Peripli/service-manager/pkg/util/client.go @@ -18,20 +18,20 @@ package util import ( "bytes" + "context" "encoding/json" "io" - "net/http" - "io/ioutil" + "net/http" - "github.com/sirupsen/logrus" + "github.com/Peripli/service-manager/pkg/log" ) // DoRequestFunc is an alias for any function that takes an http request and returns a response and error type DoRequestFunc func(request *http.Request) (*http.Response, error) // SendRequest sends a request to the specified client and the provided URL with the specified parameters and body. -func SendRequest(doRequest DoRequestFunc, method, url string, params map[string]string, body interface{}) (*http.Response, error) { +func SendRequest(ctx context.Context, doRequest DoRequestFunc, method, url string, params map[string]string, body interface{}) (*http.Response, error) { var bodyReader io.Reader if body != nil { @@ -55,7 +55,14 @@ func SendRequest(doRequest DoRequestFunc, method, url string, params map[string] request.URL.RawQuery = q.Encode() } - logrus.Debugf("Sending a request to %s", request.URL) + request = request.WithContext(ctx) + logger := log.C(ctx) + correlationID, exists := logger.Data[log.FieldCorrelationID].(string) + if exists { + request.Header.Set(log.CorrelationIDHeaders[0], correlationID) + } + + logger.Debugf("Sending a request to %s", request.URL) return doRequest(request) } @@ -63,7 +70,7 @@ func SendRequest(doRequest DoRequestFunc, method, url string, params map[string] func BodyToBytes(closer io.ReadCloser) ([]byte, error) { defer func() { if err := closer.Close(); err != nil { - logrus.Errorf("ReadCloser couldn't be closed", err) + log.D().Errorf("ReadCloser couldn't be closed: %v", err) } }() diff --git a/vendor/github.com/Peripli/service-manager/pkg/util/client_test.go b/vendor/github.com/Peripli/service-manager/pkg/util/client_test.go index c130933d..76b03c50 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/util/client_test.go +++ b/vendor/github.com/Peripli/service-manager/pkg/util/client_test.go @@ -17,14 +17,16 @@ package util_test import ( - "net/http" - + "context" "fmt" + "net/http" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/util" "github.com/Peripli/service-manager/test/common" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" + "github.com/sirupsen/logrus" ) var _ = Describe("Client Utils", func() { @@ -46,7 +48,7 @@ var _ = Describe("Client Utils", func() { body := testTypeErrorMarshaling{ Field: "Value", } - _, err := util.SendRequest(requestFunc, "GET", "http://example.com", map[string]string{}, body) + _, err := util.SendRequest(context.TODO(), requestFunc, "GET", "http://example.com", map[string]string{}, body) Expect(err).Should(HaveOccurred()) }) @@ -55,7 +57,7 @@ var _ = Describe("Client Utils", func() { Context("when method is invalid", func() { It("returns an error", func() { - _, err := util.SendRequest(requestFunc, "?+?.>", "http://example.com", map[string]string{}, nil) + _, err := util.SendRequest(context.TODO(), requestFunc, "?+?.>", "http://example.com", map[string]string{}, nil) Expect(err).Should(HaveOccurred()) }) @@ -77,8 +79,28 @@ var _ = Describe("Client Utils", func() { reaction.Err = nil reaction.Status = http.StatusOK - resp, err := util.SendRequest(requestFunc, "POST", "http://example.com", params, body) + resp, err := util.SendRequest(context.TODO(), requestFunc, "POST", "http://example.com", params, body) + + Expect(err).ShouldNot(HaveOccurred()) + Expect(resp.StatusCode).To(Equal(http.StatusOK)) + }) + }) + + Context("When context has correlation id", func() { + It("should attach it as header", func() { + expectations.URL = "http://example.com" + + reaction.Err = nil + reaction.Status = http.StatusOK + + expectedCorrelationID := "correlation-id" + entry := logrus.NewEntry(logrus.StandardLogger()) + entry = entry.WithField(log.FieldCorrelationID, expectedCorrelationID) + ctx := log.ContextWithLogger(context.TODO(), entry) + resp, err := util.SendRequest(ctx, requestFunc, "GET", "http://example.com", nil, nil) + correlationID := resp.Request.Header.Get(log.CorrelationIDHeaders[0]) + Expect(correlationID).To(Equal(expectedCorrelationID)) Expect(err).ShouldNot(HaveOccurred()) Expect(resp.StatusCode).To(Equal(http.StatusOK)) }) @@ -94,7 +116,7 @@ var _ = Describe("Client Utils", func() { reaction.Status = http.StatusOK reaction.Body = `{"field":"value"}` - resp, err = util.SendRequest(requestFunc, "POST", "http://example.com", map[string]string{}, nil) + resp, err = util.SendRequest(context.TODO(), requestFunc, "POST", "http://example.com", map[string]string{}, nil) Expect(err).ShouldNot(HaveOccurred()) }) diff --git a/vendor/github.com/Peripli/service-manager/pkg/util/errors.go b/vendor/github.com/Peripli/service-manager/pkg/util/errors.go index 6003b435..3da5d58c 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/util/errors.go +++ b/vendor/github.com/Peripli/service-manager/pkg/util/errors.go @@ -17,12 +17,11 @@ package util import ( + "errors" "fmt" "net/http" - "errors" - - "github.com/sirupsen/logrus" + "github.com/Peripli/service-manager/pkg/log" ) // HTTPError is an error type that provides error details compliant with the Open Service Broker API conventions @@ -40,12 +39,13 @@ func (e *HTTPError) Error() string { // WriteError sends a JSON containing the error to the response writer func WriteError(err error, writer http.ResponseWriter) { var respError *HTTPError + logger := log.D() switch t := err.(type) { case *HTTPError: - logrus.Debug(err) + logger.Debug(err) respError = t default: - logrus.Error(err) + logger.Error(err) respError = &HTTPError{ ErrorType: "InternalError", Description: "Internal server error", @@ -55,13 +55,14 @@ func WriteError(err error, writer http.ResponseWriter) { sendErr := WriteJSON(writer, respError.StatusCode, respError) if sendErr != nil { - logrus.Errorf("Could not write error to response: %v", sendErr) + logger.Errorf("Could not write error to response: %v", sendErr) } } // HandleResponseError builds at HttpErrorResponse from the given response. func HandleResponseError(response *http.Response) error { - logrus.Errorf("Handling failure response: returned status code %d", response.StatusCode) + logger := log.D() + logger.Errorf("Handling failure response: returned status code %d", response.StatusCode) httpErr := &HTTPError{ StatusCode: response.StatusCode, } @@ -72,7 +73,7 @@ func HandleResponseError(response *http.Response) error { } if err := BytesToObject(body, httpErr); err != nil || httpErr.Description == "" { - logrus.Debugf("Failure response with status code %d is not an HTTPError. Error converting body: %v. Default err will be returned.", response.StatusCode, err) + logger.Debugf("Failure response with status code %d is not an HTTPError. Error converting body: %v. Default err will be returned.", response.StatusCode, err) return fmt.Errorf("StatusCode: %d Body: %s", response.StatusCode, body) } return httpErr diff --git a/vendor/github.com/Peripli/service-manager/pkg/util/interrupts.go b/vendor/github.com/Peripli/service-manager/pkg/util/interrupts.go index 520c009c..062f5263 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/util/interrupts.go +++ b/vendor/github.com/Peripli/service-manager/pkg/util/interrupts.go @@ -5,7 +5,7 @@ import ( "os" "os/signal" - "github.com/sirupsen/logrus" + "github.com/Peripli/service-manager/pkg/log" ) // HandleInterrupts handles process signal interrupts @@ -16,7 +16,7 @@ func HandleInterrupts() (context.Context, context.CancelFunc) { go func() { select { case <-term: - logrus.Error("Received OS interrupt, exiting gracefully...") + log.C(ctx).Error("Received OS interrupt, exiting gracefully...") cancel() case <-ctx.Done(): return diff --git a/vendor/github.com/Peripli/service-manager/pkg/web/api.go b/vendor/github.com/Peripli/service-manager/pkg/web/api.go index fa2740e5..d048037c 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/web/api.go +++ b/vendor/github.com/Peripli/service-manager/pkg/web/api.go @@ -21,8 +21,8 @@ package web import ( "net/http" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/util/slice" - "github.com/sirupsen/logrus" ) // API is the primary point for REST API registration @@ -34,7 +34,7 @@ type API struct { Filters []Filter } -// pluginSegment represents one piece of a web.invalidPlugin. Each web.invalidPlugin is decomposed into as many plugin segments as +// pluginSegment represents one piece of a web.Plugin. Each web.Plugin is decomposed into as many plugin segments as // the count of OSB operations it provides. Each pluginSegment is treated as a web.Filter. type pluginSegment struct { NameValue string @@ -73,9 +73,7 @@ func (dp *pluginSegment) FilterMatchers() []FilterMatcher { // RegisterControllers registers a set of controllers func (api *API) RegisterControllers(controllers ...Controller) { - for _, controller := range controllers { - api.Controllers = append(api.Controllers, controller) - } + api.Controllers = append(api.Controllers, controllers...) } // RegisterFilters registers a set of filters @@ -84,33 +82,37 @@ func (api *API) RegisterFilters(filters ...Filter) { api.Filters = append(api.Filters, filters...) } -// RegisterFilterBefore registers the specified filter before the one with the given name. +// RegisterFiltersBefore registers the specified filters before the one with the given name. // If for some routes, the filter with the given name does not match the routes of the provided filter, then -// the filter will be registered at the place at which the filter with this name would have been, had it been +// the filters will be registered at the place at which the filter with this name would have been, had it been // configured to match route. -func (api *API) RegisterFilterBefore(beforeFilterName string, filter Filter) { - logrus.Debugf("Registering filter %s before %s", filter.Name(), beforeFilterName) - api.validateFilters(filter) - api.registerFilterRelatively(beforeFilterName, filter, func(beforeFilterPosition int) int { - return beforeFilterPosition - }) +func (api *API) RegisterFiltersBefore(beforeFilterName string, filters ...Filter) { + for _, filter := range filters { + log.D().Debugf("Registering filter %s before %s", filter.Name(), beforeFilterName) + api.validateFilters(filter) + api.registerFilterRelatively(beforeFilterName, filter, func(beforeFilterPosition int) int { + return beforeFilterPosition + }) + } } -// RegisterFilterAfter registers the specified filter after the one with the given name. +// RegisterFiltersAfter registers the specified filter after the one with the given name. // If for some routes, the filter with the given name does not match the routes of the provided filter, then // the filter will be registered after the place at which the filter with this name would have been, had it been // configured to match route. -func (api *API) RegisterFilterAfter(afterFilterName string, filter Filter) { - logrus.Debugf("Registering filter %s after %s", filter.Name(), afterFilterName) - api.validateFilters(filter) - api.registerFilterRelatively(afterFilterName, filter, func(filterPosition int) int { - return filterPosition + 1 - }) +func (api *API) RegisterFiltersAfter(afterFilterName string, filters ...Filter) { + for i, filter := range filters { + log.D().Debugf("Registering filter %s after %s", filter.Name(), afterFilterName) + api.validateFilters(filter) + api.registerFilterRelatively(afterFilterName, filter, func(filterPosition int) int { + return filterPosition + 1 + i + }) + } } // ReplaceFilter registers the given filter in the place of the filter with the given name. func (api *API) ReplaceFilter(replacedFilterName string, filter Filter) { - logrus.Debugf("Replacing filter %s with %s", replacedFilterName, filter.Name()) + log.D().Debugf("Replacing filter %s with %s", replacedFilterName, filter.Name()) api.validateFilters(filter) registeredFilterPosition := api.findFilterPosition(replacedFilterName) api.Filters[registeredFilterPosition] = filter @@ -129,7 +131,7 @@ func (api *API) RegisterPlugins(plugins ...Plugin) { for _, plugin := range plugins { registeredFilterNames := api.filterNames(api.Filters) if slice.StringsAnyPrefix(registeredFilterNames, plugin.Name()+":") { - logrus.Panicf("Plugin %s is already registered", plugin.Name()) + log.D().Panicf("Plugin %s is already registered", plugin.Name()) } pluginSegments := api.decomposePluginOrDie(plugin) api.Filters = append(api.Filters, pluginSegments...) @@ -139,16 +141,16 @@ func (api *API) RegisterPlugins(plugins ...Plugin) { func (api *API) validateFilters(filters ...Filter) { newFilterNames := api.filterNames(filters) if slice.StringsAnyEquals(newFilterNames, "") { - logrus.Panicf("Filters cannot have empty names") + log.D().Panicf("Filters cannot have empty names") } registeredFilterNames := api.filterNames(api.Filters) commonFilterNames := slice.StringsIntersection(registeredFilterNames, newFilterNames) if len(commonFilterNames) > 0 { - logrus.Panicf("Filters %q are already registered", commonFilterNames) + log.D().Panicf("Filters %q are already registered", commonFilterNames) } filterNamesWithColon := slice.StringsContaining(newFilterNames, ":") - if len(filterNamesWithColon) > 0 { - logrus.Panicf("Cannot register filters with : in their names. Invalid filter names: %q", filterNamesWithColon) + if len(filterNamesWithColon) > 0 { + log.D().Panicf("Cannot register filters with : in their names. Invalid filter names: %q", filterNamesWithColon) } } @@ -170,7 +172,7 @@ func (api *API) findFilterPosition(filterName string) int { } } if filterPosition < 0 { - logrus.Panicf("Filter with name %s is not found", filterName) + log.D().Panicf("Filter with name %s is not found", filterName) } return filterPosition } @@ -187,7 +189,7 @@ func (api *API) filterNames(filters []Filter) []string { func (api *API) decomposePluginOrDie(plugin Plugin) []Filter { pluginSegments := api.decomposePlugin(plugin) if len(pluginSegments) == 0 { - logrus.Panicf("%T does not implement any plugin operation", plugin) + log.D().Panicf("%T does not implement any plugin operation", plugin) } return pluginSegments } diff --git a/vendor/github.com/Peripli/service-manager/pkg/web/api_test.go b/vendor/github.com/Peripli/service-manager/pkg/web/api_test.go index 29cde550..19a89e96 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/web/api_test.go +++ b/vendor/github.com/Peripli/service-manager/pkg/web/api_test.go @@ -17,7 +17,7 @@ package web_test import ( - "github.com/Peripli/service-manager/pkg/web" + "github.com/Peripli/service-manager/pkg/web" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) @@ -100,21 +100,29 @@ var _ = Describe("API", func() { Context("When filter with such name does not exist", func() { It("Panics", func() { replaceFilter := func() { - api.RegisterFilterBefore("some-filter", &testFilter{"testFilter"}) + api.RegisterFiltersBefore("some-filter", &testFilter{"testFilter"}) } Expect(replaceFilter).To(Panic()) }) }) Context("When filter with such name exists", func() { - It("Adds the filter before it", func() { - filter1 := &testFilter{"testFilter"} + It("Adds a filter before it", func() { + filter1 := &testFilter{"testFilter1"} filter2 := &testFilter{"testFilter2"} filter3 := &testFilter{"testFilter3"} api.RegisterFilters(filter1, filter2) - api.RegisterFilterBefore(filter2.Name(), filter3) - names := filterNames() - Expect(names).To(Equal([]string{filter1.Name(), filter3.Name(), filter2.Name()})) + api.RegisterFiltersBefore(filter2.Name(), filter3) + Expect(filterNames()).To(Equal([]string{filter1.Name(), filter3.Name(), filter2.Name()})) + }) + + It("Adds multiple filters before it", func() { + filter1 := &testFilter{"testFilter1"} + filter2 := &testFilter{"testFilter2"} + filter3 := &testFilter{"testFilter3"} + api.RegisterFilters(filter1) + api.RegisterFiltersBefore(filter1.Name(), filter2, filter3) + Expect(filterNames()).To(Equal([]string{filter2.Name(), filter3.Name(), filter1.Name()})) }) }) }) @@ -123,19 +131,29 @@ var _ = Describe("API", func() { Context("When filter with such name does not exist", func() { It("Panics", func() { replaceFilter := func() { - api.RegisterFilterAfter("some-filter", &testFilter{"testFilter"}) + api.RegisterFiltersAfter("some-filter", &testFilter{"testFilter"}) } Expect(replaceFilter).To(Panic()) }) }) Context("When filter with such name exists", func() { - It("Adds the filter before it", func() { - filter := &testFilter{"testFilter"} - newFilter := &testFilter{"testFilter2"} - api.RegisterFilters(filter) - api.RegisterFilterAfter(filter.Name(), newFilter) - names := filterNames() - Expect(names).To(Equal([]string{filter.Name(), newFilter.Name()})) + It("Adds a filter after it", func() { + filter1 := &testFilter{"testFilter1"} + filter2 := &testFilter{"testFilter2"} + filter3 := &testFilter{"testFilter3"} + api.RegisterFilters(filter1, filter2) + api.RegisterFiltersAfter(filter1.Name(), filter3) + Expect(filterNames()).To(Equal([]string{filter1.Name(), filter3.Name(), filter2.Name()})) + }) + + It("Adds multiple filters after it", func() { + filter1 := &testFilter{"testFilter1"} + filter2 := &testFilter{"testFilter2"} + filter3 := &testFilter{"testFilter3"} + filter4 := &testFilter{"testFilter4"} + api.RegisterFilters(filter1, filter2) + api.RegisterFiltersAfter(filter1.Name(), filter3, filter4) + Expect(filterNames()).To(Equal([]string{filter1.Name(), filter3.Name(), filter4.Name(), filter2.Name()})) }) }) }) diff --git a/vendor/github.com/Peripli/service-manager/pkg/web/filter.go b/vendor/github.com/Peripli/service-manager/pkg/web/filter.go index 3eac7c4a..df6d4b89 100644 --- a/vendor/github.com/Peripli/service-manager/pkg/web/filter.go +++ b/vendor/github.com/Peripli/service-manager/pkg/web/filter.go @@ -17,11 +17,10 @@ package web import ( - "net/http" - "fmt" + "net/http" - "github.com/sirupsen/logrus" + "github.com/Peripli/service-manager/pkg/log" ) // Request contains the original http.Request, path parameters and the raw body @@ -51,7 +50,6 @@ type Response struct { // Named is an interface that objects that need to be identified by a particular name should implement. type Named interface { - // Name returns the string identifier for the object Name() string } @@ -59,7 +57,6 @@ type Named interface { // Handler is an interface that objects can implement to be registered in the SM REST API. //go:generate counterfeiter . Handler type Handler interface { - // Handle processes a Request and returns a corresponding Response or error Handle(req *Request) (resp *Response, err error) } @@ -75,7 +72,6 @@ func (rhf HandlerFunc) Handle(req *Request) (resp *Response, err error) { // Middleware is an interface that objects that should act as filters or plugins need to implement. It intercepts // the request before reaching the final handler and allows during preprocessing and postprocessing. type Middleware interface { - // Run returns a handler that contains the handling logic of the Middleware. The implementation of Run // should invoke next's Handle if the request should be chained to the next Handler. // It may also terminate the request by not invoking the next Handler. @@ -92,7 +88,6 @@ func (mf MiddlewareFunc) Run(req *Request, handler Handler) (*Response, error) { // Matcher allows checking whether an Endpoint matches a particular condition type Matcher interface { - // Matches matches a route against a particular condition Matches(endpoint Endpoint) (bool, error) } @@ -108,7 +103,6 @@ func (m MatcherFunc) Matches(endpoint Endpoint) (bool, error) { // FilterMatcher type represents a set of conditions (Matchers) that need to match if order // for a FilterMatcher to match type FilterMatcher struct { - // Matchers represents a set of conditions that need to be matched Matchers []Matcher } @@ -142,22 +136,23 @@ func (fs Filters) Chain(h Handler) Handler { for i := len(fs) - 1; i >= 0; i-- { i := i - wrappedFilters[i] = HandlerFunc(func(request *Request) (*Response, error) { + wrappedFilters[i] = HandlerFunc(func(r *Request) (*Response, error) { params := map[string]interface{}{ - "path": request.URL.Path, - "method": request.Method, + "path": r.URL.Path, + "method": r.Method, + log.FieldCorrelationID: log.CorrelationIDForRequest(r.Request), } + logger := log.C(r.Context()) + logger.WithFields(params).Debug("Entering Filter: ", fs[i].Name()) - logrus.WithFields(params).Debug("Entering Filter: ", fs[i].Name()) - - resp, err := fs[i].Run(request, wrappedFilters[i+1]) + resp, err := fs[i].Run(r, wrappedFilters[i+1]) params["err"] = err if resp != nil { params["statusCode"] = resp.StatusCode } - logrus.WithFields(params).Debug("Exiting Filter: ", fs[i].Name()) + logger.WithFields(params).Debug("Exiting Filter: ", fs[i].Name()) return resp, err }) @@ -166,7 +161,7 @@ func (fs Filters) Chain(h Handler) Handler { return wrappedFilters[0] } -// Matching returns a subset of Filters that match the specified route +// Matching returns a subset of Filters that match the specified endpoint func (fs Filters) Matching(endpoint Endpoint) Filters { matchedFilters := make([]Filter, 0) matchedNames := make([]string, 0) @@ -194,6 +189,6 @@ func (fs Filters) Matching(endpoint Endpoint) Filters { } } } - logrus.Debugf("Filters for %s %s:%v", endpoint.Method, endpoint.Path, matchedNames) + log.D().Debugf("Filters for %s %s:%v", endpoint.Method, endpoint.Path, matchedNames) return matchedFilters } diff --git a/vendor/github.com/Peripli/service-manager/release-notes.md b/vendor/github.com/Peripli/service-manager/release-notes.md index f4fe25ce..1a4ebe42 100644 --- a/vendor/github.com/Peripli/service-manager/release-notes.md +++ b/vendor/github.com/Peripli/service-manager/release-notes.md @@ -1,8 +1,6 @@ # Service Manager Release Notes +## v0.1.0 +2018-09-19 -## init -2018-02-28 - -* Repository is created - +* Initial version diff --git a/vendor/github.com/Peripli/service-manager/security/basic/authenticator.go b/vendor/github.com/Peripli/service-manager/security/basic/authenticator.go index cceca3d8..316e05c3 100644 --- a/vendor/github.com/Peripli/service-manager/security/basic/authenticator.go +++ b/vendor/github.com/Peripli/service-manager/security/basic/authenticator.go @@ -45,7 +45,8 @@ func (a *Authenticator) Authenticate(request *http.Request) (*web.User, security return nil, security.Abstain, nil } - credentials, err := a.CredentialStorage.Get(username) + ctx := request.Context() + credentials, err := a.CredentialStorage.Get(ctx, username) if err != nil { if err == util.ErrNotFoundInStorage { @@ -53,7 +54,7 @@ func (a *Authenticator) Authenticate(request *http.Request) (*web.User, security } return nil, security.Abstain, fmt.Errorf("could not get credentials entity from storage: %s", err) } - passwordBytes, err := a.Encrypter.Decrypt([]byte(credentials.Basic.Password)) + passwordBytes, err := a.Encrypter.Decrypt(ctx, []byte(credentials.Basic.Password)) if err != nil { return nil, security.Abstain, fmt.Errorf("could not reverse credentials from storage: %v", err) } diff --git a/vendor/github.com/Peripli/service-manager/security/encrypter.go b/vendor/github.com/Peripli/service-manager/security/encrypter.go index 603a00c9..803882e5 100644 --- a/vendor/github.com/Peripli/service-manager/security/encrypter.go +++ b/vendor/github.com/Peripli/service-manager/security/encrypter.go @@ -16,14 +16,16 @@ package security +import "context" + // TwoLayerEncrypter is an encrypter that fetches the encryption key from a remote location type TwoLayerEncrypter struct { Fetcher KeyFetcher } // Encrypt encrypts the plaintext with a key obtained from a remote location -func (e *TwoLayerEncrypter) Encrypt(plaintext []byte) ([]byte, error) { - key, err := e.Fetcher.GetEncryptionKey() +func (e *TwoLayerEncrypter) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { + key, err := e.Fetcher.GetEncryptionKey(ctx) if err != nil { return nil, err } @@ -31,8 +33,8 @@ func (e *TwoLayerEncrypter) Encrypt(plaintext []byte) ([]byte, error) { } // Decrypt decrypts the cipher text with a key obtained from a remote location -func (e *TwoLayerEncrypter) Decrypt(ciphertext []byte) ([]byte, error) { - key, err := e.Fetcher.GetEncryptionKey() +func (e *TwoLayerEncrypter) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { + key, err := e.Fetcher.GetEncryptionKey(ctx) if err != nil { return nil, err } diff --git a/vendor/github.com/Peripli/service-manager/security/interfaces.go b/vendor/github.com/Peripli/service-manager/security/interfaces.go index edc8b863..d5587298 100644 --- a/vendor/github.com/Peripli/service-manager/security/interfaces.go +++ b/vendor/github.com/Peripli/service-manager/security/interfaces.go @@ -65,18 +65,18 @@ type TokenVerifier interface { // Encrypter provides functionality to encrypt and decrypt data //go:generate counterfeiter . Encrypter type Encrypter interface { - Encrypt(plaintext []byte) ([]byte, error) - Decrypt(ciphertext []byte) ([]byte, error) + Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) + Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) } // KeyFetcher provides functionality to get encryption key from a remote location //go:generate counterfeiter . KeyFetcher type KeyFetcher interface { - GetEncryptionKey() ([]byte, error) + GetEncryptionKey(ctx context.Context) ([]byte, error) } // KeySetter provides functionality to set encryption key in a remote location //go:generate counterfeiter . KeySetter type KeySetter interface { - SetEncryptionKey(key []byte) error + SetEncryptionKey(ctx context.Context, key []byte) error } diff --git a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_encrypter.go b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_encrypter.go index 26ea5460..c412fec2 100644 --- a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_encrypter.go +++ b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_encrypter.go @@ -2,15 +2,17 @@ package securityfakes import ( + "context" "sync" "github.com/Peripli/service-manager/security" ) type FakeEncrypter struct { - EncryptStub func(plaintext []byte) ([]byte, error) + EncryptStub func(ctx context.Context, plaintext []byte) ([]byte, error) encryptMutex sync.RWMutex encryptArgsForCall []struct { + ctx context.Context plaintext []byte } encryptReturns struct { @@ -21,9 +23,10 @@ type FakeEncrypter struct { result1 []byte result2 error } - DecryptStub func(ciphertext []byte) ([]byte, error) + DecryptStub func(ctx context.Context, ciphertext []byte) ([]byte, error) decryptMutex sync.RWMutex decryptArgsForCall []struct { + ctx context.Context ciphertext []byte } decryptReturns struct { @@ -38,7 +41,7 @@ type FakeEncrypter struct { invocationsMutex sync.RWMutex } -func (fake *FakeEncrypter) Encrypt(plaintext []byte) ([]byte, error) { +func (fake *FakeEncrypter) Encrypt(ctx context.Context, plaintext []byte) ([]byte, error) { var plaintextCopy []byte if plaintext != nil { plaintextCopy = make([]byte, len(plaintext)) @@ -47,12 +50,13 @@ func (fake *FakeEncrypter) Encrypt(plaintext []byte) ([]byte, error) { fake.encryptMutex.Lock() ret, specificReturn := fake.encryptReturnsOnCall[len(fake.encryptArgsForCall)] fake.encryptArgsForCall = append(fake.encryptArgsForCall, struct { + ctx context.Context plaintext []byte - }{plaintextCopy}) - fake.recordInvocation("Encrypt", []interface{}{plaintextCopy}) + }{ctx, plaintextCopy}) + fake.recordInvocation("Encrypt", []interface{}{ctx, plaintextCopy}) fake.encryptMutex.Unlock() if fake.EncryptStub != nil { - return fake.EncryptStub(plaintext) + return fake.EncryptStub(ctx, plaintext) } if specificReturn { return ret.result1, ret.result2 @@ -66,10 +70,10 @@ func (fake *FakeEncrypter) EncryptCallCount() int { return len(fake.encryptArgsForCall) } -func (fake *FakeEncrypter) EncryptArgsForCall(i int) []byte { +func (fake *FakeEncrypter) EncryptArgsForCall(i int) (context.Context, []byte) { fake.encryptMutex.RLock() defer fake.encryptMutex.RUnlock() - return fake.encryptArgsForCall[i].plaintext + return fake.encryptArgsForCall[i].ctx, fake.encryptArgsForCall[i].plaintext } func (fake *FakeEncrypter) EncryptReturns(result1 []byte, result2 error) { @@ -94,7 +98,7 @@ func (fake *FakeEncrypter) EncryptReturnsOnCall(i int, result1 []byte, result2 e }{result1, result2} } -func (fake *FakeEncrypter) Decrypt(ciphertext []byte) ([]byte, error) { +func (fake *FakeEncrypter) Decrypt(ctx context.Context, ciphertext []byte) ([]byte, error) { var ciphertextCopy []byte if ciphertext != nil { ciphertextCopy = make([]byte, len(ciphertext)) @@ -103,12 +107,13 @@ func (fake *FakeEncrypter) Decrypt(ciphertext []byte) ([]byte, error) { fake.decryptMutex.Lock() ret, specificReturn := fake.decryptReturnsOnCall[len(fake.decryptArgsForCall)] fake.decryptArgsForCall = append(fake.decryptArgsForCall, struct { + ctx context.Context ciphertext []byte - }{ciphertextCopy}) - fake.recordInvocation("Decrypt", []interface{}{ciphertextCopy}) + }{ctx, ciphertextCopy}) + fake.recordInvocation("Decrypt", []interface{}{ctx, ciphertextCopy}) fake.decryptMutex.Unlock() if fake.DecryptStub != nil { - return fake.DecryptStub(ciphertext) + return fake.DecryptStub(ctx, ciphertext) } if specificReturn { return ret.result1, ret.result2 @@ -122,10 +127,10 @@ func (fake *FakeEncrypter) DecryptCallCount() int { return len(fake.decryptArgsForCall) } -func (fake *FakeEncrypter) DecryptArgsForCall(i int) []byte { +func (fake *FakeEncrypter) DecryptArgsForCall(i int) (context.Context, []byte) { fake.decryptMutex.RLock() defer fake.decryptMutex.RUnlock() - return fake.decryptArgsForCall[i].ciphertext + return fake.decryptArgsForCall[i].ctx, fake.decryptArgsForCall[i].ciphertext } func (fake *FakeEncrypter) DecryptReturns(result1 []byte, result2 error) { diff --git a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_fetcher.go b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_fetcher.go index d214a6ce..6253bf4e 100644 --- a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_fetcher.go +++ b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_fetcher.go @@ -2,16 +2,19 @@ package securityfakes import ( + "context" "sync" "github.com/Peripli/service-manager/security" ) type FakeKeyFetcher struct { - GetEncryptionKeyStub func() ([]byte, error) + GetEncryptionKeyStub func(ctx context.Context) ([]byte, error) getEncryptionKeyMutex sync.RWMutex - getEncryptionKeyArgsForCall []struct{} - getEncryptionKeyReturns struct { + getEncryptionKeyArgsForCall []struct { + ctx context.Context + } + getEncryptionKeyReturns struct { result1 []byte result2 error } @@ -23,14 +26,16 @@ type FakeKeyFetcher struct { invocationsMutex sync.RWMutex } -func (fake *FakeKeyFetcher) GetEncryptionKey() ([]byte, error) { +func (fake *FakeKeyFetcher) GetEncryptionKey(ctx context.Context) ([]byte, error) { fake.getEncryptionKeyMutex.Lock() ret, specificReturn := fake.getEncryptionKeyReturnsOnCall[len(fake.getEncryptionKeyArgsForCall)] - fake.getEncryptionKeyArgsForCall = append(fake.getEncryptionKeyArgsForCall, struct{}{}) - fake.recordInvocation("GetEncryptionKey", []interface{}{}) + fake.getEncryptionKeyArgsForCall = append(fake.getEncryptionKeyArgsForCall, struct { + ctx context.Context + }{ctx}) + fake.recordInvocation("GetEncryptionKey", []interface{}{ctx}) fake.getEncryptionKeyMutex.Unlock() if fake.GetEncryptionKeyStub != nil { - return fake.GetEncryptionKeyStub() + return fake.GetEncryptionKeyStub(ctx) } if specificReturn { return ret.result1, ret.result2 @@ -44,6 +49,12 @@ func (fake *FakeKeyFetcher) GetEncryptionKeyCallCount() int { return len(fake.getEncryptionKeyArgsForCall) } +func (fake *FakeKeyFetcher) GetEncryptionKeyArgsForCall(i int) context.Context { + fake.getEncryptionKeyMutex.RLock() + defer fake.getEncryptionKeyMutex.RUnlock() + return fake.getEncryptionKeyArgsForCall[i].ctx +} + func (fake *FakeKeyFetcher) GetEncryptionKeyReturns(result1 []byte, result2 error) { fake.GetEncryptionKeyStub = nil fake.getEncryptionKeyReturns = struct { diff --git a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_setter.go b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_setter.go index c0b233a8..b1ed193a 100644 --- a/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_setter.go +++ b/vendor/github.com/Peripli/service-manager/security/securityfakes/fake_key_setter.go @@ -2,15 +2,17 @@ package securityfakes import ( + "context" "sync" "github.com/Peripli/service-manager/security" ) type FakeKeySetter struct { - SetEncryptionKeyStub func(key []byte) error + SetEncryptionKeyStub func(ctx context.Context, key []byte) error setEncryptionKeyMutex sync.RWMutex setEncryptionKeyArgsForCall []struct { + ctx context.Context key []byte } setEncryptionKeyReturns struct { @@ -23,7 +25,7 @@ type FakeKeySetter struct { invocationsMutex sync.RWMutex } -func (fake *FakeKeySetter) SetEncryptionKey(key []byte) error { +func (fake *FakeKeySetter) SetEncryptionKey(ctx context.Context, key []byte) error { var keyCopy []byte if key != nil { keyCopy = make([]byte, len(key)) @@ -32,12 +34,13 @@ func (fake *FakeKeySetter) SetEncryptionKey(key []byte) error { fake.setEncryptionKeyMutex.Lock() ret, specificReturn := fake.setEncryptionKeyReturnsOnCall[len(fake.setEncryptionKeyArgsForCall)] fake.setEncryptionKeyArgsForCall = append(fake.setEncryptionKeyArgsForCall, struct { + ctx context.Context key []byte - }{keyCopy}) - fake.recordInvocation("SetEncryptionKey", []interface{}{keyCopy}) + }{ctx, keyCopy}) + fake.recordInvocation("SetEncryptionKey", []interface{}{ctx, keyCopy}) fake.setEncryptionKeyMutex.Unlock() if fake.SetEncryptionKeyStub != nil { - return fake.SetEncryptionKeyStub(key) + return fake.SetEncryptionKeyStub(ctx, key) } if specificReturn { return ret.result1 @@ -51,10 +54,10 @@ func (fake *FakeKeySetter) SetEncryptionKeyCallCount() int { return len(fake.setEncryptionKeyArgsForCall) } -func (fake *FakeKeySetter) SetEncryptionKeyArgsForCall(i int) []byte { +func (fake *FakeKeySetter) SetEncryptionKeyArgsForCall(i int) (context.Context, []byte) { fake.setEncryptionKeyMutex.RLock() defer fake.setEncryptionKeyMutex.RUnlock() - return fake.setEncryptionKeyArgsForCall[i].key + return fake.setEncryptionKeyArgsForCall[i].ctx, fake.setEncryptionKeyArgsForCall[i].key } func (fake *FakeKeySetter) SetEncryptionKeyReturns(result1 error) { diff --git a/vendor/github.com/Peripli/service-manager/storage/interfaces.go b/vendor/github.com/Peripli/service-manager/storage/interfaces.go index df3f1113..59b69521 100644 --- a/vendor/github.com/Peripli/service-manager/storage/interfaces.go +++ b/vendor/github.com/Peripli/service-manager/storage/interfaces.go @@ -73,43 +73,44 @@ type Storage interface { // Broker interface for Broker db operations type Broker interface { // Create stores a broker in SM DB - Create(broker *types.Broker) error + Create(ctx context.Context, broker *types.Broker) error // Get retrieves a broker using the provided id from SM DB - Get(id string) (*types.Broker, error) + Get(ctx context.Context, id string) (*types.Broker, error) // GetAll retrieves all brokers from SM DB - GetAll() ([]*types.Broker, error) + GetAll(ctx context.Context) ([]*types.Broker, error) // Delete deletes a broker from SM DB - Delete(id string) error + Delete(ctx context.Context, id string) error // Update updates a broker from SM DB - Update(broker *types.Broker) error + Update(ctx context.Context, broker *types.Broker) error } // Platform interface for Platform db operations type Platform interface { // Create stores a platform in SM DB - Create(platform *types.Platform) error + Create(ctx context.Context, platform *types.Platform) error // Get retrieves a platform using the provided id from SM DB - Get(id string) (*types.Platform, error) + Get(ctx context.Context, id string) (*types.Platform, error) // GetAll retrieves all platforms from SM DB - GetAll() ([]*types.Platform, error) + GetAll(ctx context.Context) ([]*types.Platform, error) // Delete deletes a platform from SM DB - Delete(id string) error + Delete(ctx context.Context, id string) error // Update updates a platform from SM DB - Update(platform *types.Platform) error + Update(ctx context.Context, platform *types.Platform) error } // Credentials interface for Credentials db operations +//go:generate counterfeiter . Credentials type Credentials interface { // Get retrieves credentials using the provided username from SM DB - Get(username string) (*types.Credentials, error) + Get(ctx context.Context, username string) (*types.Credentials, error) } // Security interface for encryption key operations @@ -118,7 +119,7 @@ type Security interface { // Returns an error if the process has already acquired the lock Lock(ctx context.Context) error // Unlock releases the acquired lock. - Unlock() error + Unlock(ctx context.Context) error // Fetcher provides means to obtain the encryption key Fetcher() security.KeyFetcher // Setter provides means to change the encryption key diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/abstract.go b/vendor/github.com/Peripli/service-manager/storage/postgres/abstract.go index 428c1b8e..f1a2165f 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/abstract.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/abstract.go @@ -17,18 +17,19 @@ package postgres import ( + "context" "database/sql" "fmt" "strings" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/util" "github.com/fatih/structs" "github.com/jmoiron/sqlx" "github.com/lib/pq" - "github.com/sirupsen/logrus" ) -func create(db *sqlx.DB, table string, dto interface{}) error { +func create(ctx context.Context, db *sqlx.DB, table string, dto interface{}) error { set := getDBTags(dto) if len(set) == 0 { @@ -41,41 +42,43 @@ func create(db *sqlx.DB, table string, dto interface{}) error { strings.Join(set, ", "), strings.Join(set, ", :"), ) - logrus.Debugf("Insert query %s", query) - _, err := db.NamedExec(query, dto) - return checkUniqueViolation(err) + log.C(ctx).Debugf("Executing query %s", query) + _, err := db.NamedExecContext(ctx, query, dto) + return checkUniqueViolation(ctx, err) } -func get(db *sqlx.DB, id string, table string, dto interface{}) error { +func get(ctx context.Context, db *sqlx.DB, id string, table string, dto interface{}) error { query := "SELECT * FROM " + table + " WHERE id=$1" - err := db.Get(dto, query, &id) + log.C(ctx).Debugf("Executing query %s", query) + err := db.GetContext(ctx, dto, query, &id) return checkSQLNoRows(err) } -func getAll(db *sqlx.DB, table string, dtos interface{}) error { +func getAll(ctx context.Context, db *sqlx.DB, table string, dtos interface{}) error { query := "SELECT * FROM " + table - return db.Select(dtos, query) + log.C(ctx).Debugf("Executing query %s", query) + return db.SelectContext(ctx, dtos, query) } -func delete(db *sqlx.DB, id string, table string) error { +func delete(ctx context.Context, db *sqlx.DB, id string, table string) error { query := "DELETE FROM " + table + " WHERE id=$1" - - result, err := db.Exec(query, &id) + log.C(ctx).Debugf("Executing query %s", query) + result, err := db.ExecContext(ctx, query, &id) if err != nil { return err } return checkRowsAffected(result) } -func update(db *sqlx.DB, table string, dto interface{}) error { +func update(ctx context.Context, db *sqlx.DB, table string, dto interface{}) error { updateQueryString := updateQuery(table, dto) if updateQueryString == "" { - logrus.Debugf("%s update: Nothing to update", table) + log.C(ctx).Debugf("%s update: Nothing to update", table) return nil } - logrus.Debugf("Update query %s", updateQueryString) - result, err := db.NamedExec(updateQueryString, dto) - if err = checkUniqueViolation(err); err != nil { + log.C(ctx).Debugf("Executing query %s", updateQueryString) + result, err := db.NamedExecContext(ctx, updateQueryString, dto) + if err = checkUniqueViolation(ctx, err); err != nil { return err } return checkRowsAffected(result) @@ -112,13 +115,13 @@ func updateQuery(tableName string, structure interface{}) string { strings.Join(set, ", ")) } -func checkUniqueViolation(err error) error { +func checkUniqueViolation(ctx context.Context, err error) error { if err == nil { return nil } sqlErr, ok := err.(*pq.Error) if ok && sqlErr.Code.Name() == "unique_violation" { - logrus.Debug(sqlErr) + log.C(ctx).Debug(sqlErr) return util.ErrAlreadyExistsInStorage } return err diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/broker.go b/vendor/github.com/Peripli/service-manager/storage/postgres/broker.go index 99ede569..46e3aeb2 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/broker.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/broker.go @@ -17,6 +17,8 @@ package postgres import ( + "context" + "github.com/Peripli/service-manager/pkg/types" "github.com/jmoiron/sqlx" ) @@ -25,21 +27,21 @@ type brokerStorage struct { db *sqlx.DB } -func (bs *brokerStorage) Create(broker *types.Broker) error { - return create(bs.db, brokerTable, convertBrokerToDTO(broker)) +func (bs *brokerStorage) Create(ctx context.Context, broker *types.Broker) error { + return create(ctx, bs.db, brokerTable, convertBrokerToDTO(broker)) } -func (bs *brokerStorage) Get(id string) (*types.Broker, error) { +func (bs *brokerStorage) Get(ctx context.Context, id string) (*types.Broker, error) { broker := &Broker{} - if err := get(bs.db, id, brokerTable, broker); err != nil { + if err := get(ctx, bs.db, id, brokerTable, broker); err != nil { return nil, err } return broker.Convert(), nil } -func (bs *brokerStorage) GetAll() ([]*types.Broker, error) { - brokerDTOs := []Broker{} - err := getAll(bs.db, brokerTable, &brokerDTOs) +func (bs *brokerStorage) GetAll(ctx context.Context) ([]*types.Broker, error) { + var brokerDTOs []Broker + err := getAll(ctx, bs.db, brokerTable, &brokerDTOs) if err != nil || len(brokerDTOs) == 0 { return []*types.Broker{}, err } @@ -50,10 +52,10 @@ func (bs *brokerStorage) GetAll() ([]*types.Broker, error) { return brokers, nil } -func (bs *brokerStorage) Delete(id string) error { - return delete(bs.db, id, brokerTable) +func (bs *brokerStorage) Delete(ctx context.Context, id string) error { + return delete(ctx, bs.db, id, brokerTable) } -func (bs *brokerStorage) Update(broker *types.Broker) error { - return update(bs.db, brokerTable, convertBrokerToDTO(broker)) +func (bs *brokerStorage) Update(ctx context.Context, broker *types.Broker) error { + return update(ctx, bs.db, brokerTable, convertBrokerToDTO(broker)) } diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/credentials.go b/vendor/github.com/Peripli/service-manager/storage/postgres/credentials.go index cb215ded..f83922cb 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/credentials.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/credentials.go @@ -17,8 +17,10 @@ package postgres import ( + "context" "fmt" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/pkg/types" "github.com/jmoiron/sqlx" ) @@ -27,11 +29,12 @@ type credentialStorage struct { db *sqlx.DB } -func (cs *credentialStorage) Get(username string) (*types.Credentials, error) { +func (cs *credentialStorage) Get(ctx context.Context, username string) (*types.Credentials, error) { platformCredentials := &Platform{} query := fmt.Sprintf("SELECT username, password FROM %s WHERE username=$1", platformTable) + log.C(ctx).Debugf("Executing query %s", query) - err := cs.db.Get(platformCredentials, query, username) + err := cs.db.GetContext(ctx, platformCredentials, query, username) if err != nil { return nil, checkSQLNoRows(err) diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/platform.go b/vendor/github.com/Peripli/service-manager/storage/postgres/platform.go index 22c907c0..58e1c16c 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/platform.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/platform.go @@ -17,6 +17,8 @@ package postgres import ( + "context" + "github.com/Peripli/service-manager/pkg/types" "github.com/jmoiron/sqlx" ) @@ -25,21 +27,21 @@ type platformStorage struct { db *sqlx.DB } -func (ps *platformStorage) Create(platform *types.Platform) error { - return create(ps.db, platformTable, convertPlatformToDTO(platform)) +func (ps *platformStorage) Create(ctx context.Context, platform *types.Platform) error { + return create(ctx, ps.db, platformTable, convertPlatformToDTO(platform)) } -func (ps *platformStorage) Get(id string) (*types.Platform, error) { +func (ps *platformStorage) Get(ctx context.Context, id string) (*types.Platform, error) { platform := &Platform{} - if err := get(ps.db, id, platformTable, platform); err != nil { + if err := get(ctx, ps.db, id, platformTable, platform); err != nil { return nil, err } return platform.Convert(), nil } -func (ps *platformStorage) GetAll() ([]*types.Platform, error) { - platformDTOs := []Platform{} - err := getAll(ps.db, platformTable, &platformDTOs) +func (ps *platformStorage) GetAll(ctx context.Context) ([]*types.Platform, error) { + var platformDTOs []Platform + err := getAll(ctx, ps.db, platformTable, &platformDTOs) if err != nil || len(platformDTOs) == 0 { return []*types.Platform{}, err } @@ -50,11 +52,10 @@ func (ps *platformStorage) GetAll() ([]*types.Platform, error) { return platforms, nil } -func (ps *platformStorage) Delete(id string) error { - return delete(ps.db, id, platformTable) +func (ps *platformStorage) Delete(ctx context.Context, id string) error { + return delete(ctx, ps.db, id, platformTable) } -func (ps *platformStorage) Update(platform *types.Platform) error { - return update(ps.db, platformTable, convertPlatformToDTO(platform)) - +func (ps *platformStorage) Update(ctx context.Context, platform *types.Platform) error { + return update(ctx, ps.db, platformTable, convertPlatformToDTO(platform)) } diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/security.go b/vendor/github.com/Peripli/service-manager/storage/postgres/security.go index 43a64a8b..0a82aa02 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/security.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/security.go @@ -22,10 +22,10 @@ import ( "sync" "time" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/security" "github.com/jmoiron/sqlx" - "github.com/sirupsen/logrus" -) + ) const securityLockIndex = 111 @@ -52,14 +52,14 @@ func (s *securityStorage) Lock(ctx context.Context) error { } // Unlock releases the database lock. -func (s *securityStorage) Unlock() error { +func (s *securityStorage) Unlock(ctx context.Context) error { s.mutex.Lock() defer s.mutex.Unlock() if !s.isLocked { return nil } - if _, err := s.db.Exec("SELECT pg_advisory_unlock($1)", securityLockIndex); err != nil { + if _, err := s.db.ExecContext(ctx, "SELECT pg_advisory_unlock($1)", securityLockIndex); err != nil { return err } s.isLocked = false @@ -82,13 +82,13 @@ type keyFetcher struct { } // GetEncryptionKey returns the encryption key used to encrypt the credentials for brokers -func (s *keyFetcher) GetEncryptionKey() ([]byte, error) { +func (s *keyFetcher) GetEncryptionKey(ctx context.Context) ([]byte, error) { var safes []Safe - if err := getAll(s.db, "safe", &safes); err != nil { + if err := getAll(ctx, s.db, "safe", &safes); err != nil { return nil, err } if len(safes) != 1 { - logrus.Warnf("Unexpected number of keys found: %d", len(safes)) + log.C(ctx).Warnf("Unexpected number of keys found: %d", len(safes)) return []byte{}, nil } encryptedKey := []byte(safes[0].Secret) @@ -101,9 +101,9 @@ type keySetter struct { } // Sets the encryption key by encrypting it beforehand with the encryption key in the environment -func (k *keySetter) SetEncryptionKey(key []byte) error { +func (k *keySetter) SetEncryptionKey(ctx context.Context, key []byte) error { var safes []Safe - if err := getAll(k.db, "safe", &safes); err != nil { + if err := getAll(ctx, k.db, "safe", &safes); err != nil { return err } if len(safes) != 0 { @@ -118,5 +118,5 @@ func (k *keySetter) SetEncryptionKey(key []byte) error { CreatedAt: time.Now(), UpdatedAt: time.Now(), } - return create(k.db, "safe", safe) + return create(ctx, k.db, "safe", safe) } diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/security_test.go b/vendor/github.com/Peripli/service-manager/storage/postgres/security_test.go index e4e87ec4..4b840f70 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/security_test.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/security_test.go @@ -60,7 +60,7 @@ var _ = Describe("Security", func() { mock.ExpectQuery("SELECT").WillReturnError(expectedError) }) It("Should return error", func() { - encryptionKey, err := fetcher.GetEncryptionKey() + encryptionKey, err := fetcher.GetEncryptionKey(context.TODO()) Expect(encryptionKey).To(BeNil()) Expect(err).To(Equal(expectedError)) }) @@ -72,7 +72,7 @@ var _ = Describe("Security", func() { mock.ExpectQuery("SELECT").WillReturnRows(rows) }) It("Should return empty byte array", func() { - encryptionKey, err := fetcher.GetEncryptionKey() + encryptionKey, err := fetcher.GetEncryptionKey(context.TODO()) Expect(encryptionKey).To(Not(BeNil())) Expect(encryptionKey).To(BeEmpty()) Expect(err).To(BeNil()) @@ -89,7 +89,7 @@ var _ = Describe("Security", func() { mock.ExpectQuery("SELECT").WillReturnRows(rows) }) It("Should return decrypted key", func() { - encryptionKey, err := fetcher.GetEncryptionKey() + encryptionKey, err := fetcher.GetEncryptionKey(context.TODO()) Expect(encryptionKey).To(Equal(plaintext)) Expect(err).To(BeNil()) }) @@ -120,7 +120,7 @@ var _ = Describe("Security", func() { Context("When encrypting key returns error", func() { It("Should return error", func() { - err := setter.SetEncryptionKey([]byte{}) + err := setter.SetEncryptionKey(context.TODO(), []byte{}) Expect(err).To(Not(BeNil())) }) }) @@ -132,7 +132,7 @@ var _ = Describe("Security", func() { mock.ExpectExec("INSERT").WillReturnError(expectedError) }) It("Should return error", func() { - err := setter.SetEncryptionKey([]byte{}) + err := setter.SetEncryptionKey(context.TODO(), []byte{}) Expect(err).To(Not(BeNil())) }) }) @@ -144,7 +144,7 @@ var _ = Describe("Security", func() { mock.ExpectCommit().WillReturnError(expectedError) }) It("Should return error", func() { - err := setter.SetEncryptionKey([]byte{}) + err := setter.SetEncryptionKey(context.TODO(), []byte{}) Expect(err).To(Not(BeNil())) }) }) @@ -156,7 +156,7 @@ var _ = Describe("Security", func() { mock.ExpectExec("INSERT").WillReturnResult(result) }) It("Should return nil", func() { - err := setter.SetEncryptionKey([]byte{}) + err := setter.SetEncryptionKey(context.TODO(), []byte{}) Expect(err).To(BeNil()) }) }) @@ -196,7 +196,7 @@ var _ = Describe("Security", func() { Context("When lock is not yet acquired", func() { AfterEach(func() { - storage.Unlock() + storage.Unlock(context.TODO()) }) BeforeEach(func() { mock.ExpectExec("SELECT").WillReturnResult(sqlmock.NewResult(int64(1), int64(1))) @@ -213,7 +213,7 @@ var _ = Describe("Security", func() { Context("When lock is not acquired", func() { It("Should return nil", func() { storage.isLocked = false - err := storage.Unlock() + err := storage.Unlock(context.TODO()) Expect(err).To(BeNil()) }) }) @@ -223,7 +223,7 @@ var _ = Describe("Security", func() { }) It("Should release lock", func() { storage.isLocked = true - err := storage.Unlock() + err := storage.Unlock(context.TODO()) Expect(err).To(BeNil()) Expect(storage.isLocked).To(Equal(false)) }) diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/storage.go b/vendor/github.com/Peripli/service-manager/storage/postgres/storage.go index 2621ffd9..e16950b3 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/storage.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/storage.go @@ -22,13 +22,13 @@ import ( "sync" "time" + "github.com/Peripli/service-manager/pkg/log" "github.com/Peripli/service-manager/storage" "github.com/golang-migrate/migrate" migratepg "github.com/golang-migrate/migrate/database/postgres" _ "github.com/golang-migrate/migrate/source/file" "github.com/jmoiron/sqlx" - "github.com/sirupsen/logrus" -) + ) // Storage defines the name of the PostgreSQL relational storage const Storage = "postgres" @@ -46,7 +46,7 @@ type postgresStorage struct { func (storage *postgresStorage) checkOpen() { if storage.db == nil { - logrus.Panicln("Storage is not yet Open") + log.D().Panicln("Storage is not yet Open") } } @@ -67,7 +67,7 @@ func (storage *postgresStorage) Platform() storage.Platform { func (storage *postgresStorage) Credentials() storage.Credentials { if storage.db == nil { - logrus.Panicln("Storage is not yet Open") + log.D().Panicln("Storage is not yet Open") } return &credentialStorage{storage.db} } @@ -85,7 +85,7 @@ func (storage *postgresStorage) Open(uri string, encryptionKey []byte) error { if storage.db == nil { storage.db, err = sqlx.Connect(Storage, uri) if err != nil { - logrus.Panicln("Could not connect to PostgreSQL:", err) + log.D().Panicln("Could not connect to PostgreSQL:", err) } storage.state = &storageState{ storageError: nil, @@ -96,9 +96,9 @@ func (storage *postgresStorage) Open(uri string, encryptionKey []byte) error { } storage.mutex = &sync.Mutex{} storage.encryptionKey = encryptionKey - logrus.Debug("Updating database schema") + log.D().Debug("Updating database schema") if err := updateSchema(storage.db); err != nil { - logrus.Panicln("Could not update database schema:", err) + log.D().Panicln("Could not update database schema:", err) } } return err @@ -120,7 +120,7 @@ func updateSchema(db *sqlx.DB) error { } err = m.Up() if err == migrate.ErrNoChange { - logrus.Debug("Database schema already up to date") + log.D().Debug("Database schema already up to date") err = nil } return err diff --git a/vendor/github.com/Peripli/service-manager/storage/postgres/storage_state.go b/vendor/github.com/Peripli/service-manager/storage/postgres/storage_state.go index 30de5008..0e85f781 100644 --- a/vendor/github.com/Peripli/service-manager/storage/postgres/storage_state.go +++ b/vendor/github.com/Peripli/service-manager/storage/postgres/storage_state.go @@ -34,17 +34,17 @@ type storageState struct { // Get returns error if the db connectivity is down and nil otherwise func (state *storageState) Get() error { - if cacheIsValid, storageError := state.getCashed(); cacheIsValid { + if cacheIsValid, storageError := state.getCached(); cacheIsValid { return storageError } return state.checkDB() } func (state *storageState) cachedStateIsValid() bool { - return time.Now().Sub(state.lastCheck) < state.storageCheckInterval + return time.Since(state.lastCheck) < state.storageCheckInterval } -func (state *storageState) getCashed() (cacheIsValid bool, storageError error) { +func (state *storageState) getCached() (cacheIsValid bool, storageError error) { state.mutex.RLock() defer state.mutex.RUnlock() if state.cachedStateIsValid() { diff --git a/vendor/github.com/Peripli/service-manager/storage/registry.go b/vendor/github.com/Peripli/service-manager/storage/registry.go index 26b2fde5..6612bbb3 100644 --- a/vendor/github.com/Peripli/service-manager/storage/registry.go +++ b/vendor/github.com/Peripli/service-manager/storage/registry.go @@ -18,11 +18,10 @@ package storage import ( "context" - "sync" - "fmt" + "sync" - "github.com/sirupsen/logrus" + "github.com/Peripli/service-manager/pkg/log" ) var ( @@ -34,11 +33,12 @@ var ( func Register(name string, storage Storage) { mux.RLock() defer mux.RUnlock() + logger := log.D() if storage == nil { - logrus.Panicln("storage: Register storage is nil") + logger.Panicln("storage: Register storage is nil") } if _, dup := storages[name]; dup { - logrus.Panicf("storage: Register called twice for storage with name %s", name) + logger.Panicf("storage: Register called twice for storage with name %s", name) } storages[name] = storage } @@ -63,8 +63,9 @@ func Use(ctx context.Context, name string, uri string, encryptionKey []byte) (St func awaitTermination(ctx context.Context, storage Storage) { <-ctx.Done() - logrus.Debug("Context cancelled. Closing storage...") + logger := log.C(ctx) + logger.Debug("Context cancelled. Closing storage...") if err := storage.Close(); err != nil { - logrus.Error(err) + logger.Error(err) } } diff --git a/vendor/github.com/Peripli/service-manager/storage/storagefakes/fake_credentials.go b/vendor/github.com/Peripli/service-manager/storage/storagefakes/fake_credentials.go index 2f7389a5..ab5bf635 100644 --- a/vendor/github.com/Peripli/service-manager/storage/storagefakes/fake_credentials.go +++ b/vendor/github.com/Peripli/service-manager/storage/storagefakes/fake_credentials.go @@ -2,6 +2,7 @@ package storagefakes import ( + "context" "sync" "github.com/Peripli/service-manager/pkg/types" @@ -9,9 +10,10 @@ import ( ) type FakeCredentials struct { - GetStub func(username string) (*types.Credentials, error) + GetStub func(ctx context.Context, username string) (*types.Credentials, error) getMutex sync.RWMutex getArgsForCall []struct { + ctx context.Context username string } getReturns struct { @@ -26,16 +28,17 @@ type FakeCredentials struct { invocationsMutex sync.RWMutex } -func (fake *FakeCredentials) Get(username string) (*types.Credentials, error) { +func (fake *FakeCredentials) Get(ctx context.Context, username string) (*types.Credentials, error) { fake.getMutex.Lock() ret, specificReturn := fake.getReturnsOnCall[len(fake.getArgsForCall)] fake.getArgsForCall = append(fake.getArgsForCall, struct { + ctx context.Context username string - }{username}) - fake.recordInvocation("Get", []interface{}{username}) + }{ctx, username}) + fake.recordInvocation("Get", []interface{}{ctx, username}) fake.getMutex.Unlock() if fake.GetStub != nil { - return fake.GetStub(username) + return fake.GetStub(ctx, username) } if specificReturn { return ret.result1, ret.result2 @@ -49,10 +52,10 @@ func (fake *FakeCredentials) GetCallCount() int { return len(fake.getArgsForCall) } -func (fake *FakeCredentials) GetArgsForCall(i int) string { +func (fake *FakeCredentials) GetArgsForCall(i int) (context.Context, string) { fake.getMutex.RLock() defer fake.getMutex.RUnlock() - return fake.getArgsForCall[i].username + return fake.getArgsForCall[i].ctx, fake.getArgsForCall[i].username } func (fake *FakeCredentials) GetReturns(result1 *types.Credentials, result2 error) { diff --git a/vendor/github.com/Peripli/service-manager/test/auth_test/auth_test.go b/vendor/github.com/Peripli/service-manager/test/auth_test/auth_test.go index dbbba5f7..8a7d337e 100644 --- a/vendor/github.com/Peripli/service-manager/test/auth_test/auth_test.go +++ b/vendor/github.com/Peripli/service-manager/test/auth_test/auth_test.go @@ -49,7 +49,7 @@ var _ = Describe("Service Manager Authentication", func() { BeforeSuite(func() { os.Chdir("../..") - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { @@ -72,6 +72,7 @@ var _ = Describe("Service Manager Authentication", func() { code := http.StatusOK catalogResponse := []byte(common.Catalog) brokerServer := common.FakeBrokerServer(&code, &catalogResponse) + defer brokerServer.Close() brokerJSON := common.MakeBroker("broker-id", brokerServer.URL(), "") ctx.SMWithOAuth.POST("/v1/service_brokers"). @@ -79,8 +80,6 @@ var _ = Describe("Service Manager Authentication", func() { WithJSON(brokerJSON). Expect(). Status(http.StatusCreated) - - brokerServer.Close() }) }) diff --git a/vendor/github.com/Peripli/service-manager/test/broker_test/broker_test.go b/vendor/github.com/Peripli/service-manager/test/broker_test/broker_test.go index e3b93cbe..94be50b9 100644 --- a/vendor/github.com/Peripli/service-manager/test/broker_test/broker_test.go +++ b/vendor/github.com/Peripli/service-manager/test/broker_test/broker_test.go @@ -51,7 +51,7 @@ var _ = Describe("Service Manager Broker API", func() { BeforeSuite(func() { os.Chdir("../..") - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { @@ -561,7 +561,6 @@ var _ = Describe("Service Manager Broker API", func() { Context("when unmodifiable fields are provided request body", func() { var ( - err error unmarshaledCatalog common.Object ) @@ -579,7 +578,7 @@ var _ = Describe("Service Manager Broker API", func() { } unmarshaledCatalog = common.Object{} - err = json.Unmarshal([]byte(common.Catalog), &unmarshaledCatalog) + json.Unmarshal([]byte(common.Catalog), &unmarshaledCatalog) }) It("should not change them", func() { diff --git a/vendor/github.com/Peripli/service-manager/test/catalog_test/catalog_test.go b/vendor/github.com/Peripli/service-manager/test/catalog_test/catalog_test.go index e59a41b5..5ab1e47a 100644 --- a/vendor/github.com/Peripli/service-manager/test/catalog_test/catalog_test.go +++ b/vendor/github.com/Peripli/service-manager/test/catalog_test/catalog_test.go @@ -51,7 +51,7 @@ var _ = Describe("Service Manager Aggregated Catalog API", func() { BeforeSuite(func() { os.Chdir("../..") - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { diff --git a/vendor/github.com/Peripli/service-manager/test/common/broker.go b/vendor/github.com/Peripli/service-manager/test/common/broker.go new file mode 100644 index 00000000..4484c0d0 --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/test/common/broker.go @@ -0,0 +1,73 @@ +package common + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "net/http/httptest" + + "github.com/gavv/httpexpect" + . "github.com/onsi/ginkgo" +) + +type Broker struct { + StatusCode int + ResponseBody []byte + Request *http.Request + RequestBody *httpexpect.Value + RawRequestBody []byte + OSBURL string + Server *httptest.Server + ID string +} + +const serviceCatalog = `{ + "services": [{ + "id": "1234", + "name": "service1", + "description": "sample-test", + "bindable": true, + "plans": [{ + "id": "plan-id", + "name": "plan-name", + "description": "plan-desc" + }] + }] +}` + +func (b *Broker) ServeHTTP(rw http.ResponseWriter, req *http.Request) { + b.Request = req + responseBody := b.ResponseBody + switch req.Method { + case http.MethodPatch, http.MethodPost, http.MethodPut: + var err error + b.RawRequestBody, err = ioutil.ReadAll(req.Body) + if err != nil { + panic(err) + } + var reqData interface{} + err = json.Unmarshal(b.RawRequestBody, &reqData) + if err != nil { + panic(err) + } + b.RequestBody = httpexpect.NewValue(GinkgoT(), reqData) + + case http.MethodGet: + if responseBody == nil && req.URL.Path == "/v2/catalog" { + responseBody = []byte(serviceCatalog) + } + } + + code := b.StatusCode + if code == 0 { + code = http.StatusOK + } + rw.Header().Set("Content-Type", "application/json") + rw.WriteHeader(code) + + rw.Write(responseBody) +} + +func (b *Broker) Called() bool { + return b.Request != nil +} diff --git a/vendor/github.com/Peripli/service-manager/test/common/common.go b/vendor/github.com/Peripli/service-manager/test/common/common.go index 0e4b93ee..6af98dc9 100644 --- a/vendor/github.com/Peripli/service-manager/test/common/common.go +++ b/vendor/github.com/Peripli/service-manager/test/common/common.go @@ -21,11 +21,9 @@ import ( "crypto/rsa" "encoding/base64" "encoding/binary" - "encoding/json" "fmt" "net/http" "net/http/httptest" - "time" "net/url" "reflect" @@ -38,7 +36,6 @@ import ( "github.com/Peripli/service-manager/pkg/types" "github.com/gavv/httpexpect" - "github.com/gbrlsnchs/jwt" "github.com/gorilla/mux" "github.com/mitchellh/mapstructure" . "github.com/onsi/ginkgo" @@ -230,68 +227,6 @@ func newJwkResponse(keyID string, publicKey rsa.PublicKey) *jwkResponse { } } -func RequestToken(issuerURL string) string { - issuer := httpexpect.New(GinkgoT(), issuerURL) - token := issuer.GET("/oauth/token").Expect(). - Status(http.StatusOK).JSON().Object(). - Value("access_token").String().Raw() - return token -} - -func SetupFakeOAuthServer() *httptest.Server { - privateKey := generatePrivateKey() - publicKey := privateKey.PublicKey - signer := jwt.RS256(privateKey, &publicKey) - keyID := "test-key" - - var issuerURL string - - mux := http.NewServeMux() - mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{ - "issuer": "` + issuerURL + `/oauth/token", - "jwks_uri": "` + issuerURL + `/token_keys" - }`)) - }) - - mux.HandleFunc("/oauth/token", func(w http.ResponseWriter, r *http.Request) { - nextYear := time.Now().Add(24 * 30 * 12 * time.Hour) - token, err := jwt.Sign(signer, &jwt.Options{ - Issuer: issuerURL + "/oauth/token", - KeyID: keyID, - Audience: "sm", - ExpirationTime: nextYear, - Public: map[string]interface{}{ - "user_name": "testUser", - }, - }) - if err != nil { - panic(err) - } - - w.Header().Set("Content-Type", "application/json") - w.Write([]byte(`{"access_token": "` + token + `"}`)) - }) - - mux.HandleFunc("/token_keys", func(w http.ResponseWriter, r *http.Request) { - jwk := newJwkResponse(keyID, publicKey) - responseBody, _ := json.Marshal(&struct { - Keys []jwkResponse `json:"keys"` - }{ - Keys: []jwkResponse{*jwk}, - }) - - w.Header().Set("Content-Type", "application/json") - w.Write(responseBody) - }) - - server := httptest.NewServer(mux) - issuerURL = server.URL - - return server -} - func MakeBroker(name string, url string, description string) Object { return Object{ "name": name, @@ -411,6 +346,7 @@ func DoHTTP(reaction *HTTPReaction, checks *HTTPExpectations) func(*http.Request return &http.Response{ StatusCode: reaction.Status, Body: Closer(reaction.Body), + Request: request, }, reaction.Err } } diff --git a/vendor/github.com/Peripli/service-manager/test/common/oauth_server.go b/vendor/github.com/Peripli/service-manager/test/common/oauth_server.go new file mode 100644 index 00000000..ada1d8a5 --- /dev/null +++ b/vendor/github.com/Peripli/service-manager/test/common/oauth_server.go @@ -0,0 +1,111 @@ +/* + * Copyright 2018 The Service Manager Authors + * + * 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. + */ + +package common + +import ( + "crypto/rsa" + "encoding/json" + "net/http" + "net/http/httptest" + "time" + + "github.com/gbrlsnchs/jwt" +) + +type OAuthServer struct { + URL string + + server *httptest.Server + mux *http.ServeMux + privateKey *rsa.PrivateKey // public key privateKey.PublicKey + signer jwt.Signer + keyID string +} + +func NewOAuthServer() *OAuthServer { + privateKey := generatePrivateKey() + + os := &OAuthServer{ + privateKey: privateKey, + signer: jwt.RS256(privateKey, &privateKey.PublicKey), + keyID: "test-key", + mux: http.NewServeMux(), + } + os.mux.HandleFunc("/.well-known/openid-configuration", os.getOpenIDConfig) + os.mux.HandleFunc("/oauth/token", os.getToken) + os.mux.HandleFunc("/token_keys", os.getTokenKeys) + + return os +} + +func (os *OAuthServer) Start() { + if os.server != nil { + panic("OAuth server already started") + } + os.server = httptest.NewServer(os.mux) + os.URL = os.server.URL +} + +func (os *OAuthServer) Close() { + if os != nil && os.server != nil { + os.server.Close() + os.server = nil + } +} + +func (os *OAuthServer) getOpenIDConfig(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{ + "issuer": "` + os.URL + `/oauth/token", + "jwks_uri": "` + os.URL + `/token_keys" + }`)) +} + +func (os *OAuthServer) getToken(w http.ResponseWriter, r *http.Request) { + token := os.CreateToken(map[string]interface{}{ + "user_name": "testUser", + }) + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"access_token": "` + token + `"}`)) +} + +func (os *OAuthServer) CreateToken(payload map[string]interface{}) string { + nextYear := time.Now().Add(365 * 24 * time.Hour) + token, err := jwt.Sign(os.signer, &jwt.Options{ + Issuer: os.URL + "/oauth/token", + KeyID: os.keyID, + Audience: "sm", + ExpirationTime: nextYear, + Public: payload, + }) + if err != nil { + panic(err) + } + return token +} + +func (os *OAuthServer) getTokenKeys(w http.ResponseWriter, r *http.Request) { + jwk := newJwkResponse(os.keyID, os.privateKey.PublicKey) + responseBody, _ := json.Marshal(&struct { + Keys []jwkResponse `json:"keys"` + }{ + Keys: []jwkResponse{*jwk}, + }) + + w.Header().Set("Content-Type", "application/json") + w.Write(responseBody) +} diff --git a/vendor/github.com/Peripli/service-manager/test/common/test_context.go b/vendor/github.com/Peripli/service-manager/test/common/test_context.go index 1269535f..c7bd95a8 100644 --- a/vendor/github.com/Peripli/service-manager/test/common/test_context.go +++ b/vendor/github.com/Peripli/service-manager/test/common/test_context.go @@ -18,36 +18,56 @@ package common import ( "context" - "encoding/json" - "io/ioutil" - "net/http" "net/http/httptest" . "github.com/onsi/ginkgo" "github.com/spf13/pflag" + "github.com/Peripli/service-manager/pkg/env" "github.com/Peripli/service-manager/pkg/sm" "github.com/Peripli/service-manager/pkg/web" "github.com/gavv/httpexpect" ) -var serviceCatalog = `{ - "services": [{ - "id": "1234", - "name": "service1", - "description": "sample-test", - "bindable": true, - "plans": [{ - "id": "plan-id", - "name": "plan-name", - "description": "plan-desc" - }] - }] -}` - -func NewTestContext(smURL, tokenIssuerURL string) *TestContext { - SM := httpexpect.New(GinkgoT(), smURL) - accessToken := RequestToken(tokenIssuerURL) +type ContextParams struct { + Environment env.Environment + RegisterExtensions func(api *web.API) + DefaultTokenClaims map[string]interface{} +} + +func LoadEnvironment(confgiFileDir string) env.Environment { + return sm.DefaultEnv(func(set *pflag.FlagSet) { + set.Set("file.location", confgiFileDir) + }) +} + +func buildSM(params *ContextParams, issuerURL string) *httptest.Server { + if params.Environment == nil { + params.Environment = LoadEnvironment("./test/common") + } + params.Environment.Set("api.token_issuer_url", issuerURL) + + ctx, _ := context.WithCancel(context.Background()) + smanagerBuilder := sm.New(ctx, params.Environment) + if params.RegisterExtensions != nil { + params.RegisterExtensions(smanagerBuilder.API) + } + serviceManager := smanagerBuilder.Build() + return httptest.NewServer(serviceManager.Server.Router) +} + +func NewTestContext(params *ContextParams) *TestContext { + if params == nil { + params = &ContextParams{} + } + + oauthServer := NewOAuthServer() + oauthServer.Start() + + smServer := buildSM(params, oauthServer.URL) + SM := httpexpect.New(GinkgoT(), smServer.URL) + + accessToken := oauthServer.CreateToken(params.DefaultTokenClaims) SMWithOAuth := SM.Builder(func(req *httpexpect.Request) { req.WithHeader("Authorization", "Bearer "+accessToken) }) @@ -57,46 +77,29 @@ func NewTestContext(smURL, tokenIssuerURL string) *TestContext { platformJSON := MakePlatform("ctx-platform-test", "ctx-platform-test", "platform-type", "test-platform") platform := RegisterPlatform(platformJSON, SMWithOAuth) - SMWithBasic := SM.Builder(func(req *httpexpect.Request) { username, password := platform.Credentials.Basic.Username, platform.Credentials.Basic.Password req.WithBasicAuth(username, password) }) + return &TestContext{ SM: SM, SMWithOAuth: SMWithOAuth, SMWithBasic: SMWithBasic, brokers: make(map[string]*Broker), + smServer: smServer, + OAuthServer: oauthServer, } } -func NewTestContextFromAPIs(plugins []web.Plugin, additionalAPIs ...*web.API) *TestContext { - ctx, _ := context.WithCancel(context.Background()) - mockOauthServer := SetupFakeOAuthServer() - - env := sm.DefaultEnv(func(set *pflag.FlagSet) { - set.Set("file.location", "./test/common") - set.Set("api.token_issuer_url", mockOauthServer.URL) - }) - - smanagerBuilder := sm.New(ctx, env) - for _, additionalAPI := range additionalAPIs { - smanagerBuilder.RegisterControllers(additionalAPI.Controllers...) - smanagerBuilder.RegisterFilters(additionalAPI.Filters...) - } - smanagerBuilder.RegisterPlugins(plugins...) - serviceManager := smanagerBuilder.Build() - smServer := httptest.NewServer(serviceManager.Server.Router) - - return NewTestContext(smServer.URL, mockOauthServer.URL) -} - type TestContext struct { SM *httpexpect.Expect SMWithOAuth *httpexpect.Expect SMWithBasic *httpexpect.Expect - brokers map[string]*Broker + smServer *httptest.Server + OAuthServer *OAuthServer + brokers map[string]*Broker } func (ctx *TestContext) RegisterBroker(name string, server *httptest.Server) *Broker { @@ -105,19 +108,26 @@ func (ctx *TestContext) RegisterBroker(name string, server *httptest.Server) *Br server = httptest.NewServer(broker) } brokerJSON := MakeBroker(name, server.URL, "") - broker.ResponseBody = []byte(serviceCatalog) - brokerID := RegisterBroker(brokerJSON, ctx.SMWithOAuth) + broker.ID = RegisterBroker(brokerJSON, ctx.SMWithOAuth) - broker.OSBURL = "/v1/osb/" + brokerID + broker.OSBURL = "/v1/osb/" + broker.ID broker.Server = server - broker.ResponseBody = nil broker.Request = nil ctx.brokers[name] = broker return broker } +func (ctx *TestContext) CleanupBroker(name string) { + broker := ctx.brokers[name] + ctx.SMWithOAuth.DELETE("/v1/service_brokers/" + broker.ID).Expect() + if broker.Server != nil { + broker.Server.Close() + } + delete(ctx.brokers, name) +} + func (ctx *TestContext) Cleanup() { if ctx == nil { return @@ -133,46 +143,9 @@ func (ctx *TestContext) Cleanup() { broker.Server.Close() } } -} -type Broker struct { - StatusCode int - ResponseBody []byte - Request *http.Request - RequestBody *httpexpect.Value - RawRequestBody []byte - OSBURL string - Server *httptest.Server -} - -func (b *Broker) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - b.Request = req - - if req.Method == http.MethodPatch || req.Method == http.MethodPost || req.Method == http.MethodPut { - var err error - b.RawRequestBody, err = ioutil.ReadAll(req.Body) - if err != nil { - panic(err) - } - var reqData interface{} - err = json.Unmarshal(b.RawRequestBody, &reqData) - if err != nil { - panic(err) - } - - b.RequestBody = httpexpect.NewValue(GinkgoT(), reqData) + if ctx.smServer != nil { + ctx.smServer.Close() } - - code := b.StatusCode - if code == 0 { - code = http.StatusOK - } - rw.Header().Set("Content-Type", "application/json") - rw.WriteHeader(code) - - rw.Write(b.ResponseBody) -} - -func (b *Broker) Called() bool { - return b.Request != nil + ctx.OAuthServer.Close() } diff --git a/vendor/github.com/Peripli/service-manager/test/filter_test/filter_test.go b/vendor/github.com/Peripli/service-manager/test/filter_test/filter_test.go index 0405464c..80aaf3d4 100644 --- a/vendor/github.com/Peripli/service-manager/test/filter_test/filter_test.go +++ b/vendor/github.com/Peripli/service-manager/test/filter_test/filter_test.go @@ -5,10 +5,10 @@ import ( "os" "testing" + "github.com/Peripli/service-manager/pkg/web" "github.com/Peripli/service-manager/test/common" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" - "github.com/Peripli/service-manager/pkg/web" ) type object = common.Object @@ -27,9 +27,11 @@ var _ = Describe("Service Manager Filters", func() { var order string JustBeforeEach(func() { - api := &web.API{} - api.RegisterFilters(testFilters...) - ctx = common.NewTestContextFromAPIs(nil, api) + ctx = common.NewTestContext(&common.ContextParams{ + RegisterExtensions: func(api *web.API) { + api.RegisterFilters(testFilters...) + }, + }) testBroker = ctx.RegisterBroker("broker1", nil) order = "" }) @@ -116,12 +118,12 @@ func (tf osbTestFilter) FilterMatchers() []web.FilterMatcher { } func (tf osbTestFilter) Run(request *web.Request, next web.Handler) (*web.Response, error) { - *tf.state += "osb1" - res, err := next.Handle(request) - if err == nil { - *tf.state += "osb2" - } - return res, err + *tf.state += "osb1" + res, err := next.Handle(request) + if err == nil { + *tf.state += "osb2" + } + return res, err } type globalTestFilterA struct { @@ -142,13 +144,13 @@ func (gfa globalTestFilterA) FilterMatchers() []web.FilterMatcher { } } -func (gfa globalTestFilterA) Run(request *web.Request, next web.Handler) (*web.Response,error) { - *gfa.state += "a1" - res, err := next.Handle(request) - if err == nil { - *gfa.state += "a2" - } - return res, err +func (gfa globalTestFilterA) Run(request *web.Request, next web.Handler) (*web.Response, error) { + *gfa.state += "a1" + res, err := next.Handle(request) + if err == nil { + *gfa.state += "a2" + } + return res, err } type globalTestFilterB struct { @@ -169,12 +171,11 @@ func (gfb globalTestFilterB) FilterMatchers() []web.FilterMatcher { } } -func (gfb globalTestFilterB) Run(request *web.Request, next web.Handler) (*web.Response,error) { - *gfb.state += "b1" - res, err := next.Handle(request) - if err == nil { - *gfb.state += "b2" - } - return res, err +func (gfb globalTestFilterB) Run(request *web.Request, next web.Handler) (*web.Response, error) { + *gfb.state += "b1" + res, err := next.Handle(request) + if err == nil { + *gfb.state += "b2" + } + return res, err } - diff --git a/vendor/github.com/Peripli/service-manager/test/healthcheck_test/healthcheck_test.go b/vendor/github.com/Peripli/service-manager/test/healthcheck_test/healthcheck_test.go index ad997a76..bac36128 100644 --- a/vendor/github.com/Peripli/service-manager/test/healthcheck_test/healthcheck_test.go +++ b/vendor/github.com/Peripli/service-manager/test/healthcheck_test/healthcheck_test.go @@ -36,7 +36,7 @@ var _ = Describe("Healthcheck API", func() { var ctx *common.TestContext BeforeSuite(func() { - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { diff --git a/vendor/github.com/Peripli/service-manager/test/info_test/info_test.go b/vendor/github.com/Peripli/service-manager/test/info_test/info_test.go index 9cc6487b..4eb52bde 100644 --- a/vendor/github.com/Peripli/service-manager/test/info_test/info_test.go +++ b/vendor/github.com/Peripli/service-manager/test/info_test/info_test.go @@ -36,7 +36,7 @@ var _ = Describe("Info API", func() { var ctx *common.TestContext BeforeSuite(func() { - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { diff --git a/vendor/github.com/Peripli/service-manager/test/osb_test/osb_test.go b/vendor/github.com/Peripli/service-manager/test/osb_test/osb_test.go index d5663af5..3a9b4186 100644 --- a/vendor/github.com/Peripli/service-manager/test/osb_test/osb_test.go +++ b/vendor/github.com/Peripli/service-manager/test/osb_test/osb_test.go @@ -63,14 +63,15 @@ func getDummyService(idsToRemove ...string) *object { var _ = Describe("Service Manager OSB API", func() { var ( - ctx *common.TestContext - validBroker, failingBroker *common.Broker + ctx *common.TestContext + validBroker, failingBroker, brokerWithPrefix *common.Broker ) BeforeSuite(func() { - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) validBroker = ctx.RegisterBroker("broker1", common.SetupFakeServiceBrokerServer("broker1")) failingBroker = ctx.RegisterBroker("broker2", common.SetupFakeFailingBrokerServer("broker2")) + brokerWithPrefix = ctx.RegisterBroker("broker3", common.SetupFakeServiceBrokerServerWithPrefix("broker3", "/sm")) }) AfterSuite(func() { @@ -234,25 +235,12 @@ var _ = Describe("Service Manager OSB API", func() { }) Describe("Prefixed broker path", func() { + Context("when call to working broker", func() { + It("should get catalog", func() { + resp := ctx.SMWithBasic.GET(brokerWithPrefix.OSBURL + "/v2/catalog"). + Expect().Status(http.StatusOK).JSON().Object() - Describe("Catalog", func() { - - BeforeEach(func() { - ctx = common.NewTestContextFromAPIs(nil) - validBroker = ctx.RegisterBroker("broker1", common.SetupFakeServiceBrokerServerWithPrefix("broker1", "/sm")) - }) - - AfterEach(func() { - ctx.Cleanup() - }) - - Context("when call to working broker", func() { - It("should get catalog", func() { - resp := ctx.SMWithBasic.GET(validBroker.OSBURL+"/v2/catalog").WithHeader("X-Broker-API-Version", "oidc_authn.13"). - Expect().Status(http.StatusOK).JSON().Object() - - resp.ContainsKey("services") - }) + resp.ContainsKey("services") }) }) }) diff --git a/vendor/github.com/Peripli/service-manager/test/platform_test/platform_test.go b/vendor/github.com/Peripli/service-manager/test/platform_test/platform_test.go index d5c24a3d..c40f2538 100644 --- a/vendor/github.com/Peripli/service-manager/test/platform_test/platform_test.go +++ b/vendor/github.com/Peripli/service-manager/test/platform_test/platform_test.go @@ -38,7 +38,7 @@ var _ = Describe("Service Manager Platform API", func() { var ctx *common.TestContext BeforeSuite(func() { - ctx = common.NewTestContextFromAPIs(nil) + ctx = common.NewTestContext(nil) }) AfterSuite(func() { diff --git a/vendor/github.com/Peripli/service-manager/test/plugin_test/plugin_test.go b/vendor/github.com/Peripli/service-manager/test/plugin_test/plugin_test.go index 6cdd0b5f..1300a037 100644 --- a/vendor/github.com/Peripli/service-manager/test/plugin_test/plugin_test.go +++ b/vendor/github.com/Peripli/service-manager/test/plugin_test/plugin_test.go @@ -34,7 +34,11 @@ var _ = Describe("Service Manager Plugins", func() { Describe("Partial plugin", func() { BeforeEach(func() { - ctx = common.NewTestContextFromAPIs([]web.Plugin{&PartialPlugin{}}) + ctx = common.NewTestContext(&common.ContextParams{ + RegisterExtensions: func(api *web.API) { + api.RegisterPlugins(&PartialPlugin{}) + }, + }) testBroker = ctx.RegisterBroker("broker1", nil) }) @@ -60,30 +64,34 @@ var _ = Describe("Service Manager Plugins", func() { }) JustBeforeEach(func() { - ctx = common.NewTestContextFromAPIs([]web.Plugin{testPlugin}) + ctx = common.NewTestContext(&common.ContextParams{ + RegisterExtensions: func(api *web.API) { + api.RegisterPlugins(testPlugin) + }, + }) testBroker = ctx.RegisterBroker("broker1", nil) }) It("Plugin modifies the request & response body", func() { var resBodySize int testPlugin["provision"] = web.MiddlewareFunc(func(req *web.Request, next web.Handler) (*web.Response, error) { - var err error - req.Body, err = sjson.SetBytes(req.Body, "extra", "request") - if err != nil { - return nil, err - } + var err error + req.Body, err = sjson.SetBytes(req.Body, "extra", "request") + if err != nil { + return nil, err + } - res, err := next.Handle(req) - if err != nil { - return nil, err - } + res, err := next.Handle(req) + if err != nil { + return nil, err + } - res.Body, err = sjson.SetBytes(res.Body, "extra", "response") - if err != nil { - return nil, err - } - resBodySize = len(res.Body) - return res, nil + res.Body, err = sjson.SetBytes(res.Body, "extra", "response") + if err != nil { + return nil, err + } + resBodySize = len(res.Body) + return res, nil }) testBroker.StatusCode = http.StatusCreated @@ -108,16 +116,16 @@ var _ = Describe("Service Manager Plugins", func() { It("Plugin modifies the request & response headers", func() { testPlugin["fetchCatalog"] = web.MiddlewareFunc(func(req *web.Request, next web.Handler) (*web.Response, error) { - h := req.Header.Get("extra") - req.Header.Set("extra", h+"-request") + h := req.Header.Get("extra") + req.Header.Set("extra", h+"-request") - res, err := next.Handle(req) - if err != nil { - return nil, err - } + res, err := next.Handle(req) + if err != nil { + return nil, err + } - res.Header.Set("extra", h+"-response") - return res, nil + res.Header.Set("extra", h+"-response") + return res, nil }) testBroker.StatusCode = http.StatusOK @@ -129,11 +137,11 @@ var _ = Describe("Service Manager Plugins", func() { It("Plugin aborts the request", func() { testPlugin["fetchCatalog"] = web.MiddlewareFunc(func(req *web.Request, next web.Handler) (*web.Response, error) { - return nil, &util.HTTPError{ - ErrorType: "PluginErr", - Description: "Plugin error", - StatusCode: http.StatusBadRequest, - } + return nil, &util.HTTPError{ + ErrorType: "PluginErr", + Description: "Plugin error", + StatusCode: http.StatusBadRequest, + } }) ctx.SMWithBasic.GET(testBroker.OSBURL + "/v2/catalog"). @@ -174,11 +182,11 @@ var _ = Describe("Service Manager Plugins", func() { op := op It(fmt.Sprintf("Plugin intercepts %s operation", op.name), func() { testPlugin[op.name] = web.MiddlewareFunc(func(req *web.Request, next web.Handler) (*web.Response, error) { - res, err := next.Handle(req) - if err == nil { - res.Header.Set("X-Plugin", op.name) - } - return res, err + res, err := next.Handle(req) + if err == nil { + res.Header.Set("X-Plugin", op.name) + } + return res, err }) for _, query := range op.queries { @@ -200,10 +208,10 @@ type TestPlugin map[string]web.Middleware func (p TestPlugin) Name() string { return "TestPlugin" } func (p TestPlugin) call(middleware web.Middleware, req *web.Request, next web.Handler) (*web.Response, error) { - if middleware == nil { - return next.Handle(req) - } - return middleware.Run(req, next) + if middleware == nil { + return next.Handle(req) + } + return middleware.Run(req, next) } func (p TestPlugin) FetchCatalog(request *web.Request, next web.Handler) (*web.Response, error) { @@ -211,38 +219,38 @@ func (p TestPlugin) FetchCatalog(request *web.Request, next web.Handler) (*web.R } func (p TestPlugin) Provision(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["provision"], request,next) + return p.call(p["provision"], request, next) } func (p TestPlugin) Deprovision(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["deprovision"], request,next) + return p.call(p["deprovision"], request, next) } func (p TestPlugin) UpdateService(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["updateService"],request, next) + return p.call(p["updateService"], request, next) } func (p TestPlugin) FetchService(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["fetchService"],request, next) + return p.call(p["fetchService"], request, next) } func (p TestPlugin) Bind(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["bind"], request,next) + return p.call(p["bind"], request, next) } func (p TestPlugin) Unbind(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["unbind"],request, next) + return p.call(p["unbind"], request, next) } func (p TestPlugin) FetchBinding(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["fetchBinding"],request, next) + return p.call(p["fetchBinding"], request, next) } func (p TestPlugin) PollInstance(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["pollInstance"], request,next) + return p.call(p["pollInstance"], request, next) } func (p TestPlugin) PollBinding(request *web.Request, next web.Handler) (*web.Response, error) { - return p.call(p["pollBinding"],request, next) + return p.call(p["pollBinding"], request, next) } type PartialPlugin struct{} diff --git a/vendor/github.com/Peripli/service-manager/test/security_test/two_layer_encrypter_test.go b/vendor/github.com/Peripli/service-manager/test/security_test/two_layer_encrypter_test.go index 4d7e478e..ddc4de85 100644 --- a/vendor/github.com/Peripli/service-manager/test/security_test/two_layer_encrypter_test.go +++ b/vendor/github.com/Peripli/service-manager/test/security_test/two_layer_encrypter_test.go @@ -17,6 +17,7 @@ package security_test import ( + "context" "crypto/rand" "fmt" "log" @@ -60,7 +61,7 @@ var _ = Describe("Encrypter", func() { fetcher.GetEncryptionKeyReturns(nil, expectedError) }) It("Should return error", func() { - encryptedString, err := encrypter.Encrypt(plaintext) + encryptedString, err := encrypter.Encrypt(context.TODO(), plaintext) Expect(encryptedString).To(BeNil()) Expect(err).To(Equal(expectedError)) }) @@ -72,7 +73,7 @@ var _ = Describe("Encrypter", func() { fetcher.GetEncryptionKeyReturns(encryptionKey, nil) }) It("Should encrypt the data", func() { - encryptedString, err := encrypter.Encrypt(plaintext) + encryptedString, err := encrypter.Encrypt(context.TODO(), plaintext) Expect(encryptedString).To(Not(BeNil())) Expect(err).To(BeNil()) }) @@ -87,7 +88,7 @@ var _ = Describe("Encrypter", func() { fetcher.GetEncryptionKeyReturns(nil, expectedError) }) It("Should return error", func() { - encryptedString, err := encrypter.Decrypt([]byte("cipher")) + encryptedString, err := encrypter.Decrypt(context.TODO(), []byte("cipher")) Expect(encryptedString).To(BeNil()) Expect(err).To(Equal(expectedError)) }) @@ -101,8 +102,8 @@ var _ = Describe("Encrypter", func() { fetcher.GetEncryptionKeyReturns(encryptionKey, nil) }) It("Should decrypt the data", func() { - encryptedString, _ := encrypter.Encrypt(plaintext) - decryptedBytes, err := encrypter.Decrypt(encryptedString) + encryptedString, _ := encrypter.Encrypt(context.TODO(), plaintext) + decryptedBytes, err := encrypter.Decrypt(context.TODO(), encryptedString) Expect(decryptedBytes).To(Not(BeNil())) Expect(err).To(BeNil()) Expect(decryptedBytes).To(Equal(plaintext)) diff --git a/vendor/github.com/Peripli/service-manager/test/sm/sm_test.go b/vendor/github.com/Peripli/service-manager/test/sm/sm_test.go index 9a62389b..70afa494 100644 --- a/vendor/github.com/Peripli/service-manager/test/sm/sm_test.go +++ b/vendor/github.com/Peripli/service-manager/test/sm/sm_test.go @@ -46,9 +46,9 @@ func TestServiceManager(t *testing.T) { var _ = Describe("SM", func() { var ( - serviceManagerServer *httptest.Server - ctx context.Context - cancel context.CancelFunc + ctx context.Context + cancel context.CancelFunc + oauthServer *common.OAuthServer ) BeforeSuite(func() { @@ -56,22 +56,16 @@ var _ = Describe("SM", func() { ctx, cancel = context.WithCancel(context.Background()) os.Chdir("../..") os.Setenv("FILE_LOCATION", "test/common") + oauthServer = common.NewOAuthServer() + oauthServer.Start() + os.Setenv("API_TOKEN_ISSUER_URL", oauthServer.URL) }) AfterSuite(func() { defer cancel() os.Unsetenv("FILE_LOCATION") - }) - - BeforeEach(func() { - os.Setenv("API_TOKEN_ISSUER_URL", common.SetupFakeOAuthServer().URL) - }) - - AfterEach(func() { + oauthServer.Close() os.Unsetenv("API_TOKEN_ISSUER_URL") - if serviceManagerServer != nil { - serviceManagerServer.Close() - } }) Describe("New", func() { diff --git a/vendor/github.com/gorilla/handlers/.travis.yml b/vendor/github.com/gorilla/handlers/.travis.yml deleted file mode 100644 index 1ba74af1..00000000 --- a/vendor/github.com/gorilla/handlers/.travis.yml +++ /dev/null @@ -1,20 +0,0 @@ -language: go -sudo: false - -matrix: - include: - - go: 1.4 - - go: 1.5 - - go: 1.6 - - go: 1.7 - - go: 1.8 - - go: tip - allow_failures: - - go: tip - -script: - - go get -t -v ./... - - diff -u <(echo -n) <(gofmt -d .) - - go vet $(go list ./... | grep -v /vendor/) - - go test -v -race ./... - diff --git a/vendor/github.com/gorilla/handlers/LICENSE b/vendor/github.com/gorilla/handlers/LICENSE deleted file mode 100644 index 66ea3c8a..00000000 --- a/vendor/github.com/gorilla/handlers/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2013 The Gorilla Handlers Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - Redistributions of source code must retain the above copyright notice, this - list of conditions and the following disclaimer. - - Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/handlers/README.md b/vendor/github.com/gorilla/handlers/README.md deleted file mode 100644 index 4a6895dc..00000000 --- a/vendor/github.com/gorilla/handlers/README.md +++ /dev/null @@ -1,55 +0,0 @@ -gorilla/handlers -================ -[![GoDoc](https://godoc.org/github.com/gorilla/handlers?status.svg)](https://godoc.org/github.com/gorilla/handlers) [![Build Status](https://travis-ci.org/gorilla/handlers.svg?branch=master)](https://travis-ci.org/gorilla/handlers) -[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/handlers/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/handlers?badge) - - -Package handlers is a collection of handlers (aka "HTTP middleware") for use -with Go's `net/http` package (or any framework supporting `http.Handler`), including: - -* [**LoggingHandler**](https://godoc.org/github.com/gorilla/handlers#LoggingHandler) for logging HTTP requests in the Apache [Common Log - Format](http://httpd.apache.org/docs/2.2/logs.html#common). -* [**CombinedLoggingHandler**](https://godoc.org/github.com/gorilla/handlers#CombinedLoggingHandler) for logging HTTP requests in the Apache [Combined Log - Format](http://httpd.apache.org/docs/2.2/logs.html#combined) commonly used by - both Apache and nginx. -* [**CompressHandler**](https://godoc.org/github.com/gorilla/handlers#CompressHandler) for gzipping responses. -* [**ContentTypeHandler**](https://godoc.org/github.com/gorilla/handlers#ContentTypeHandler) for validating requests against a list of accepted - content types. -* [**MethodHandler**](https://godoc.org/github.com/gorilla/handlers#MethodHandler) for matching HTTP methods against handlers in a - `map[string]http.Handler` -* [**ProxyHeaders**](https://godoc.org/github.com/gorilla/handlers#ProxyHeaders) for populating `r.RemoteAddr` and `r.URL.Scheme` based on the - `X-Forwarded-For`, `X-Real-IP`, `X-Forwarded-Proto` and RFC7239 `Forwarded` - headers when running a Go server behind a HTTP reverse proxy. -* [**CanonicalHost**](https://godoc.org/github.com/gorilla/handlers#CanonicalHost) for re-directing to the preferred host when handling multiple - domains (i.e. multiple CNAME aliases). -* [**RecoveryHandler**](https://godoc.org/github.com/gorilla/handlers#RecoveryHandler) for recovering from unexpected panics. - -Other handlers are documented [on the Gorilla -website](http://www.gorillatoolkit.org/pkg/handlers). - -## Example - -A simple example using `handlers.LoggingHandler` and `handlers.CompressHandler`: - -```go -import ( - "net/http" - "github.com/gorilla/handlers" -) - -func main() { - r := http.NewServeMux() - - // Only log requests to our admin dashboard to stdout - r.Handle("/admin", handlers.LoggingHandler(os.Stdout, http.HandlerFunc(ShowAdminDashboard))) - r.HandleFunc("/", ShowIndex) - - // Wrap our server with our gzip handler to gzip compress all responses. - http.ListenAndServe(":8000", handlers.CompressHandler(r)) -} -``` - -## License - -BSD licensed. See the included LICENSE file for details. - diff --git a/vendor/github.com/gorilla/handlers/canonical.go b/vendor/github.com/gorilla/handlers/canonical.go deleted file mode 100644 index 8437fefc..00000000 --- a/vendor/github.com/gorilla/handlers/canonical.go +++ /dev/null @@ -1,74 +0,0 @@ -package handlers - -import ( - "net/http" - "net/url" - "strings" -) - -type canonical struct { - h http.Handler - domain string - code int -} - -// CanonicalHost is HTTP middleware that re-directs requests to the canonical -// domain. It accepts a domain and a status code (e.g. 301 or 302) and -// re-directs clients to this domain. The existing request path is maintained. -// -// Note: If the provided domain is considered invalid by url.Parse or otherwise -// returns an empty scheme or host, clients are not re-directed. -// -// Example: -// -// r := mux.NewRouter() -// canonical := handlers.CanonicalHost("http://www.gorillatoolkit.org", 302) -// r.HandleFunc("/route", YourHandler) -// -// log.Fatal(http.ListenAndServe(":7000", canonical(r))) -// -func CanonicalHost(domain string, code int) func(h http.Handler) http.Handler { - fn := func(h http.Handler) http.Handler { - return canonical{h, domain, code} - } - - return fn -} - -func (c canonical) ServeHTTP(w http.ResponseWriter, r *http.Request) { - dest, err := url.Parse(c.domain) - if err != nil { - // Call the next handler if the provided domain fails to parse. - c.h.ServeHTTP(w, r) - return - } - - if dest.Scheme == "" || dest.Host == "" { - // Call the next handler if the scheme or host are empty. - // Note that url.Parse won't fail on in this case. - c.h.ServeHTTP(w, r) - return - } - - if !strings.EqualFold(cleanHost(r.Host), dest.Host) { - // Re-build the destination URL - dest := dest.Scheme + "://" + dest.Host + r.URL.Path - if r.URL.RawQuery != "" { - dest += "?" + r.URL.RawQuery - } - http.Redirect(w, r, dest, c.code) - return - } - - c.h.ServeHTTP(w, r) -} - -// cleanHost cleans invalid Host headers by stripping anything after '/' or ' '. -// This is backported from Go 1.5 (in response to issue #11206) and attempts to -// mitigate malformed Host headers that do not match the format in RFC7230. -func cleanHost(in string) string { - if i := strings.IndexAny(in, " /"); i != -1 { - return in[:i] - } - return in -} diff --git a/vendor/github.com/gorilla/handlers/canonical_test.go b/vendor/github.com/gorilla/handlers/canonical_test.go deleted file mode 100644 index 615e4b05..00000000 --- a/vendor/github.com/gorilla/handlers/canonical_test.go +++ /dev/null @@ -1,127 +0,0 @@ -package handlers - -import ( - "bufio" - "bytes" - "log" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" -) - -func TestCleanHost(t *testing.T) { - tests := []struct { - in, want string - }{ - {"www.google.com", "www.google.com"}, - {"www.google.com foo", "www.google.com"}, - {"www.google.com/foo", "www.google.com"}, - {" first character is a space", ""}, - } - for _, tt := range tests { - got := cleanHost(tt.in) - if tt.want != got { - t.Errorf("cleanHost(%q) = %q, want %q", tt.in, got, tt.want) - } - } -} - -func TestCanonicalHost(t *testing.T) { - gorilla := "http://www.gorillatoolkit.org" - - rr := httptest.NewRecorder() - r := newRequest("GET", "http://www.example.com/") - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - // Test a re-direct: should return a 302 Found. - CanonicalHost(gorilla, http.StatusFound)(testHandler).ServeHTTP(rr, r) - - if rr.Code != http.StatusFound { - t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusFound) - } - - if rr.Header().Get("Location") != gorilla+r.URL.Path { - t.Fatalf("bad re-direct: got %q want %q", rr.Header().Get("Location"), gorilla+r.URL.Path) - } - -} - -func TestKeepsQueryString(t *testing.T) { - google := "https://www.google.com" - - rr := httptest.NewRecorder() - querystring := url.Values{"q": {"golang"}, "format": {"json"}}.Encode() - r := newRequest("GET", "http://www.example.com/search?"+querystring) - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - CanonicalHost(google, http.StatusFound)(testHandler).ServeHTTP(rr, r) - - want := google + r.URL.Path + "?" + querystring - if rr.Header().Get("Location") != want { - t.Fatalf("bad re-direct: got %q want %q", rr.Header().Get("Location"), want) - } -} - -func TestBadDomain(t *testing.T) { - rr := httptest.NewRecorder() - r := newRequest("GET", "http://www.example.com/") - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - // Test a bad domain - should return 200 OK. - CanonicalHost("%", http.StatusFound)(testHandler).ServeHTTP(rr, r) - - if rr.Code != http.StatusOK { - t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusOK) - } -} - -func TestEmptyHost(t *testing.T) { - rr := httptest.NewRecorder() - r := newRequest("GET", "http://www.example.com/") - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - // Test a domain that returns an empty url.Host from url.Parse. - CanonicalHost("hello.com", http.StatusFound)(testHandler).ServeHTTP(rr, r) - - if rr.Code != http.StatusOK { - t.Fatalf("bad status: got %v want %v", rr.Code, http.StatusOK) - } -} - -func TestHeaderWrites(t *testing.T) { - gorilla := "http://www.gorillatoolkit.org" - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(200) - }) - - // Catch the log output to ensure we don't write multiple headers. - var b bytes.Buffer - buf := bufio.NewWriter(&b) - tl := log.New(buf, "test: ", log.Lshortfile) - - srv := httptest.NewServer( - CanonicalHost(gorilla, http.StatusFound)(testHandler)) - defer srv.Close() - srv.Config.ErrorLog = tl - - _, err := http.Get(srv.URL) - if err != nil { - t.Fatal(err) - } - - err = buf.Flush() - if err != nil { - t.Fatal(err) - } - - // We rely on the error not changing: net/http does not export it. - if strings.Contains(b.String(), "multiple response.WriteHeader calls") { - t.Fatalf("re-direct did not return early: multiple header writes") - } -} diff --git a/vendor/github.com/gorilla/handlers/compress.go b/vendor/github.com/gorilla/handlers/compress.go deleted file mode 100644 index e8345d79..00000000 --- a/vendor/github.com/gorilla/handlers/compress.go +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "compress/flate" - "compress/gzip" - "io" - "net/http" - "strings" -) - -type compressResponseWriter struct { - io.Writer - http.ResponseWriter - http.Hijacker - http.Flusher - http.CloseNotifier -} - -func (w *compressResponseWriter) WriteHeader(c int) { - w.ResponseWriter.Header().Del("Content-Length") - w.ResponseWriter.WriteHeader(c) -} - -func (w *compressResponseWriter) Header() http.Header { - return w.ResponseWriter.Header() -} - -func (w *compressResponseWriter) Write(b []byte) (int, error) { - h := w.ResponseWriter.Header() - if h.Get("Content-Type") == "" { - h.Set("Content-Type", http.DetectContentType(b)) - } - h.Del("Content-Length") - - return w.Writer.Write(b) -} - -type flusher interface { - Flush() error -} - -func (w *compressResponseWriter) Flush() { - // Flush compressed data if compressor supports it. - if f, ok := w.Writer.(flusher); ok { - f.Flush() - } - // Flush HTTP response. - if w.Flusher != nil { - w.Flusher.Flush() - } -} - -// CompressHandler gzip compresses HTTP responses for clients that support it -// via the 'Accept-Encoding' header. -// -// Compressing TLS traffic may leak the page contents to an attacker if the -// page contains user input: http://security.stackexchange.com/a/102015/12208 -func CompressHandler(h http.Handler) http.Handler { - return CompressHandlerLevel(h, gzip.DefaultCompression) -} - -// CompressHandlerLevel gzip compresses HTTP responses with specified compression level -// for clients that support it via the 'Accept-Encoding' header. -// -// The compression level should be gzip.DefaultCompression, gzip.NoCompression, -// or any integer value between gzip.BestSpeed and gzip.BestCompression inclusive. -// gzip.DefaultCompression is used in case of invalid compression level. -func CompressHandlerLevel(h http.Handler, level int) http.Handler { - if level < gzip.DefaultCompression || level > gzip.BestCompression { - level = gzip.DefaultCompression - } - - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - L: - for _, enc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") { - switch strings.TrimSpace(enc) { - case "gzip": - w.Header().Set("Content-Encoding", "gzip") - w.Header().Add("Vary", "Accept-Encoding") - - gw, _ := gzip.NewWriterLevel(w, level) - defer gw.Close() - - h, hok := w.(http.Hijacker) - if !hok { /* w is not Hijacker... oh well... */ - h = nil - } - - f, fok := w.(http.Flusher) - if !fok { - f = nil - } - - cn, cnok := w.(http.CloseNotifier) - if !cnok { - cn = nil - } - - w = &compressResponseWriter{ - Writer: gw, - ResponseWriter: w, - Hijacker: h, - Flusher: f, - CloseNotifier: cn, - } - - break L - case "deflate": - w.Header().Set("Content-Encoding", "deflate") - w.Header().Add("Vary", "Accept-Encoding") - - fw, _ := flate.NewWriter(w, level) - defer fw.Close() - - h, hok := w.(http.Hijacker) - if !hok { /* w is not Hijacker... oh well... */ - h = nil - } - - f, fok := w.(http.Flusher) - if !fok { - f = nil - } - - cn, cnok := w.(http.CloseNotifier) - if !cnok { - cn = nil - } - - w = &compressResponseWriter{ - Writer: fw, - ResponseWriter: w, - Hijacker: h, - Flusher: f, - CloseNotifier: cn, - } - - break L - } - } - - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/handlers/compress_test.go b/vendor/github.com/gorilla/handlers/compress_test.go deleted file mode 100644 index 6f07f440..00000000 --- a/vendor/github.com/gorilla/handlers/compress_test.go +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "bufio" - "io" - "net" - "net/http" - "net/http/httptest" - "strconv" - "testing" -) - -var contentType = "text/plain; charset=utf-8" - -func compressedRequest(w *httptest.ResponseRecorder, compression string) { - CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.Header().Set("Content-Length", strconv.Itoa(9*1024)) - w.Header().Set("Content-Type", contentType) - for i := 0; i < 1024; i++ { - io.WriteString(w, "Gorilla!\n") - } - })).ServeHTTP(w, &http.Request{ - Method: "GET", - Header: http.Header{ - "Accept-Encoding": []string{compression}, - }, - }) - -} - -func TestCompressHandlerNoCompression(t *testing.T) { - w := httptest.NewRecorder() - compressedRequest(w, "") - if enc := w.HeaderMap.Get("Content-Encoding"); enc != "" { - t.Errorf("wrong content encoding, got %q want %q", enc, "") - } - if ct := w.HeaderMap.Get("Content-Type"); ct != contentType { - t.Errorf("wrong content type, got %q want %q", ct, contentType) - } - if w.Body.Len() != 1024*9 { - t.Errorf("wrong len, got %d want %d", w.Body.Len(), 1024*9) - } - if l := w.HeaderMap.Get("Content-Length"); l != "9216" { - t.Errorf("wrong content-length. got %q expected %d", l, 1024*9) - } -} - -func TestCompressHandlerGzip(t *testing.T) { - w := httptest.NewRecorder() - compressedRequest(w, "gzip") - if w.HeaderMap.Get("Content-Encoding") != "gzip" { - t.Errorf("wrong content encoding, got %q want %q", w.HeaderMap.Get("Content-Encoding"), "gzip") - } - if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { - t.Errorf("wrong content type, got %s want %s", w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") - } - if w.Body.Len() != 72 { - t.Errorf("wrong len, got %d want %d", w.Body.Len(), 72) - } - if l := w.HeaderMap.Get("Content-Length"); l != "" { - t.Errorf("wrong content-length. got %q expected %q", l, "") - } -} - -func TestCompressHandlerDeflate(t *testing.T) { - w := httptest.NewRecorder() - compressedRequest(w, "deflate") - if w.HeaderMap.Get("Content-Encoding") != "deflate" { - t.Fatalf("wrong content encoding, got %q want %q", w.HeaderMap.Get("Content-Encoding"), "deflate") - } - if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { - t.Fatalf("wrong content type, got %s want %s", w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") - } - if w.Body.Len() != 54 { - t.Fatalf("wrong len, got %d want %d", w.Body.Len(), 54) - } -} - -func TestCompressHandlerGzipDeflate(t *testing.T) { - w := httptest.NewRecorder() - compressedRequest(w, "gzip, deflate ") - if w.HeaderMap.Get("Content-Encoding") != "gzip" { - t.Fatalf("wrong content encoding, got %q want %q", w.HeaderMap.Get("Content-Encoding"), "gzip") - } - if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" { - t.Fatalf("wrong content type, got %s want %s", w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8") - } -} - -type fullyFeaturedResponseWriter struct{} - -// Header/Write/WriteHeader implement the http.ResponseWriter interface. -func (fullyFeaturedResponseWriter) Header() http.Header { - return http.Header{} -} -func (fullyFeaturedResponseWriter) Write([]byte) (int, error) { - return 0, nil -} -func (fullyFeaturedResponseWriter) WriteHeader(int) {} - -// Flush implements the http.Flusher interface. -func (fullyFeaturedResponseWriter) Flush() {} - -// Hijack implements the http.Hijacker interface. -func (fullyFeaturedResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { - return nil, nil, nil -} - -// CloseNotify implements the http.CloseNotifier interface. -func (fullyFeaturedResponseWriter) CloseNotify() <-chan bool { - return nil -} - -func TestCompressHandlerPreserveInterfaces(t *testing.T) { - // Compile time validation fullyFeaturedResponseWriter implements all the - // interfaces we're asserting in the test case below. - var ( - _ http.Flusher = fullyFeaturedResponseWriter{} - _ http.CloseNotifier = fullyFeaturedResponseWriter{} - _ http.Hijacker = fullyFeaturedResponseWriter{} - ) - var h http.Handler = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { - comp := r.Header.Get("Accept-Encoding") - if _, ok := rw.(*compressResponseWriter); !ok { - t.Fatalf("ResponseWriter wasn't wrapped by compressResponseWriter, got %T type", rw) - } - if _, ok := rw.(http.Flusher); !ok { - t.Errorf("ResponseWriter lost http.Flusher interface for %q", comp) - } - if _, ok := rw.(http.CloseNotifier); !ok { - t.Errorf("ResponseWriter lost http.CloseNotifier interface for %q", comp) - } - if _, ok := rw.(http.Hijacker); !ok { - t.Errorf("ResponseWriter lost http.Hijacker interface for %q", comp) - } - }) - h = CompressHandler(h) - var ( - rw fullyFeaturedResponseWriter - ) - r, err := http.NewRequest("GET", "/", nil) - if err != nil { - t.Fatalf("Failed to create test request: %v", err) - } - r.Header.Set("Accept-Encoding", "gzip") - h.ServeHTTP(rw, r) - - r.Header.Set("Accept-Encoding", "deflate") - h.ServeHTTP(rw, r) -} diff --git a/vendor/github.com/gorilla/handlers/cors.go b/vendor/github.com/gorilla/handlers/cors.go deleted file mode 100644 index 1cf7581c..00000000 --- a/vendor/github.com/gorilla/handlers/cors.go +++ /dev/null @@ -1,327 +0,0 @@ -package handlers - -import ( - "net/http" - "strconv" - "strings" -) - -// CORSOption represents a functional option for configuring the CORS middleware. -type CORSOption func(*cors) error - -type cors struct { - h http.Handler - allowedHeaders []string - allowedMethods []string - allowedOrigins []string - allowedOriginValidator OriginValidator - exposedHeaders []string - maxAge int - ignoreOptions bool - allowCredentials bool -} - -// OriginValidator takes an origin string and returns whether or not that origin is allowed. -type OriginValidator func(string) bool - -var ( - defaultCorsMethods = []string{"GET", "HEAD", "POST"} - defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"} - // (WebKit/Safari v9 sends the Origin header by default in AJAX requests) -) - -const ( - corsOptionMethod string = "OPTIONS" - corsAllowOriginHeader string = "Access-Control-Allow-Origin" - corsExposeHeadersHeader string = "Access-Control-Expose-Headers" - corsMaxAgeHeader string = "Access-Control-Max-Age" - corsAllowMethodsHeader string = "Access-Control-Allow-Methods" - corsAllowHeadersHeader string = "Access-Control-Allow-Headers" - corsAllowCredentialsHeader string = "Access-Control-Allow-Credentials" - corsRequestMethodHeader string = "Access-Control-Request-Method" - corsRequestHeadersHeader string = "Access-Control-Request-Headers" - corsOriginHeader string = "Origin" - corsVaryHeader string = "Vary" - corsOriginMatchAll string = "*" -) - -func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) { - origin := r.Header.Get(corsOriginHeader) - if !ch.isOriginAllowed(origin) { - ch.h.ServeHTTP(w, r) - return - } - - if r.Method == corsOptionMethod { - if ch.ignoreOptions { - ch.h.ServeHTTP(w, r) - return - } - - if _, ok := r.Header[corsRequestMethodHeader]; !ok { - w.WriteHeader(http.StatusBadRequest) - return - } - - method := r.Header.Get(corsRequestMethodHeader) - if !ch.isMatch(method, ch.allowedMethods) { - w.WriteHeader(http.StatusMethodNotAllowed) - return - } - - requestHeaders := strings.Split(r.Header.Get(corsRequestHeadersHeader), ",") - allowedHeaders := []string{} - for _, v := range requestHeaders { - canonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if canonicalHeader == "" || ch.isMatch(canonicalHeader, defaultCorsHeaders) { - continue - } - - if !ch.isMatch(canonicalHeader, ch.allowedHeaders) { - w.WriteHeader(http.StatusForbidden) - return - } - - allowedHeaders = append(allowedHeaders, canonicalHeader) - } - - if len(allowedHeaders) > 0 { - w.Header().Set(corsAllowHeadersHeader, strings.Join(allowedHeaders, ",")) - } - - if ch.maxAge > 0 { - w.Header().Set(corsMaxAgeHeader, strconv.Itoa(ch.maxAge)) - } - - if !ch.isMatch(method, defaultCorsMethods) { - w.Header().Set(corsAllowMethodsHeader, method) - } - } else { - if len(ch.exposedHeaders) > 0 { - w.Header().Set(corsExposeHeadersHeader, strings.Join(ch.exposedHeaders, ",")) - } - } - - if ch.allowCredentials { - w.Header().Set(corsAllowCredentialsHeader, "true") - } - - if len(ch.allowedOrigins) > 1 { - w.Header().Set(corsVaryHeader, corsOriginHeader) - } - - returnOrigin := origin - for _, o := range ch.allowedOrigins { - // A configuration of * is different than explicitly setting an allowed - // origin. Returning arbitrary origin headers an an access control allow - // origin header is unsafe and is not required by any use case. - if o == corsOriginMatchAll { - returnOrigin = "*" - break - } - } - w.Header().Set(corsAllowOriginHeader, returnOrigin) - - if r.Method == corsOptionMethod { - return - } - ch.h.ServeHTTP(w, r) -} - -// CORS provides Cross-Origin Resource Sharing middleware. -// Example: -// -// import ( -// "net/http" -// -// "github.com/gorilla/handlers" -// "github.com/gorilla/mux" -// ) -// -// func main() { -// r := mux.NewRouter() -// r.HandleFunc("/users", UserEndpoint) -// r.HandleFunc("/projects", ProjectEndpoint) -// -// // Apply the CORS middleware to our top-level router, with the defaults. -// http.ListenAndServe(":8000", handlers.CORS()(r)) -// } -// -func CORS(opts ...CORSOption) func(http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - ch := parseCORSOptions(opts...) - ch.h = h - return ch - } -} - -func parseCORSOptions(opts ...CORSOption) *cors { - ch := &cors{ - allowedMethods: defaultCorsMethods, - allowedHeaders: defaultCorsHeaders, - allowedOrigins: []string{corsOriginMatchAll}, - } - - for _, option := range opts { - option(ch) - } - - return ch -} - -// -// Functional options for configuring CORS. -// - -// AllowedHeaders adds the provided headers to the list of allowed headers in a -// CORS request. -// This is an append operation so the headers Accept, Accept-Language, -// and Content-Language are always allowed. -// Content-Type must be explicitly declared if accepting Content-Types other than -// application/x-www-form-urlencoded, multipart/form-data, or text/plain. -func AllowedHeaders(headers []string) CORSOption { - return func(ch *cors) error { - for _, v := range headers { - normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if normalizedHeader == "" { - continue - } - - if !ch.isMatch(normalizedHeader, ch.allowedHeaders) { - ch.allowedHeaders = append(ch.allowedHeaders, normalizedHeader) - } - } - - return nil - } -} - -// AllowedMethods can be used to explicitly allow methods in the -// Access-Control-Allow-Methods header. -// This is a replacement operation so you must also -// pass GET, HEAD, and POST if you wish to support those methods. -func AllowedMethods(methods []string) CORSOption { - return func(ch *cors) error { - ch.allowedMethods = []string{} - for _, v := range methods { - normalizedMethod := strings.ToUpper(strings.TrimSpace(v)) - if normalizedMethod == "" { - continue - } - - if !ch.isMatch(normalizedMethod, ch.allowedMethods) { - ch.allowedMethods = append(ch.allowedMethods, normalizedMethod) - } - } - - return nil - } -} - -// AllowedOrigins sets the allowed origins for CORS requests, as used in the -// 'Allow-Access-Control-Origin' HTTP header. -// Note: Passing in a []string{"*"} will allow any domain. -func AllowedOrigins(origins []string) CORSOption { - return func(ch *cors) error { - for _, v := range origins { - if v == corsOriginMatchAll { - ch.allowedOrigins = []string{corsOriginMatchAll} - return nil - } - } - - ch.allowedOrigins = origins - return nil - } -} - -// AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the -// 'Allow-Access-Control-Origin' HTTP header. -func AllowedOriginValidator(fn OriginValidator) CORSOption { - return func(ch *cors) error { - ch.allowedOriginValidator = fn - return nil - } -} - -// ExposeHeaders can be used to specify headers that are available -// and will not be stripped out by the user-agent. -func ExposedHeaders(headers []string) CORSOption { - return func(ch *cors) error { - ch.exposedHeaders = []string{} - for _, v := range headers { - normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v)) - if normalizedHeader == "" { - continue - } - - if !ch.isMatch(normalizedHeader, ch.exposedHeaders) { - ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader) - } - } - - return nil - } -} - -// MaxAge determines the maximum age (in seconds) between preflight requests. A -// maximum of 10 minutes is allowed. An age above this value will default to 10 -// minutes. -func MaxAge(age int) CORSOption { - return func(ch *cors) error { - // Maximum of 10 minutes. - if age > 600 { - age = 600 - } - - ch.maxAge = age - return nil - } -} - -// IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, instead -// passing them through to the next handler. This is useful when your application -// or framework has a pre-existing mechanism for responding to OPTIONS requests. -func IgnoreOptions() CORSOption { - return func(ch *cors) error { - ch.ignoreOptions = true - return nil - } -} - -// AllowCredentials can be used to specify that the user agent may pass -// authentication details along with the request. -func AllowCredentials() CORSOption { - return func(ch *cors) error { - ch.allowCredentials = true - return nil - } -} - -func (ch *cors) isOriginAllowed(origin string) bool { - if origin == "" { - return false - } - - if ch.allowedOriginValidator != nil { - return ch.allowedOriginValidator(origin) - } - - for _, allowedOrigin := range ch.allowedOrigins { - if allowedOrigin == origin || allowedOrigin == corsOriginMatchAll { - return true - } - } - - return false -} - -func (ch *cors) isMatch(needle string, haystack []string) bool { - for _, v := range haystack { - if v == needle { - return true - } - } - - return false -} diff --git a/vendor/github.com/gorilla/handlers/cors_test.go b/vendor/github.com/gorilla/handlers/cors_test.go deleted file mode 100644 index 61eb18f7..00000000 --- a/vendor/github.com/gorilla/handlers/cors_test.go +++ /dev/null @@ -1,371 +0,0 @@ -package handlers - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestDefaultCORSHandlerReturnsOk(t *testing.T) { - r := newRequest("GET", "http://www.example.com/") - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusFound) - } -} - -func TestDefaultCORSHandlerReturnsOkWithOrigin(t *testing.T) { - r := newRequest("GET", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusFound) - } -} - -func TestCORSHandlerIgnoreOptionsFallsThrough(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - w.WriteHeader(http.StatusTeapot) - }) - - CORS(IgnoreOptions())(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusTeapot { - t.Fatalf("bad status: got %v want %v", status, http.StatusTeapot) - } -} - -func TestCORSHandlerSetsExposedHeaders(t *testing.T) { - // Test default configuration. - r := newRequest("GET", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(ExposedHeaders([]string{"X-CORS-TEST"}))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsExposeHeadersHeader) - if header != "X-Cors-Test" { - t.Fatal("bad header: expected X-Cors-Test header, got empty header for method.") - } -} - -func TestCORSHandlerUnsetRequestMethodForPreflightBadRequest(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(AllowedMethods([]string{"DELETE"}))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusBadRequest { - t.Fatalf("bad status: got %v want %v", status, http.StatusBadRequest) - } -} - -func TestCORSHandlerInvalidRequestMethodForPreflightMethodNotAllowed(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "DELETE") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusMethodNotAllowed { - t.Fatalf("bad status: got %v want %v", status, http.StatusMethodNotAllowed) - } -} - -func TestCORSHandlerOptionsRequestMustNotBePassedToNextHandler(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "GET") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - t.Fatal("Options request must not be passed to next handler") - }) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } -} - -func TestCORSHandlerAllowedMethodForPreflight(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "DELETE") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(AllowedMethods([]string{"DELETE"}))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsAllowMethodsHeader) - if header != "DELETE" { - t.Fatalf("bad header: expected DELETE method header, got empty header.") - } -} - -func TestCORSHandlerAllowMethodsNotSetForSimpleRequestPreflight(t *testing.T) { - for _, method := range defaultCorsMethods { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, method) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsAllowMethodsHeader) - if header != "" { - t.Fatalf("bad header: expected empty method header, got %s.", header) - } - } -} - -func TestCORSHandlerAllowedHeaderNotSetForSimpleRequestPreflight(t *testing.T) { - for _, simpleHeader := range defaultCorsHeaders { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "GET") - r.Header.Set(corsRequestHeadersHeader, simpleHeader) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsAllowHeadersHeader) - if header != "" { - t.Fatalf("bad header: expected empty header, got %s.", header) - } - } -} - -func TestCORSHandlerAllowedHeaderForPreflight(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "POST") - r.Header.Set(corsRequestHeadersHeader, "Content-Type") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(AllowedHeaders([]string{"Content-Type"}))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsAllowHeadersHeader) - if header != "Content-Type" { - t.Fatalf("bad header: expected Content-Type header, got empty header.") - } -} - -func TestCORSHandlerInvalidHeaderForPreflightForbidden(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "POST") - r.Header.Set(corsRequestHeadersHeader, "Content-Type") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS()(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusForbidden { - t.Fatalf("bad status: got %v want %v", status, http.StatusForbidden) - } -} - -func TestCORSHandlerMaxAgeForPreflight(t *testing.T) { - r := newRequest("OPTIONS", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - r.Header.Set(corsRequestMethodHeader, "POST") - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(MaxAge(3500))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsMaxAgeHeader) - if header != "600" { - t.Fatalf("bad header: expected %s to be %s, got %s.", corsMaxAgeHeader, "600", header) - } -} - -func TestCORSHandlerAllowedCredentials(t *testing.T) { - r := newRequest("GET", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(AllowCredentials())(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsAllowCredentialsHeader) - if header != "true" { - t.Fatalf("bad header: expected %s to be %s, got %s.", corsAllowCredentialsHeader, "true", header) - } -} - -func TestCORSHandlerMultipleAllowOriginsSetsVaryHeader(t *testing.T) { - r := newRequest("GET", "http://www.example.com/") - r.Header.Set("Origin", r.URL.String()) - - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - CORS(AllowedOrigins([]string{r.URL.String(), "http://google.com"}))(testHandler).ServeHTTP(rr, r) - - if status := rr.Code; status != http.StatusOK { - t.Fatalf("bad status: got %v want %v", status, http.StatusOK) - } - - header := rr.HeaderMap.Get(corsVaryHeader) - if header != corsOriginHeader { - t.Fatalf("bad header: expected %s to be %s, got %s.", corsVaryHeader, corsOriginHeader, header) - } -} - -func TestCORSWithMultipleHandlers(t *testing.T) { - var lastHandledBy string - corsMiddleware := CORS() - - testHandler1 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lastHandledBy = "testHandler1" - }) - testHandler2 := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - lastHandledBy = "testHandler2" - }) - - r1 := newRequest("GET", "http://www.example.com/") - rr1 := httptest.NewRecorder() - handler1 := corsMiddleware(testHandler1) - - corsMiddleware(testHandler2) - - handler1.ServeHTTP(rr1, r1) - if lastHandledBy != "testHandler1" { - t.Fatalf("bad CORS() registration: Handler served should be Handler registered") - } -} - -func TestCORSHandlerWithCustomValidator(t *testing.T) { - r := newRequest("GET", "http://a.example.com") - r.Header.Set("Origin", r.URL.String()) - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - - originValidator := func(origin string) bool { - if strings.HasSuffix(origin, ".example.com") { - return true - } - return false - } - - // Specially craft a CORS object. - handleFunc := func(h http.Handler) http.Handler { - c := &cors{ - allowedMethods: defaultCorsMethods, - allowedHeaders: defaultCorsHeaders, - allowedOrigins: []string{"http://a.example.com"}, - h: h, - } - AllowedOriginValidator(originValidator)(c) - return c - } - - handleFunc(testHandler).ServeHTTP(rr, r) - header := rr.HeaderMap.Get(corsAllowOriginHeader) - if header != r.URL.String() { - t.Fatalf("bad header: expected %s to be %s, got %s.", corsAllowOriginHeader, r.URL.String(), header) - } - -} - -func TestCORSAllowStar(t *testing.T) { - r := newRequest("GET", "http://a.example.com") - r.Header.Set("Origin", r.URL.String()) - rr := httptest.NewRecorder() - - testHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) - originValidator := func(origin string) bool { - if strings.HasSuffix(origin, ".example.com") { - return true - } - return false - } - - CORS(AllowedOriginValidator(originValidator))(testHandler).ServeHTTP(rr, r) - header := rr.HeaderMap.Get(corsAllowOriginHeader) - // Because * is the default CORS policy (which is safe), we should be - // expect a * returned here as the Access Control Allow Origin header - if header != "*" { - t.Fatalf("bad header: expected %s to be %s, got %s.", corsAllowOriginHeader, r.URL.String(), header) - } - -} diff --git a/vendor/github.com/gorilla/handlers/doc.go b/vendor/github.com/gorilla/handlers/doc.go deleted file mode 100644 index 944e5a8a..00000000 --- a/vendor/github.com/gorilla/handlers/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -/* -Package handlers is a collection of handlers (aka "HTTP middleware") for use -with Go's net/http package (or any framework supporting http.Handler). - -The package includes handlers for logging in standardised formats, compressing -HTTP responses, validating content types and other useful tools for manipulating -requests and responses. -*/ -package handlers diff --git a/vendor/github.com/gorilla/handlers/handlers.go b/vendor/github.com/gorilla/handlers/handlers.go deleted file mode 100644 index 75db7f87..00000000 --- a/vendor/github.com/gorilla/handlers/handlers.go +++ /dev/null @@ -1,399 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "bufio" - "fmt" - "io" - "net" - "net/http" - "net/url" - "sort" - "strconv" - "strings" - "time" - "unicode/utf8" -) - -// MethodHandler is an http.Handler that dispatches to a handler whose key in the -// MethodHandler's map matches the name of the HTTP request's method, eg: GET -// -// If the request's method is OPTIONS and OPTIONS is not a key in the map then -// the handler responds with a status of 200 and sets the Allow header to a -// comma-separated list of available methods. -// -// If the request's method doesn't match any of its keys the handler responds -// with a status of HTTP 405 "Method Not Allowed" and sets the Allow header to a -// comma-separated list of available methods. -type MethodHandler map[string]http.Handler - -func (h MethodHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - if handler, ok := h[req.Method]; ok { - handler.ServeHTTP(w, req) - } else { - allow := []string{} - for k := range h { - allow = append(allow, k) - } - sort.Strings(allow) - w.Header().Set("Allow", strings.Join(allow, ", ")) - if req.Method == "OPTIONS" { - w.WriteHeader(http.StatusOK) - } else { - http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) - } - } -} - -// loggingHandler is the http.Handler implementation for LoggingHandlerTo and its -// friends -type loggingHandler struct { - writer io.Writer - handler http.Handler -} - -// combinedLoggingHandler is the http.Handler implementation for LoggingHandlerTo -// and its friends -type combinedLoggingHandler struct { - writer io.Writer - handler http.Handler -} - -func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - t := time.Now() - logger := makeLogger(w) - url := *req.URL - h.handler.ServeHTTP(logger, req) - writeLog(h.writer, req, url, t, logger.Status(), logger.Size()) -} - -func (h combinedLoggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - t := time.Now() - logger := makeLogger(w) - url := *req.URL - h.handler.ServeHTTP(logger, req) - writeCombinedLog(h.writer, req, url, t, logger.Status(), logger.Size()) -} - -func makeLogger(w http.ResponseWriter) loggingResponseWriter { - var logger loggingResponseWriter = &responseLogger{w: w, status: http.StatusOK} - if _, ok := w.(http.Hijacker); ok { - logger = &hijackLogger{responseLogger{w: w, status: http.StatusOK}} - } - h, ok1 := logger.(http.Hijacker) - c, ok2 := w.(http.CloseNotifier) - if ok1 && ok2 { - return hijackCloseNotifier{logger, h, c} - } - if ok2 { - return &closeNotifyWriter{logger, c} - } - return logger -} - -type commonLoggingResponseWriter interface { - http.ResponseWriter - http.Flusher - Status() int - Size() int -} - -// responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP -// status code and body size -type responseLogger struct { - w http.ResponseWriter - status int - size int -} - -func (l *responseLogger) Header() http.Header { - return l.w.Header() -} - -func (l *responseLogger) Write(b []byte) (int, error) { - size, err := l.w.Write(b) - l.size += size - return size, err -} - -func (l *responseLogger) WriteHeader(s int) { - l.w.WriteHeader(s) - l.status = s -} - -func (l *responseLogger) Status() int { - return l.status -} - -func (l *responseLogger) Size() int { - return l.size -} - -func (l *responseLogger) Flush() { - f, ok := l.w.(http.Flusher) - if ok { - f.Flush() - } -} - -type hijackLogger struct { - responseLogger -} - -func (l *hijackLogger) Hijack() (net.Conn, *bufio.ReadWriter, error) { - h := l.responseLogger.w.(http.Hijacker) - conn, rw, err := h.Hijack() - if err == nil && l.responseLogger.status == 0 { - // The status will be StatusSwitchingProtocols if there was no error and - // WriteHeader has not been called yet - l.responseLogger.status = http.StatusSwitchingProtocols - } - return conn, rw, err -} - -type closeNotifyWriter struct { - loggingResponseWriter - http.CloseNotifier -} - -type hijackCloseNotifier struct { - loggingResponseWriter - http.Hijacker - http.CloseNotifier -} - -const lowerhex = "0123456789abcdef" - -func appendQuoted(buf []byte, s string) []byte { - var runeTmp [utf8.UTFMax]byte - for width := 0; len(s) > 0; s = s[width:] { - r := rune(s[0]) - width = 1 - if r >= utf8.RuneSelf { - r, width = utf8.DecodeRuneInString(s) - } - if width == 1 && r == utf8.RuneError { - buf = append(buf, `\x`...) - buf = append(buf, lowerhex[s[0]>>4]) - buf = append(buf, lowerhex[s[0]&0xF]) - continue - } - if r == rune('"') || r == '\\' { // always backslashed - buf = append(buf, '\\') - buf = append(buf, byte(r)) - continue - } - if strconv.IsPrint(r) { - n := utf8.EncodeRune(runeTmp[:], r) - buf = append(buf, runeTmp[:n]...) - continue - } - switch r { - case '\a': - buf = append(buf, `\a`...) - case '\b': - buf = append(buf, `\b`...) - case '\f': - buf = append(buf, `\f`...) - case '\n': - buf = append(buf, `\n`...) - case '\r': - buf = append(buf, `\r`...) - case '\t': - buf = append(buf, `\t`...) - case '\v': - buf = append(buf, `\v`...) - default: - switch { - case r < ' ': - buf = append(buf, `\x`...) - buf = append(buf, lowerhex[s[0]>>4]) - buf = append(buf, lowerhex[s[0]&0xF]) - case r > utf8.MaxRune: - r = 0xFFFD - fallthrough - case r < 0x10000: - buf = append(buf, `\u`...) - for s := 12; s >= 0; s -= 4 { - buf = append(buf, lowerhex[r>>uint(s)&0xF]) - } - default: - buf = append(buf, `\U`...) - for s := 28; s >= 0; s -= 4 { - buf = append(buf, lowerhex[r>>uint(s)&0xF]) - } - } - } - } - return buf - -} - -// buildCommonLogLine builds a log entry for req in Apache Common Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func buildCommonLogLine(req *http.Request, url url.URL, ts time.Time, status int, size int) []byte { - username := "-" - if url.User != nil { - if name := url.User.Username(); name != "" { - username = name - } - } - - host, _, err := net.SplitHostPort(req.RemoteAddr) - - if err != nil { - host = req.RemoteAddr - } - - uri := req.RequestURI - - // Requests using the CONNECT method over HTTP/2.0 must use - // the authority field (aka r.Host) to identify the target. - // Refer: https://httpwg.github.io/specs/rfc7540.html#CONNECT - if req.ProtoMajor == 2 && req.Method == "CONNECT" { - uri = req.Host - } - if uri == "" { - uri = url.RequestURI() - } - - buf := make([]byte, 0, 3*(len(host)+len(username)+len(req.Method)+len(uri)+len(req.Proto)+50)/2) - buf = append(buf, host...) - buf = append(buf, " - "...) - buf = append(buf, username...) - buf = append(buf, " ["...) - buf = append(buf, ts.Format("02/Jan/2006:15:04:05 -0700")...) - buf = append(buf, `] "`...) - buf = append(buf, req.Method...) - buf = append(buf, " "...) - buf = appendQuoted(buf, uri) - buf = append(buf, " "...) - buf = append(buf, req.Proto...) - buf = append(buf, `" `...) - buf = append(buf, strconv.Itoa(status)...) - buf = append(buf, " "...) - buf = append(buf, strconv.Itoa(size)...) - return buf -} - -// writeLog writes a log entry for req to w in Apache Common Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func writeLog(w io.Writer, req *http.Request, url url.URL, ts time.Time, status, size int) { - buf := buildCommonLogLine(req, url, ts, status, size) - buf = append(buf, '\n') - w.Write(buf) -} - -// writeCombinedLog writes a log entry for req to w in Apache Combined Log Format. -// ts is the timestamp with which the entry should be logged. -// status and size are used to provide the response HTTP status and size. -func writeCombinedLog(w io.Writer, req *http.Request, url url.URL, ts time.Time, status, size int) { - buf := buildCommonLogLine(req, url, ts, status, size) - buf = append(buf, ` "`...) - buf = appendQuoted(buf, req.Referer()) - buf = append(buf, `" "`...) - buf = appendQuoted(buf, req.UserAgent()) - buf = append(buf, '"', '\n') - w.Write(buf) -} - -// CombinedLoggingHandler return a http.Handler that wraps h and logs requests to out in -// Apache Combined Log Format. -// -// See http://httpd.apache.org/docs/2.2/logs.html#combined for a description of this format. -// -// LoggingHandler always sets the ident field of the log to - -func CombinedLoggingHandler(out io.Writer, h http.Handler) http.Handler { - return combinedLoggingHandler{out, h} -} - -// LoggingHandler return a http.Handler that wraps h and logs requests to out in -// Apache Common Log Format (CLF). -// -// See http://httpd.apache.org/docs/2.2/logs.html#common for a description of this format. -// -// LoggingHandler always sets the ident field of the log to - -// -// Example: -// -// r := mux.NewRouter() -// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -// w.Write([]byte("This is a catch-all route")) -// }) -// loggedRouter := handlers.LoggingHandler(os.Stdout, r) -// http.ListenAndServe(":1123", loggedRouter) -// -func LoggingHandler(out io.Writer, h http.Handler) http.Handler { - return loggingHandler{out, h} -} - -// isContentType validates the Content-Type header matches the supplied -// contentType. That is, its type and subtype match. -func isContentType(h http.Header, contentType string) bool { - ct := h.Get("Content-Type") - if i := strings.IndexRune(ct, ';'); i != -1 { - ct = ct[0:i] - } - return ct == contentType -} - -// ContentTypeHandler wraps and returns a http.Handler, validating the request -// content type is compatible with the contentTypes list. It writes a HTTP 415 -// error if that fails. -// -// Only PUT, POST, and PATCH requests are considered. -func ContentTypeHandler(h http.Handler, contentTypes ...string) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !(r.Method == "PUT" || r.Method == "POST" || r.Method == "PATCH") { - h.ServeHTTP(w, r) - return - } - - for _, ct := range contentTypes { - if isContentType(r.Header, ct) { - h.ServeHTTP(w, r) - return - } - } - http.Error(w, fmt.Sprintf("Unsupported content type %q; expected one of %q", r.Header.Get("Content-Type"), contentTypes), http.StatusUnsupportedMediaType) - }) -} - -const ( - // HTTPMethodOverrideHeader is a commonly used - // http header to override a request method. - HTTPMethodOverrideHeader = "X-HTTP-Method-Override" - // HTTPMethodOverrideFormKey is a commonly used - // HTML form key to override a request method. - HTTPMethodOverrideFormKey = "_method" -) - -// HTTPMethodOverrideHandler wraps and returns a http.Handler which checks for -// the X-HTTP-Method-Override header or the _method form key, and overrides (if -// valid) request.Method with its value. -// -// This is especially useful for HTTP clients that don't support many http verbs. -// It isn't secure to override e.g a GET to a POST, so only POST requests are -// considered. Likewise, the override method can only be a "write" method: PUT, -// PATCH or DELETE. -// -// Form method takes precedence over header method. -func HTTPMethodOverrideHandler(h http.Handler) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method == "POST" { - om := r.FormValue(HTTPMethodOverrideFormKey) - if om == "" { - om = r.Header.Get(HTTPMethodOverrideHeader) - } - if om == "PUT" || om == "PATCH" || om == "DELETE" { - r.Method = om - } - } - h.ServeHTTP(w, r) - }) -} diff --git a/vendor/github.com/gorilla/handlers/handlers_go18.go b/vendor/github.com/gorilla/handlers/handlers_go18.go deleted file mode 100644 index 35eb8d4f..00000000 --- a/vendor/github.com/gorilla/handlers/handlers_go18.go +++ /dev/null @@ -1,21 +0,0 @@ -// +build go1.8 - -package handlers - -import ( - "fmt" - "net/http" -) - -type loggingResponseWriter interface { - commonLoggingResponseWriter - http.Pusher -} - -func (l *responseLogger) Push(target string, opts *http.PushOptions) error { - p, ok := l.w.(http.Pusher) - if !ok { - return fmt.Errorf("responseLogger does not implement http.Pusher") - } - return p.Push(target, opts) -} diff --git a/vendor/github.com/gorilla/handlers/handlers_go18_test.go b/vendor/github.com/gorilla/handlers/handlers_go18_test.go deleted file mode 100644 index c8cfa722..00000000 --- a/vendor/github.com/gorilla/handlers/handlers_go18_test.go +++ /dev/null @@ -1,34 +0,0 @@ -// +build go1.8 - -package handlers - -import ( - "io/ioutil" - "net/http" - "net/http/httptest" - "testing" -) - -func TestLoggingHandlerWithPush(t *testing.T) { - handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if _, ok := w.(http.Pusher); !ok { - t.Fatalf("%T from LoggingHandler does not satisfy http.Pusher interface when built with Go >=1.8", w) - } - w.WriteHeader(200) - }) - - logger := LoggingHandler(ioutil.Discard, handler) - logger.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/")) -} - -func TestCombinedLoggingHandlerWithPush(t *testing.T) { - handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - if _, ok := w.(http.Pusher); !ok { - t.Fatalf("%T from CombinedLoggingHandler does not satisfy http.Pusher interface when built with Go >=1.8", w) - } - w.WriteHeader(200) - }) - - logger := CombinedLoggingHandler(ioutil.Discard, handler) - logger.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/")) -} diff --git a/vendor/github.com/gorilla/handlers/handlers_pre18.go b/vendor/github.com/gorilla/handlers/handlers_pre18.go deleted file mode 100644 index 197836ab..00000000 --- a/vendor/github.com/gorilla/handlers/handlers_pre18.go +++ /dev/null @@ -1,7 +0,0 @@ -// +build !go1.8 - -package handlers - -type loggingResponseWriter interface { - commonLoggingResponseWriter -} diff --git a/vendor/github.com/gorilla/handlers/handlers_test.go b/vendor/github.com/gorilla/handlers/handlers_test.go deleted file mode 100644 index 04ee2449..00000000 --- a/vendor/github.com/gorilla/handlers/handlers_test.go +++ /dev/null @@ -1,378 +0,0 @@ -// Copyright 2013 The Gorilla Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package handlers - -import ( - "bytes" - "net" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" - "time" -) - -const ( - ok = "ok\n" - notAllowed = "Method not allowed\n" -) - -var okHandler = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - w.Write([]byte(ok)) -}) - -func newRequest(method, url string) *http.Request { - req, err := http.NewRequest(method, url, nil) - if err != nil { - panic(err) - } - return req -} - -func TestMethodHandler(t *testing.T) { - tests := []struct { - req *http.Request - handler http.Handler - code int - allow string // Contents of the Allow header - body string - }{ - // No handlers - {newRequest("GET", "/foo"), MethodHandler{}, http.StatusMethodNotAllowed, "", notAllowed}, - {newRequest("OPTIONS", "/foo"), MethodHandler{}, http.StatusOK, "", ""}, - - // A single handler - {newRequest("GET", "/foo"), MethodHandler{"GET": okHandler}, http.StatusOK, "", ok}, - {newRequest("POST", "/foo"), MethodHandler{"GET": okHandler}, http.StatusMethodNotAllowed, "GET", notAllowed}, - - // Multiple handlers - {newRequest("GET", "/foo"), MethodHandler{"GET": okHandler, "POST": okHandler}, http.StatusOK, "", ok}, - {newRequest("POST", "/foo"), MethodHandler{"GET": okHandler, "POST": okHandler}, http.StatusOK, "", ok}, - {newRequest("DELETE", "/foo"), MethodHandler{"GET": okHandler, "POST": okHandler}, http.StatusMethodNotAllowed, "GET, POST", notAllowed}, - {newRequest("OPTIONS", "/foo"), MethodHandler{"GET": okHandler, "POST": okHandler}, http.StatusOK, "GET, POST", ""}, - - // Override OPTIONS - {newRequest("OPTIONS", "/foo"), MethodHandler{"OPTIONS": okHandler}, http.StatusOK, "", ok}, - } - - for i, test := range tests { - rec := httptest.NewRecorder() - test.handler.ServeHTTP(rec, test.req) - if rec.Code != test.code { - t.Fatalf("%d: wrong code, got %d want %d", i, rec.Code, test.code) - } - if allow := rec.HeaderMap.Get("Allow"); allow != test.allow { - t.Fatalf("%d: wrong Allow, got %s want %s", i, allow, test.allow) - } - if body := rec.Body.String(); body != test.body { - t.Fatalf("%d: wrong body, got %q want %q", i, body, test.body) - } - } -} - -func TestMakeLogger(t *testing.T) { - rec := httptest.NewRecorder() - logger := makeLogger(rec) - // initial status - if logger.Status() != http.StatusOK { - t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusOK) - } - // WriteHeader - logger.WriteHeader(http.StatusInternalServerError) - if logger.Status() != http.StatusInternalServerError { - t.Fatalf("wrong status, got %d want %d", logger.Status(), http.StatusInternalServerError) - } - // Write - logger.Write([]byte(ok)) - if logger.Size() != len(ok) { - t.Fatalf("wrong size, got %d want %d", logger.Size(), len(ok)) - } - // Header - logger.Header().Set("key", "value") - if val := logger.Header().Get("key"); val != "value" { - t.Fatalf("wrong header, got %s want %s", val, "value") - } -} - -func TestWriteLog(t *testing.T) { - loc, err := time.LoadLocation("Europe/Warsaw") - if err != nil { - panic(err) - } - ts := time.Date(1983, 05, 26, 3, 30, 45, 0, loc) - - // A typical request with an OK response - req := newRequest("GET", "http://example.com") - req.RemoteAddr = "192.168.100.5" - - buf := new(bytes.Buffer) - writeLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log := buf.String() - - expected := "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 200 100\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // CONNECT request over http/2.0 - req = &http.Request{ - Method: "CONNECT", - Proto: "HTTP/2.0", - ProtoMajor: 2, - ProtoMinor: 0, - URL: &url.URL{Host: "www.example.com:443"}, - Host: "www.example.com:443", - RemoteAddr: "192.168.100.5", - } - - buf = new(bytes.Buffer) - writeLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log = buf.String() - - expected = "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"CONNECT www.example.com:443 HTTP/2.0\" 200 100\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // Request with an unauthorized user - req = newRequest("GET", "http://example.com") - req.RemoteAddr = "192.168.100.5" - req.URL.User = url.User("kamil") - - buf.Reset() - writeLog(buf, req, *req.URL, ts, http.StatusUnauthorized, 500) - log = buf.String() - - expected = "192.168.100.5 - kamil [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 401 500\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // Request with url encoded parameters - req = newRequest("GET", "http://example.com/test?abc=hello%20world&a=b%3F") - req.RemoteAddr = "192.168.100.5" - - buf.Reset() - writeLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log = buf.String() - - expected = "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"GET /test?abc=hello%20world&a=b%3F HTTP/1.1\" 200 100\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } -} - -func TestWriteCombinedLog(t *testing.T) { - loc, err := time.LoadLocation("Europe/Warsaw") - if err != nil { - panic(err) - } - ts := time.Date(1983, 05, 26, 3, 30, 45, 0, loc) - - // A typical request with an OK response - req := newRequest("GET", "http://example.com") - req.RemoteAddr = "192.168.100.5" - req.Header.Set("Referer", "http://example.com") - req.Header.Set( - "User-Agent", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.33 "+ - "(KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33", - ) - - buf := new(bytes.Buffer) - writeCombinedLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log := buf.String() - - expected := "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 200 100 \"http://example.com\" " + - "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) " + - "AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33\"\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // CONNECT request over http/2.0 - req1 := &http.Request{ - Method: "CONNECT", - Host: "www.example.com:443", - Proto: "HTTP/2.0", - ProtoMajor: 2, - ProtoMinor: 0, - RemoteAddr: "192.168.100.5", - Header: http.Header{}, - URL: &url.URL{Host: "www.example.com:443"}, - } - req1.Header.Set("Referer", "http://example.com") - req1.Header.Set( - "User-Agent", - "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.33 "+ - "(KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33", - ) - - buf = new(bytes.Buffer) - writeCombinedLog(buf, req1, *req1.URL, ts, http.StatusOK, 100) - log = buf.String() - - expected = "192.168.100.5 - - [26/May/1983:03:30:45 +0200] \"CONNECT www.example.com:443 HTTP/2.0\" 200 100 \"http://example.com\" " + - "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) " + - "AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33\"\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // Request with an unauthorized user - req.URL.User = url.User("kamil") - - buf.Reset() - writeCombinedLog(buf, req, *req.URL, ts, http.StatusUnauthorized, 500) - log = buf.String() - - expected = "192.168.100.5 - kamil [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 401 500 \"http://example.com\" " + - "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) " + - "AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33\"\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // Test with remote ipv6 address - req.RemoteAddr = "::1" - - buf.Reset() - writeCombinedLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log = buf.String() - - expected = "::1 - kamil [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 200 100 \"http://example.com\" " + - "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) " + - "AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33\"\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } - - // Test remote ipv6 addr, with port - req.RemoteAddr = net.JoinHostPort("::1", "65000") - - buf.Reset() - writeCombinedLog(buf, req, *req.URL, ts, http.StatusOK, 100) - log = buf.String() - - expected = "::1 - kamil [26/May/1983:03:30:45 +0200] \"GET / HTTP/1.1\" 200 100 \"http://example.com\" " + - "\"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) " + - "AppleWebKit/537.33 (KHTML, like Gecko) Chrome/27.0.1430.0 Safari/537.33\"\n" - if log != expected { - t.Fatalf("wrong log, got %q want %q", log, expected) - } -} - -func TestLogPathRewrites(t *testing.T) { - var buf bytes.Buffer - - handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - req.URL.Path = "/" // simulate http.StripPrefix and friends - w.WriteHeader(200) - }) - logger := LoggingHandler(&buf, handler) - - logger.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) - - if !strings.Contains(buf.String(), "GET /subdir/asdf HTTP") { - t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "GET /subdir/asdf HTTP") - } -} - -func BenchmarkWriteLog(b *testing.B) { - loc, err := time.LoadLocation("Europe/Warsaw") - if err != nil { - b.Fatalf(err.Error()) - } - ts := time.Date(1983, 05, 26, 3, 30, 45, 0, loc) - - req := newRequest("GET", "http://example.com") - req.RemoteAddr = "192.168.100.5" - - b.ResetTimer() - - buf := &bytes.Buffer{} - for i := 0; i < b.N; i++ { - buf.Reset() - writeLog(buf, req, *req.URL, ts, http.StatusUnauthorized, 500) - } -} - -func TestContentTypeHandler(t *testing.T) { - tests := []struct { - Method string - AllowContentTypes []string - ContentType string - Code int - }{ - {"POST", []string{"application/json"}, "application/json", http.StatusOK}, - {"POST", []string{"application/json", "application/xml"}, "application/json", http.StatusOK}, - {"POST", []string{"application/json"}, "application/json; charset=utf-8", http.StatusOK}, - {"POST", []string{"application/json"}, "application/json+xxx", http.StatusUnsupportedMediaType}, - {"POST", []string{"application/json"}, "text/plain", http.StatusUnsupportedMediaType}, - {"GET", []string{"application/json"}, "", http.StatusOK}, - {"GET", []string{}, "", http.StatusOK}, - } - for _, test := range tests { - r, err := http.NewRequest(test.Method, "/", nil) - if err != nil { - t.Error(err) - continue - } - - h := ContentTypeHandler(okHandler, test.AllowContentTypes...) - r.Header.Set("Content-Type", test.ContentType) - w := httptest.NewRecorder() - h.ServeHTTP(w, r) - if w.Code != test.Code { - t.Errorf("expected %d, got %d", test.Code, w.Code) - } - } -} - -func TestHTTPMethodOverride(t *testing.T) { - var tests = []struct { - Method string - OverrideMethod string - ExpectedMethod string - }{ - {"POST", "PUT", "PUT"}, - {"POST", "PATCH", "PATCH"}, - {"POST", "DELETE", "DELETE"}, - {"PUT", "DELETE", "PUT"}, - {"GET", "GET", "GET"}, - {"HEAD", "HEAD", "HEAD"}, - {"GET", "PUT", "GET"}, - {"HEAD", "DELETE", "HEAD"}, - } - - for _, test := range tests { - h := HTTPMethodOverrideHandler(okHandler) - reqs := make([]*http.Request, 0, 2) - - rHeader, err := http.NewRequest(test.Method, "/", nil) - if err != nil { - t.Error(err) - } - rHeader.Header.Set(HTTPMethodOverrideHeader, test.OverrideMethod) - reqs = append(reqs, rHeader) - - f := url.Values{HTTPMethodOverrideFormKey: []string{test.OverrideMethod}} - rForm, err := http.NewRequest(test.Method, "/", strings.NewReader(f.Encode())) - if err != nil { - t.Error(err) - } - rForm.Header.Set("Content-Type", "application/x-www-form-urlencoded") - reqs = append(reqs, rForm) - - for _, r := range reqs { - w := httptest.NewRecorder() - h.ServeHTTP(w, r) - if r.Method != test.ExpectedMethod { - t.Errorf("Expected %s, got %s", test.ExpectedMethod, r.Method) - } - } - } -} diff --git a/vendor/github.com/gorilla/handlers/proxy_headers.go b/vendor/github.com/gorilla/handlers/proxy_headers.go deleted file mode 100644 index 0be750fd..00000000 --- a/vendor/github.com/gorilla/handlers/proxy_headers.go +++ /dev/null @@ -1,120 +0,0 @@ -package handlers - -import ( - "net/http" - "regexp" - "strings" -) - -var ( - // De-facto standard header keys. - xForwardedFor = http.CanonicalHeaderKey("X-Forwarded-For") - xForwardedHost = http.CanonicalHeaderKey("X-Forwarded-Host") - xForwardedProto = http.CanonicalHeaderKey("X-Forwarded-Proto") - xForwardedScheme = http.CanonicalHeaderKey("X-Forwarded-Scheme") - xRealIP = http.CanonicalHeaderKey("X-Real-IP") -) - -var ( - // RFC7239 defines a new "Forwarded: " header designed to replace the - // existing use of X-Forwarded-* headers. - // e.g. Forwarded: for=192.0.2.60;proto=https;by=203.0.113.43 - forwarded = http.CanonicalHeaderKey("Forwarded") - // Allows for a sub-match of the first value after 'for=' to the next - // comma, semi-colon or space. The match is case-insensitive. - forRegex = regexp.MustCompile(`(?i)(?:for=)([^(;|,| )]+)`) - // Allows for a sub-match for the first instance of scheme (http|https) - // prefixed by 'proto='. The match is case-insensitive. - protoRegex = regexp.MustCompile(`(?i)(?:proto=)(https|http)`) -) - -// ProxyHeaders inspects common reverse proxy headers and sets the corresponding -// fields in the HTTP request struct. These are X-Forwarded-For and X-Real-IP -// for the remote (client) IP address, X-Forwarded-Proto or X-Forwarded-Scheme -// for the scheme (http|https) and the RFC7239 Forwarded header, which may -// include both client IPs and schemes. -// -// NOTE: This middleware should only be used when behind a reverse -// proxy like nginx, HAProxy or Apache. Reverse proxies that don't (or are -// configured not to) strip these headers from client requests, or where these -// headers are accepted "as is" from a remote client (e.g. when Go is not behind -// a proxy), can manifest as a vulnerability if your application uses these -// headers for validating the 'trustworthiness' of a request. -func ProxyHeaders(h http.Handler) http.Handler { - fn := func(w http.ResponseWriter, r *http.Request) { - // Set the remote IP with the value passed from the proxy. - if fwd := getIP(r); fwd != "" { - r.RemoteAddr = fwd - } - - // Set the scheme (proto) with the value passed from the proxy. - if scheme := getScheme(r); scheme != "" { - r.URL.Scheme = scheme - } - // Set the host with the value passed by the proxy - if r.Header.Get(xForwardedHost) != "" { - r.Host = r.Header.Get(xForwardedHost) - } - // Call the next handler in the chain. - h.ServeHTTP(w, r) - } - - return http.HandlerFunc(fn) -} - -// getIP retrieves the IP from the X-Forwarded-For, X-Real-IP and RFC7239 -// Forwarded headers (in that order). -func getIP(r *http.Request) string { - var addr string - - if fwd := r.Header.Get(xForwardedFor); fwd != "" { - // Only grab the first (client) address. Note that '192.168.0.1, - // 10.1.1.1' is a valid key for X-Forwarded-For where addresses after - // the first may represent forwarding proxies earlier in the chain. - s := strings.Index(fwd, ", ") - if s == -1 { - s = len(fwd) - } - addr = fwd[:s] - } else if fwd := r.Header.Get(xRealIP); fwd != "" { - // X-Real-IP should only contain one IP address (the client making the - // request). - addr = fwd - } else if fwd := r.Header.Get(forwarded); fwd != "" { - // match should contain at least two elements if the protocol was - // specified in the Forwarded header. The first element will always be - // the 'for=' capture, which we ignore. In the case of multiple IP - // addresses (for=8.8.8.8, 8.8.4.4,172.16.1.20 is valid) we only - // extract the first, which should be the client IP. - if match := forRegex.FindStringSubmatch(fwd); len(match) > 1 { - // IPv6 addresses in Forwarded headers are quoted-strings. We strip - // these quotes. - addr = strings.Trim(match[1], `"`) - } - } - - return addr -} - -// getScheme retrieves the scheme from the X-Forwarded-Proto and RFC7239 -// Forwarded headers (in that order). -func getScheme(r *http.Request) string { - var scheme string - - // Retrieve the scheme from X-Forwarded-Proto. - if proto := r.Header.Get(xForwardedProto); proto != "" { - scheme = strings.ToLower(proto) - } else if proto = r.Header.Get(xForwardedScheme); proto != "" { - scheme = strings.ToLower(proto) - } else if proto = r.Header.Get(forwarded); proto != "" { - // match should contain at least two elements if the protocol was - // specified in the Forwarded header. The first element will always be - // the 'proto=' capture, which we ignore. In the case of multiple proto - // parameters (invalid) we only extract the first. - if match := protoRegex.FindStringSubmatch(proto); len(match) > 1 { - scheme = strings.ToLower(match[1]) - } - } - - return scheme -} diff --git a/vendor/github.com/gorilla/handlers/proxy_headers_test.go b/vendor/github.com/gorilla/handlers/proxy_headers_test.go deleted file mode 100644 index 1bd78052..00000000 --- a/vendor/github.com/gorilla/handlers/proxy_headers_test.go +++ /dev/null @@ -1,111 +0,0 @@ -package handlers - -import ( - "net/http" - "net/http/httptest" - "testing" -) - -type headerTable struct { - key string // header key - val string // header val - expected string // expected result -} - -func TestGetIP(t *testing.T) { - headers := []headerTable{ - {xForwardedFor, "8.8.8.8", "8.8.8.8"}, // Single address - {xForwardedFor, "8.8.8.8, 8.8.4.4", "8.8.8.8"}, // Multiple - {xForwardedFor, "[2001:db8:cafe::17]:4711", "[2001:db8:cafe::17]:4711"}, // IPv6 address - {xForwardedFor, "", ""}, // None - {xRealIP, "8.8.8.8", "8.8.8.8"}, // Single address - {xRealIP, "8.8.8.8, 8.8.4.4", "8.8.8.8, 8.8.4.4"}, // Multiple - {xRealIP, "[2001:db8:cafe::17]:4711", "[2001:db8:cafe::17]:4711"}, // IPv6 address - {xRealIP, "", ""}, // None - {forwarded, `for="_gazonk"`, "_gazonk"}, // Hostname - {forwarded, `For="[2001:db8:cafe::17]:4711`, `[2001:db8:cafe::17]:4711`}, // IPv6 address - {forwarded, `for=192.0.2.60;proto=http;by=203.0.113.43`, `192.0.2.60`}, // Multiple params - {forwarded, `for=192.0.2.43, for=198.51.100.17`, "192.0.2.43"}, // Multiple params - {forwarded, `for="workstation.local",for=198.51.100.17`, "workstation.local"}, // Hostname - } - - for _, v := range headers { - req := &http.Request{ - Header: http.Header{ - v.key: []string{v.val}, - }} - res := getIP(req) - if res != v.expected { - t.Fatalf("wrong header for %s: got %s want %s", v.key, res, - v.expected) - } - } -} - -func TestGetScheme(t *testing.T) { - headers := []headerTable{ - {xForwardedProto, "https", "https"}, - {xForwardedProto, "http", "http"}, - {xForwardedProto, "HTTP", "http"}, - {xForwardedScheme, "https", "https"}, - {xForwardedScheme, "http", "http"}, - {xForwardedScheme, "HTTP", "http"}, - {forwarded, `For="[2001:db8:cafe::17]:4711`, ""}, // No proto - {forwarded, `for=192.0.2.43, for=198.51.100.17;proto=https`, "https"}, // Multiple params before proto - {forwarded, `for=172.32.10.15; proto=https;by=127.0.0.1`, "https"}, // Space before proto - {forwarded, `for=192.0.2.60;proto=http;by=203.0.113.43`, "http"}, // Multiple params - } - - for _, v := range headers { - req := &http.Request{ - Header: http.Header{ - v.key: []string{v.val}, - }, - } - res := getScheme(req) - if res != v.expected { - t.Fatalf("wrong header for %s: got %s want %s", v.key, res, - v.expected) - } - } -} - -// Test the middleware end-to-end -func TestProxyHeaders(t *testing.T) { - rr := httptest.NewRecorder() - r := newRequest("GET", "/") - - r.Header.Set(xForwardedFor, "8.8.8.8") - r.Header.Set(xForwardedProto, "https") - r.Header.Set(xForwardedHost, "google.com") - var ( - addr string - proto string - host string - ) - ProxyHeaders(http.HandlerFunc( - func(w http.ResponseWriter, r *http.Request) { - addr = r.RemoteAddr - proto = r.URL.Scheme - host = r.Host - })).ServeHTTP(rr, r) - - if rr.Code != http.StatusOK { - t.Fatalf("bad status: got %d want %d", rr.Code, http.StatusOK) - } - - if addr != r.Header.Get(xForwardedFor) { - t.Fatalf("wrong address: got %s want %s", addr, - r.Header.Get(xForwardedFor)) - } - - if proto != r.Header.Get(xForwardedProto) { - t.Fatalf("wrong address: got %s want %s", proto, - r.Header.Get(xForwardedProto)) - } - if host != r.Header.Get(xForwardedHost) { - t.Fatalf("wrong address: got %s want %s", host, - r.Header.Get(xForwardedHost)) - } - -} diff --git a/vendor/github.com/gorilla/handlers/recovery.go b/vendor/github.com/gorilla/handlers/recovery.go deleted file mode 100644 index b1be9dc8..00000000 --- a/vendor/github.com/gorilla/handlers/recovery.go +++ /dev/null @@ -1,91 +0,0 @@ -package handlers - -import ( - "log" - "net/http" - "runtime/debug" -) - -// RecoveryHandlerLogger is an interface used by the recovering handler to print logs. -type RecoveryHandlerLogger interface { - Println(...interface{}) -} - -type recoveryHandler struct { - handler http.Handler - logger RecoveryHandlerLogger - printStack bool -} - -// RecoveryOption provides a functional approach to define -// configuration for a handler; such as setting the logging -// whether or not to print strack traces on panic. -type RecoveryOption func(http.Handler) - -func parseRecoveryOptions(h http.Handler, opts ...RecoveryOption) http.Handler { - for _, option := range opts { - option(h) - } - - return h -} - -// RecoveryHandler is HTTP middleware that recovers from a panic, -// logs the panic, writes http.StatusInternalServerError, and -// continues to the next handler. -// -// Example: -// -// r := mux.NewRouter() -// r.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { -// panic("Unexpected error!") -// }) -// -// http.ListenAndServe(":1123", handlers.RecoveryHandler()(r)) -func RecoveryHandler(opts ...RecoveryOption) func(h http.Handler) http.Handler { - return func(h http.Handler) http.Handler { - r := &recoveryHandler{handler: h} - return parseRecoveryOptions(r, opts...) - } -} - -// RecoveryLogger is a functional option to override -// the default logger -func RecoveryLogger(logger RecoveryHandlerLogger) RecoveryOption { - return func(h http.Handler) { - r := h.(*recoveryHandler) - r.logger = logger - } -} - -// PrintRecoveryStack is a functional option to enable -// or disable printing stack traces on panic. -func PrintRecoveryStack(print bool) RecoveryOption { - return func(h http.Handler) { - r := h.(*recoveryHandler) - r.printStack = print - } -} - -func (h recoveryHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { - defer func() { - if err := recover(); err != nil { - w.WriteHeader(http.StatusInternalServerError) - h.log(err) - } - }() - - h.handler.ServeHTTP(w, req) -} - -func (h recoveryHandler) log(v ...interface{}) { - if h.logger != nil { - h.logger.Println(v...) - } else { - log.Println(v...) - } - - if h.printStack { - debug.PrintStack() - } -} diff --git a/vendor/github.com/gorilla/handlers/recovery_test.go b/vendor/github.com/gorilla/handlers/recovery_test.go deleted file mode 100644 index 1ae0e580..00000000 --- a/vendor/github.com/gorilla/handlers/recovery_test.go +++ /dev/null @@ -1,44 +0,0 @@ -package handlers - -import ( - "bytes" - "log" - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestRecoveryLoggerWithDefaultOptions(t *testing.T) { - var buf bytes.Buffer - log.SetOutput(&buf) - - handler := RecoveryHandler() - handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - panic("Unexpected error!") - }) - - recovery := handler(handlerFunc) - recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) - - if !strings.Contains(buf.String(), "Unexpected error!") { - t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!") - } -} - -func TestRecoveryLoggerWithCustomLogger(t *testing.T) { - var buf bytes.Buffer - var logger = log.New(&buf, "", log.LstdFlags) - - handler := RecoveryHandler(RecoveryLogger(logger), PrintRecoveryStack(false)) - handlerFunc := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { - panic("Unexpected error!") - }) - - recovery := handler(handlerFunc) - recovery.ServeHTTP(httptest.NewRecorder(), newRequest("GET", "/subdir/asdf")) - - if !strings.Contains(buf.String(), "Unexpected error!") { - t.Fatalf("Got log %#v, wanted substring %#v", buf.String(), "Unexpected error!") - } -} diff --git a/vendor/github.com/hashicorp/errwrap/go.mod b/vendor/github.com/hashicorp/errwrap/go.mod new file mode 100644 index 00000000..c9b84022 --- /dev/null +++ b/vendor/github.com/hashicorp/errwrap/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/errwrap diff --git a/vendor/github.com/hashicorp/go-multierror/go.mod b/vendor/github.com/hashicorp/go-multierror/go.mod new file mode 100644 index 00000000..2534331d --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/go.mod @@ -0,0 +1,3 @@ +module github.com/hashicorp/go-multierror + +require github.com/hashicorp/errwrap v1.0.0 diff --git a/vendor/github.com/hashicorp/go-multierror/go.sum b/vendor/github.com/hashicorp/go-multierror/go.sum new file mode 100644 index 00000000..85b1f8ff --- /dev/null +++ b/vendor/github.com/hashicorp/go-multierror/go.sum @@ -0,0 +1,4 @@ +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce h1:prjrVgOk2Yg6w+PflHoszQNLTUh4kaByUcEWM/9uin4= +github.com/hashicorp/errwrap v0.0.0-20141028054710-7554cd9344ce/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= diff --git a/vendor/github.com/hashicorp/go-multierror/scripts/deps.sh b/vendor/github.com/hashicorp/go-multierror/scripts/deps.sh deleted file mode 100755 index 1d2fcf98..00000000 --- a/vendor/github.com/hashicorp/go-multierror/scripts/deps.sh +++ /dev/null @@ -1,54 +0,0 @@ -#!/usr/bin/env bash -# -# This script updates dependencies using a temporary directory. This is required -# to avoid any auxillary dependencies that sneak into GOPATH. -set -e - -# Get the parent directory of where this script is. -SOURCE="${BASH_SOURCE[0]}" -while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done -DIR="$(cd -P "$(dirname "$SOURCE")/.." && pwd)" - -# Change into that directory -cd "$DIR" - -# Get the name from the directory -NAME=${NAME:-"$(basename $(pwd))"} - -# Announce -echo "==> Updating dependencies..." - -echo "--> Making tmpdir..." -tmpdir=$(mktemp -d) -function cleanup { - rm -rf "${tmpdir}" -} -trap cleanup EXIT - -export GOPATH="${tmpdir}" -export PATH="${tmpdir}/bin:$PATH" - -mkdir -p "${tmpdir}/src/github.com/hashicorp" -pushd "${tmpdir}/src/github.com/hashicorp" &>/dev/null - -echo "--> Copying ${NAME}..." -cp -R "$DIR" "${tmpdir}/src/github.com/hashicorp/${NAME}" -pushd "${tmpdir}/src/github.com/hashicorp/${NAME}" &>/dev/null -rm -rf vendor/ - -echo "--> Installing dependency manager..." -go get -u github.com/kardianos/govendor -govendor init - -echo "--> Installing all dependencies (may take some time)..." -govendor fetch -v +outside - -echo "--> Vendoring..." -govendor add +external - -echo "--> Moving into place..." -vpath="${tmpdir}/src/github.com/hashicorp/${NAME}/vendor" -popd &>/dev/null -popd &>/dev/null -rm -rf vendor/ -cp -R "${vpath}" . diff --git a/vendor/github.com/hashicorp/hcl/go.mod b/vendor/github.com/hashicorp/hcl/go.mod new file mode 100644 index 00000000..4debbbe3 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/go.mod @@ -0,0 +1,3 @@ +module github.com/hashicorp/hcl + +require github.com/davecgh/go-spew v1.1.1 diff --git a/vendor/github.com/hashicorp/hcl/go.sum b/vendor/github.com/hashicorp/hcl/go.sum new file mode 100644 index 00000000..b5e2922e --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/go.sum @@ -0,0 +1,2 @@ +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= diff --git a/vendor/github.com/mitchellh/mapstructure/go.mod b/vendor/github.com/mitchellh/mapstructure/go.mod new file mode 100644 index 00000000..d2a71256 --- /dev/null +++ b/vendor/github.com/mitchellh/mapstructure/go.mod @@ -0,0 +1 @@ +module github.com/mitchellh/mapstructure diff --git a/vendor/github.com/onsi/gomega/.travis.yml b/vendor/github.com/onsi/gomega/.travis.yml index 8b982a9a..783fb3b4 100644 --- a/vendor/github.com/onsi/gomega/.travis.yml +++ b/vendor/github.com/onsi/gomega/.travis.yml @@ -5,10 +5,12 @@ go: - 1.8.x - 1.9.x - 1.10.x + - 1.11.x install: - - go get -v ./... + - env GO111MODULE=on go get -v ./... + - env GO111MODULE=on go build ./... - go get github.com/onsi/ginkgo - go install github.com/onsi/ginkgo/ginkgo -script: $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && go vet +script: env GO111MODULE=on $HOME/gopath/bin/ginkgo -p -r --randomizeAllSpecs --failOnPending --randomizeSuites --race && env GO111MODULE=on go vet diff --git a/vendor/github.com/onsi/gomega/CHANGELOG.md b/vendor/github.com/onsi/gomega/CHANGELOG.md index a629b2e5..f2aaea4e 100644 --- a/vendor/github.com/onsi/gomega/CHANGELOG.md +++ b/vendor/github.com/onsi/gomega/CHANGELOG.md @@ -1,3 +1,13 @@ +## 1.4.2 + +### Fixes: + +- Add go.mod and go.sum files to define the gomega go module [f3de367, a085d30] +- Work around go vet issue with Go v1.11 (#300) [40dd6ad] +- Better output when using with go XUnit-style tests, fixes #255 (#297) [29a4b97] +- Fix MatchJSON fail to parse json.RawMessage (#298) [ae19f1b] +- show threshold in failure message of BeNumericallyMatcher (#293) [4bbecc8] + ## 1.4.1 ### Fixes: diff --git a/vendor/github.com/onsi/gomega/gbytes/say_matcher.go b/vendor/github.com/onsi/gomega/gbytes/say_matcher.go index 77214204..14317182 100644 --- a/vendor/github.com/onsi/gomega/gbytes/say_matcher.go +++ b/vendor/github.com/onsi/gomega/gbytes/say_matcher.go @@ -36,12 +36,11 @@ In such cases, Say simply operates on the *gbytes.Buffer returned by Buffer() If the buffer is closed, the Say matcher will tell Eventually to abort. */ func Say(expected string, args ...interface{}) *sayMatcher { - formattedRegexp := expected if len(args) > 0 { - formattedRegexp = fmt.Sprintf(expected, args...) + expected = fmt.Sprintf(expected, args...) } return &sayMatcher{ - re: regexp.MustCompile(formattedRegexp), + re: regexp.MustCompile(expected), } } diff --git a/vendor/github.com/onsi/gomega/gbytes/say_matcher_test.go b/vendor/github.com/onsi/gomega/gbytes/say_matcher_test.go index ef8f784f..0055d4a1 100644 --- a/vendor/github.com/onsi/gomega/gbytes/say_matcher_test.go +++ b/vendor/github.com/onsi/gomega/gbytes/say_matcher_test.go @@ -43,6 +43,11 @@ var _ = Describe("SayMatcher", func() { Expect(buffer).Should(Say("a%sc", "b")) }) + It("should match literal %", func() { + buffer.Write([]byte("%")) + Expect(buffer).Should(Say("abc%")) + }) + It("should use a regular expression", func() { Expect(buffer).Should(Say("a.c")) }) diff --git a/vendor/github.com/onsi/gomega/gexec/build_test.go b/vendor/github.com/onsi/gomega/gexec/build_test.go index 87c623cb..295dac8b 100644 --- a/vendor/github.com/onsi/gomega/gexec/build_test.go +++ b/vendor/github.com/onsi/gomega/gexec/build_test.go @@ -1,7 +1,10 @@ package gexec_test import ( + "fmt" + "io/ioutil" "os" + "path/filepath" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" @@ -59,29 +62,51 @@ var _ = Describe(".BuildWithEnvironment", func() { }) var _ = Describe(".BuildIn", func() { + const ( + target = "github.com/onsi/gomega/gexec/_fixture/firefly/" + ) + var ( - gopath string + original string + gopath string ) BeforeEach(func() { - gopath = os.Getenv("GOPATH") - Expect(gopath).NotTo(BeEmpty()) - Expect(os.Setenv("GOPATH", "/tmp")).To(Succeed()) - Expect(os.Environ()).To(ContainElement("GOPATH=/tmp")) + var err error + original = os.Getenv("GOPATH") + gopath, err = ioutil.TempDir("", "") + Expect(err).NotTo(HaveOccurred()) + copyFile(filepath.Join("_fixture", "firefly", "main.go"), filepath.Join(gopath, "src", target), "main.go") + Expect(os.Setenv("GOPATH", filepath.Join(os.TempDir(), "emptyFakeGopath"))).To(Succeed()) + Expect(os.Environ()).To(ContainElement(fmt.Sprintf("GOPATH=%s", filepath.Join(os.TempDir(), "emptyFakeGopath")))) }) AfterEach(func() { - Expect(os.Setenv("GOPATH", gopath)).To(Succeed()) + if original == "" { + Expect(os.Unsetenv("GOPATH")).To(Succeed()) + } else { + Expect(os.Setenv("GOPATH", original)).To(Succeed()) + } + if gopath != "" { + os.RemoveAll(gopath) + } }) It("appends the gopath env var", func() { - _, err := gexec.BuildIn(gopath, "github.com/onsi/gomega/gexec/_fixture/firefly/") + _, err := gexec.BuildIn(gopath, target) Expect(err).NotTo(HaveOccurred()) }) It("resets GOPATH to its original value", func() { - _, err := gexec.BuildIn(gopath, "github.com/onsi/gomega/gexec/_fixture/firefly/") + _, err := gexec.BuildIn(gopath, target) Expect(err).NotTo(HaveOccurred()) - Expect(os.Getenv("GOPATH")).To(Equal("/tmp")) + Expect(os.Getenv("GOPATH")).To(Equal(filepath.Join(os.TempDir(), "emptyFakeGopath"))) }) }) + +func copyFile(source, directory, basename string) { + Expect(os.MkdirAll(directory, 0755)).To(Succeed()) + content, err := ioutil.ReadFile(source) + Expect(err).NotTo(HaveOccurred()) + Expect(ioutil.WriteFile(filepath.Join(directory, basename), content, 0644)).To(Succeed()) +} diff --git a/vendor/github.com/onsi/gomega/go.mod b/vendor/github.com/onsi/gomega/go.mod new file mode 100644 index 00000000..65eedf69 --- /dev/null +++ b/vendor/github.com/onsi/gomega/go.mod @@ -0,0 +1,15 @@ +module github.com/onsi/gomega + +require ( + github.com/fsnotify/fsnotify v1.4.7 // indirect + github.com/golang/protobuf v1.2.0 + github.com/hpcloud/tail v1.0.0 // indirect + github.com/onsi/ginkgo v1.6.0 + golang.org/x/net v0.0.0-20180906233101-161cd47e91fd + golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f // indirect + golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e // indirect + golang.org/x/text v0.3.0 // indirect + gopkg.in/fsnotify.v1 v1.4.7 // indirect + gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 // indirect + gopkg.in/yaml.v2 v2.2.1 +) diff --git a/vendor/github.com/onsi/gomega/go.sum b/vendor/github.com/onsi/gomega/go.sum new file mode 100644 index 00000000..b23f6ef0 --- /dev/null +++ b/vendor/github.com/onsi/gomega/go.sum @@ -0,0 +1,24 @@ +github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= +github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= +github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= +github.com/onsi/ginkgo v1.6.0 h1:Ix8l273rp3QzYgXSR+c8d1fTG7UPgYkOSELPhiY/YGw= +github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA= +golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= +golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= +gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= +gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= +gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= diff --git a/vendor/github.com/onsi/gomega/gomega_dsl.go b/vendor/github.com/onsi/gomega/gomega_dsl.go index 6d96c43a..51d7872f 100644 --- a/vendor/github.com/onsi/gomega/gomega_dsl.go +++ b/vendor/github.com/onsi/gomega/gomega_dsl.go @@ -24,7 +24,7 @@ import ( "github.com/onsi/gomega/types" ) -const GOMEGA_VERSION = "1.4.1" +const GOMEGA_VERSION = "1.4.2" const nilFailHandlerPanic = `You are trying to make an assertion, but Gomega's fail handler is nil. If you're using Ginkgo then you probably forgot to put your assertion in an It(). @@ -32,7 +32,7 @@ Alternatively, you may have forgotten to register a fail handler with RegisterFa Depending on your vendoring solution you may be inadvertently importing gomega and subpackages (e.g. ghhtp, gexec,...) from different locations. ` -var globalFailHandler types.GomegaFailHandler +var globalFailWrapper *types.GomegaFailWrapper var defaultEventuallyTimeout = time.Second var defaultEventuallyPollingInterval = 10 * time.Millisecond @@ -42,7 +42,14 @@ var defaultConsistentlyPollingInterval = 10 * time.Millisecond //RegisterFailHandler connects Ginkgo to Gomega. When a matcher fails //the fail handler passed into RegisterFailHandler is called. func RegisterFailHandler(handler types.GomegaFailHandler) { - globalFailHandler = handler + if handler == nil { + globalFailWrapper = nil + return + } + globalFailWrapper = &types.GomegaFailWrapper{ + Fail: handler, + TWithHelper: testingtsupport.EmptyTWithHelper{}, + } } //RegisterTestingT connects Gomega to Golang's XUnit style @@ -67,7 +74,7 @@ func RegisterFailHandler(handler types.GomegaFailHandler) { // // (As an aside: Ginkgo gets around this limitation by running parallel tests in different *processes*). func RegisterTestingT(t types.GomegaTestingT) { - RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailHandler(t)) + RegisterFailHandler(testingtsupport.BuildTestingTGomegaFailWrapper(t).Fail) } //InterceptGomegaHandlers runs a given callback and returns an array of @@ -80,7 +87,7 @@ func RegisterTestingT(t types.GomegaTestingT) { //This is most useful when testing custom matchers, but can also be used to check //on a value using a Gomega assertion without causing a test failure. func InterceptGomegaFailures(f func()) []string { - originalHandler := globalFailHandler + originalHandler := globalFailWrapper.Fail failures := []string{} RegisterFailHandler(func(message string, callerSkip ...int) { failures = append(failures, message) @@ -142,10 +149,10 @@ func Expect(actual interface{}, extra ...interface{}) GomegaAssertion { //error message to refer to the calling line in the test (as opposed to the line in the helper function) //set the first argument of `ExpectWithOffset` appropriately. func ExpectWithOffset(offset int, actual interface{}, extra ...interface{}) GomegaAssertion { - if globalFailHandler == nil { + if globalFailWrapper == nil { panic(nilFailHandlerPanic) } - return assertion.New(actual, globalFailHandler, offset, extra...) + return assertion.New(actual, globalFailWrapper, offset, extra...) } //Eventually wraps an actual value allowing assertions to be made on it. @@ -192,7 +199,7 @@ func Eventually(actual interface{}, intervals ...interface{}) GomegaAsyncAsserti //initial argument to indicate an offset in the call stack. This is useful when building helper //functions that contain matchers. To learn more, read about `ExpectWithOffset`. func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailHandler == nil { + if globalFailWrapper == nil { panic(nilFailHandlerPanic) } timeoutInterval := defaultEventuallyTimeout @@ -203,7 +210,7 @@ func EventuallyWithOffset(offset int, actual interface{}, intervals ...interface if len(intervals) > 1 { pollingInterval = toDuration(intervals[1]) } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailHandler, timeoutInterval, pollingInterval, offset) + return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset) } //Consistently wraps an actual value allowing assertions to be made on it. @@ -237,7 +244,7 @@ func Consistently(actual interface{}, intervals ...interface{}) GomegaAsyncAsser //initial argument to indicate an offset in the call stack. This is useful when building helper //functions that contain matchers. To learn more, read about `ExpectWithOffset`. func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interface{}) GomegaAsyncAssertion { - if globalFailHandler == nil { + if globalFailWrapper == nil { panic(nilFailHandlerPanic) } timeoutInterval := defaultConsistentlyDuration @@ -248,7 +255,7 @@ func ConsistentlyWithOffset(offset int, actual interface{}, intervals ...interfa if len(intervals) > 1 { pollingInterval = toDuration(intervals[1]) } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailHandler, timeoutInterval, pollingInterval, offset) + return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, globalFailWrapper, timeoutInterval, pollingInterval, offset) } //Set the default timeout duration for Eventually. Eventually will repeatedly poll your condition until it succeeds, or until this timeout elapses. @@ -340,7 +347,7 @@ func NewGomegaWithT(t types.GomegaTestingT) *GomegaWithT { //See documentation for Expect func (g *GomegaWithT) Expect(actual interface{}, extra ...interface{}) GomegaAssertion { - return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), 0, extra...) + return assertion.New(actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), 0, extra...) } //See documentation for Eventually @@ -353,7 +360,7 @@ func (g *GomegaWithT) Eventually(actual interface{}, intervals ...interface{}) G if len(intervals) > 1 { pollingInterval = toDuration(intervals[1]) } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0) + return asyncassertion.New(asyncassertion.AsyncAssertionTypeEventually, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0) } //See documentation for Consistently @@ -366,7 +373,7 @@ func (g *GomegaWithT) Consistently(actual interface{}, intervals ...interface{}) if len(intervals) > 1 { pollingInterval = toDuration(intervals[1]) } - return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailHandler(g.t), timeoutInterval, pollingInterval, 0) + return asyncassertion.New(asyncassertion.AsyncAssertionTypeConsistently, actual, testingtsupport.BuildTestingTGomegaFailWrapper(g.t), timeoutInterval, pollingInterval, 0) } func toDuration(input interface{}) time.Duration { diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion.go index b73673f2..00197b67 100644 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion.go +++ b/vendor/github.com/onsi/gomega/internal/assertion/assertion.go @@ -9,37 +9,42 @@ import ( type Assertion struct { actualInput interface{} - fail types.GomegaFailHandler + failWrapper *types.GomegaFailWrapper offset int extra []interface{} } -func New(actualInput interface{}, fail types.GomegaFailHandler, offset int, extra ...interface{}) *Assertion { +func New(actualInput interface{}, failWrapper *types.GomegaFailWrapper, offset int, extra ...interface{}) *Assertion { return &Assertion{ actualInput: actualInput, - fail: fail, + failWrapper: failWrapper, offset: offset, extra: extra, } } func (assertion *Assertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } func (assertion *Assertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } func (assertion *Assertion) To(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, true, optionalDescription...) } func (assertion *Assertion) ToNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } func (assertion *Assertion) NotTo(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.vetExtras(optionalDescription...) && assertion.match(matcher, false, optionalDescription...) } @@ -55,8 +60,9 @@ func (assertion *Assertion) buildDescription(optionalDescription ...interface{}) func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool, optionalDescription ...interface{}) bool { matches, err := matcher.Match(assertion.actualInput) description := assertion.buildDescription(optionalDescription...) + assertion.failWrapper.TWithHelper.Helper() if err != nil { - assertion.fail(description+err.Error(), 2+assertion.offset) + assertion.failWrapper.Fail(description+err.Error(), 2+assertion.offset) return false } if matches != desiredMatch { @@ -66,7 +72,7 @@ func (assertion *Assertion) match(matcher types.GomegaMatcher, desiredMatch bool } else { message = matcher.NegatedFailureMessage(assertion.actualInput) } - assertion.fail(description+message, 2+assertion.offset) + assertion.failWrapper.Fail(description+message, 2+assertion.offset) return false } @@ -80,7 +86,8 @@ func (assertion *Assertion) vetExtras(optionalDescription ...interface{}) bool { } description := assertion.buildDescription(optionalDescription...) - assertion.fail(description+message, 2+assertion.offset) + assertion.failWrapper.TWithHelper.Helper() + assertion.failWrapper.Fail(description+message, 2+assertion.offset) return false } diff --git a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go b/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go index 1334777b..cac0d24c 100644 --- a/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go +++ b/vendor/github.com/onsi/gomega/internal/assertion/assertion_test.go @@ -3,10 +3,13 @@ package assertion_test import ( "errors" + "github.com/onsi/gomega/internal/testingtsupport" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/internal/assertion" "github.com/onsi/gomega/internal/fakematcher" + "github.com/onsi/gomega/types" ) var _ = Describe("Assertion", func() { @@ -19,18 +22,21 @@ var _ = Describe("Assertion", func() { input := "The thing I'm testing" - var fakeFailHandler = func(message string, callerSkip ...int) { - failureMessage = message - if len(callerSkip) == 1 { - failureCallerSkip = callerSkip[0] - } + var fakeFailWrapper = &types.GomegaFailWrapper{ + Fail: func(message string, callerSkip ...int) { + failureMessage = message + if len(callerSkip) == 1 { + failureCallerSkip = callerSkip[0] + } + }, + TWithHelper: testingtsupport.EmptyTWithHelper{}, } BeforeEach(func() { matcher = &fakematcher.FakeMatcher{} failureMessage = "" failureCallerSkip = 0 - a = New(input, fakeFailHandler, 1) + a = New(input, fakeFailWrapper, 1) }) Context("when called", func() { @@ -186,7 +192,7 @@ var _ = Describe("Assertion", func() { matcher.ErrToReturn = nil var typedNil []string - a = New(input, fakeFailHandler, 1, 0, nil, typedNil) + a = New(input, fakeFailWrapper, 1, 0, nil, typedNil) result := a.Should(matcher) Expect(result).Should(BeTrue()) @@ -201,32 +207,32 @@ var _ = Describe("Assertion", func() { matcher.MatchesToReturn = false matcher.ErrToReturn = nil - a = New(input, fakeFailHandler, 1, errors.New("foo")) + a = New(input, fakeFailWrapper, 1, errors.New("foo")) result := a.Should(matcher) Expect(result).Should(BeFalse()) Expect(matcher.ReceivedActual).Should(BeZero(), "The matcher doesn't even get called") Expect(failureMessage).Should(ContainSubstring("foo")) failureMessage = "" - a = New(input, fakeFailHandler, 1, nil, 1) + a = New(input, fakeFailWrapper, 1, nil, 1) result = a.ShouldNot(matcher) Expect(result).Should(BeFalse()) Expect(failureMessage).Should(ContainSubstring("1")) failureMessage = "" - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) + a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"}) result = a.To(matcher) Expect(result).Should(BeFalse()) Expect(failureMessage).Should(ContainSubstring("foo")) failureMessage = "" - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) + a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"}) result = a.ToNot(matcher) Expect(result).Should(BeFalse()) Expect(failureMessage).Should(ContainSubstring("foo")) failureMessage = "" - a = New(input, fakeFailHandler, 1, nil, 0, []string{"foo"}) + a = New(input, fakeFailWrapper, 1, nil, 0, []string{"foo"}) result = a.NotTo(matcher) Expect(result).Should(BeFalse()) Expect(failureMessage).Should(ContainSubstring("foo")) diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go index bce08530..cdab233e 100644 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go +++ b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion.go @@ -22,11 +22,11 @@ type AsyncAssertion struct { actualInput interface{} timeoutInterval time.Duration pollingInterval time.Duration - fail types.GomegaFailHandler + failWrapper *types.GomegaFailWrapper offset int } -func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.GomegaFailHandler, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion { +func New(asyncType AsyncAssertionType, actualInput interface{}, failWrapper *types.GomegaFailWrapper, timeoutInterval time.Duration, pollingInterval time.Duration, offset int) *AsyncAssertion { actualType := reflect.TypeOf(actualInput) if actualType.Kind() == reflect.Func { if actualType.NumIn() != 0 || actualType.NumOut() == 0 { @@ -37,7 +37,7 @@ func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.Gomeg return &AsyncAssertion{ asyncType: asyncType, actualInput: actualInput, - fail: fail, + failWrapper: failWrapper, timeoutInterval: timeoutInterval, pollingInterval: pollingInterval, offset: offset, @@ -45,10 +45,12 @@ func New(asyncType AsyncAssertionType, actualInput interface{}, fail types.Gomeg } func (assertion *AsyncAssertion) Should(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.match(matcher, true, optionalDescription...) } func (assertion *AsyncAssertion) ShouldNot(matcher types.GomegaMatcher, optionalDescription ...interface{}) bool { + assertion.failWrapper.TWithHelper.Helper() return assertion.match(matcher, false, optionalDescription...) } @@ -110,6 +112,8 @@ func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch matches, err = matcher.Match(value) } + assertion.failWrapper.TWithHelper.Helper() + fail := func(preamble string) { errMsg := "" message := "" @@ -122,7 +126,8 @@ func (assertion *AsyncAssertion) match(matcher types.GomegaMatcher, desiredMatch message = matcher.NegatedFailureMessage(value) } } - assertion.fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset) + assertion.failWrapper.TWithHelper.Helper() + assertion.failWrapper.Fail(fmt.Sprintf("%s after %.3fs.\n%s%s%s", preamble, time.Since(timer).Seconds(), description, message, errMsg), 3+assertion.offset) } if assertion.asyncType == AsyncAssertionTypeEventually { diff --git a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go index 13ffae7c..afd61a7c 100644 --- a/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go +++ b/vendor/github.com/onsi/gomega/internal/asyncassertion/async_assertion_test.go @@ -4,9 +4,12 @@ import ( "errors" "time" + "github.com/onsi/gomega/internal/testingtsupport" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/internal/asyncassertion" + "github.com/onsi/gomega/types" ) var _ = Describe("Async Assertion", func() { @@ -15,9 +18,12 @@ var _ = Describe("Async Assertion", func() { callerSkip int ) - var fakeFailHandler = func(message string, skip ...int) { - failureMessage = message - callerSkip = skip[0] + var fakeFailWrapper = &types.GomegaFailWrapper{ + Fail: func(message string, skip ...int) { + failureMessage = message + callerSkip = skip[0] + }, + TWithHelper: testingtsupport.EmptyTWithHelper{}, } BeforeEach(func() { @@ -32,7 +38,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeEventually, func() int { counter++ return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(BeNumerically("==", 5)) Expect(failureMessage).Should(BeZero()) @@ -46,7 +52,7 @@ var _ = Describe("Async Assertion", func() { return "not-a-number" //this should cause the matcher to error } return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(BeNumerically("==", 5), "My description %d", 2) @@ -60,7 +66,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeEventually, func() int { counter++ return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(BeNumerically(">", 100), "My description %d", 2) @@ -79,7 +85,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeEventually, func() int { counter += 1 return counter - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(BeNumerically("<", 3)) @@ -90,7 +96,7 @@ var _ = Describe("Async Assertion", func() { It("should timeout when the matcher errors", func() { a := New(AsyncAssertionTypeEventually, func() interface{} { return 0 //this should cause the matcher to error - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(HaveLen(0), "My description %d", 2) @@ -103,7 +109,7 @@ var _ = Describe("Async Assertion", func() { It("should be able to timeout", func() { a := New(AsyncAssertionTypeEventually, func() int { return 0 - }, fakeFailHandler, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.1*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(Equal(0), "My description %d", 2) @@ -128,7 +134,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeEventually, func() (int, error) { i++ return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(Equal(2)) Expect(failureMessage).Should(ContainSubstring("Timed out after")) @@ -164,7 +170,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeConsistently, func() string { calls++ return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(Equal("foo")) Expect(calls).Should(BeNumerically(">", 8)) @@ -182,7 +188,7 @@ var _ = Describe("Async Assertion", func() { return "bar" } return "foo" - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(Equal("foo")) Expect(failureMessage).Should(ContainSubstring("to equal")) @@ -199,7 +205,7 @@ var _ = Describe("Async Assertion", func() { return 3 } return []int{1, 2, 3} - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(HaveLen(3)) Expect(failureMessage).Should(ContainSubstring("HaveLen matcher expects")) @@ -212,7 +218,7 @@ var _ = Describe("Async Assertion", func() { Context("when the matcher consistently passes for the duration", func() { It("should pass", func() { c := make(chan bool) - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + a := New(AsyncAssertionTypeConsistently, c, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(Receive()) Expect(failureMessage).Should(BeZero()) @@ -227,7 +233,7 @@ var _ = Describe("Async Assertion", func() { c <- true }() - a := New(AsyncAssertionTypeConsistently, c, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + a := New(AsyncAssertionTypeConsistently, c, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(Receive()) Expect(failureMessage).Should(ContainSubstring("not to receive anything")) @@ -240,7 +246,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeConsistently, func() interface{} { calls++ return calls - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.ShouldNot(BeNumerically(">", 5)) Expect(failureMessage).Should(ContainSubstring("not to be >")) @@ -263,7 +269,7 @@ var _ = Describe("Async Assertion", func() { a := New(AsyncAssertionTypeEventually, func() (int, error) { i++ return i, errors.New("bam") - }, fakeFailHandler, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) + }, fakeFailWrapper, time.Duration(0.2*float64(time.Second)), time.Duration(0.02*float64(time.Second)), 1) a.Should(BeNumerically(">=", 2)) Expect(failureMessage).Should(ContainSubstring("Error:")) @@ -292,19 +298,19 @@ var _ = Describe("Async Assertion", func() { Context("when passed a function with the wrong # or arguments & returns", func() { It("should panic", func() { Expect(func() { - New(AsyncAssertionTypeEventually, func() {}, fakeFailHandler, 0, 0, 1) + New(AsyncAssertionTypeEventually, func() {}, fakeFailWrapper, 0, 0, 1) }).Should(Panic()) Expect(func() { - New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailHandler, 0, 0, 1) + New(AsyncAssertionTypeEventually, func(a string) int { return 0 }, fakeFailWrapper, 0, 0, 1) }).Should(Panic()) Expect(func() { - New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailHandler, 0, 0, 1) + New(AsyncAssertionTypeEventually, func() int { return 0 }, fakeFailWrapper, 0, 0, 1) }).ShouldNot(Panic()) Expect(func() { - New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailHandler, 0, 0, 1) + New(AsyncAssertionTypeEventually, func() (int, error) { return 0, nil }, fakeFailWrapper, 0, 0, 1) }).ShouldNot(Panic()) }) }) diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go index ac891252..bb27032f 100644 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go +++ b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support.go @@ -8,30 +8,50 @@ import ( "github.com/onsi/gomega/types" ) +var StackTracePruneRE = regexp.MustCompile(`\/gomega\/|\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) + +type EmptyTWithHelper struct{} + +func (e EmptyTWithHelper) Helper() {} + type gomegaTestingT interface { Fatalf(format string, args ...interface{}) } -func BuildTestingTGomegaFailHandler(t gomegaTestingT) types.GomegaFailHandler { - return func(message string, callerSkip ...int) { - skip := 1 - if len(callerSkip) > 0 { - skip = callerSkip[0] +func BuildTestingTGomegaFailWrapper(t gomegaTestingT) *types.GomegaFailWrapper { + tWithHelper, hasHelper := t.(types.TWithHelper) + if !hasHelper { + tWithHelper = EmptyTWithHelper{} + } + + fail := func(message string, callerSkip ...int) { + if hasHelper { + tWithHelper.Helper() + t.Fatalf("\n%s", message) + } else { + skip := 2 + if len(callerSkip) > 0 { + skip += callerSkip[0] + } + stackTrace := pruneStack(string(debug.Stack()), skip) + t.Fatalf("\n%s\n%s\n", stackTrace, message) } - stackTrace := pruneStack(string(debug.Stack()), skip) - t.Fatalf("\n%s\n%s", stackTrace, message) + } + + return &types.GomegaFailWrapper{ + Fail: fail, + TWithHelper: tWithHelper, } } func pruneStack(fullStackTrace string, skip int) string { - stack := strings.Split(fullStackTrace, "\n") - if len(stack) > 2*(skip+1) { - stack = stack[2*(skip+1):] + stack := strings.Split(fullStackTrace, "\n")[1:] + if len(stack) > 2*skip { + stack = stack[2*skip:] } prunedStack := []string{} - re := regexp.MustCompile(`\/ginkgo\/|\/pkg\/testing\/|\/pkg\/runtime\/`) for i := 0; i < len(stack)/2; i++ { - if !re.Match([]byte(stack[i*2])) { + if !StackTracePruneRE.Match([]byte(stack[i*2])) { prunedStack = append(prunedStack, stack[i*2]) prunedStack = append(prunedStack, stack[i*2+1]) } diff --git a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go index 9c6ccbdf..8fd8f0a6 100644 --- a/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go +++ b/vendor/github.com/onsi/gomega/internal/testingtsupport/testing_t_support_test.go @@ -1,34 +1,92 @@ package testingtsupport_test import ( + "regexp" + "time" + + "github.com/onsi/gomega/internal/testingtsupport" + . "github.com/onsi/gomega" "fmt" "testing" ) -type FakeT struct { - LastCall string +func TestTestingT(t *testing.T) { + RegisterTestingT(t) + Ω(true).Should(BeTrue()) } -func (f *FakeT) Fatalf(format string, args ...interface{}) { - f.LastCall = fmt.Sprintf(format, args...) +type FakeTWithHelper struct { + LastFatal string } -func TestTestingT(t *testing.T) { - RegisterTestingT(t) - Expect(true).Should(BeTrue()) +func (f *FakeTWithHelper) Fatalf(format string, args ...interface{}) { + f.LastFatal = fmt.Sprintf(format, args...) +} + +func TestGomegaWithTWithoutHelper(t *testing.T) { + g := NewGomegaWithT(t) + + testingtsupport.StackTracePruneRE = regexp.MustCompile(`\/ginkgo\/`) + + f := &FakeTWithHelper{} + testG := NewGomegaWithT(f) + + testG.Expect("foo").To(Equal("foo")) + g.Expect(f.LastFatal).To(BeZero()) + + testG.Expect("foo").To(Equal("bar")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo")) + g.Expect(f.LastFatal).To(ContainSubstring("testingtsupport_test"), "It should include a stacktrace") + + testG.Eventually("foo2", time.Millisecond).Should(Equal("bar")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo2")) + + testG.Consistently("foo3", time.Millisecond).Should(Equal("bar")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo3")) +} + +type FakeTWithoutHelper struct { + LastFatal string + HelperCount int +} + +func (f *FakeTWithoutHelper) Fatalf(format string, args ...interface{}) { + f.LastFatal = fmt.Sprintf(format, args...) +} + +func (f *FakeTWithoutHelper) Helper() { + f.HelperCount += 1 } -func TestGomegaWithT(t *testing.T) { +func (f *FakeTWithoutHelper) ResetHelper() { + f.HelperCount = 0 +} + +func TestGomegaWithTWithHelper(t *testing.T) { g := NewGomegaWithT(t) - f := &FakeT{} + f := &FakeTWithoutHelper{} testG := NewGomegaWithT(f) testG.Expect("foo").To(Equal("foo")) - g.Expect(f.LastCall).To(BeZero()) + g.Expect(f.LastFatal).To(BeZero()) + g.Expect(f.HelperCount).To(BeNumerically(">", 0)) + f.ResetHelper() testG.Expect("foo").To(Equal("bar")) - g.Expect(f.LastCall).To(ContainSubstring(": foo")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo")) + g.Expect(f.LastFatal).NotTo(ContainSubstring("testingtsupport_test"), "It should _not_ include a stacktrace") + g.Expect(f.HelperCount).To(BeNumerically(">", 0)) + f.ResetHelper() + + testG.Eventually("foo2", time.Millisecond).Should(Equal("bar")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo2")) + g.Expect(f.HelperCount).To(BeNumerically(">", 0)) + f.ResetHelper() + + testG.Consistently("foo3", time.Millisecond).Should(Equal("bar")) + g.Expect(f.LastFatal).To(ContainSubstring(": foo3")) + g.Expect(f.HelperCount).To(BeNumerically(">", 0)) } diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go index 0c157f61..9f4f77ee 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher.go @@ -13,11 +13,23 @@ type BeNumericallyMatcher struct { } func (matcher *BeNumericallyMatcher) FailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("to be %s", matcher.Comparator), matcher.CompareTo[0]) + return matcher.FormatFailureMessage(actual, false) } func (matcher *BeNumericallyMatcher) NegatedFailureMessage(actual interface{}) (message string) { - return format.Message(actual, fmt.Sprintf("not to be %s", matcher.Comparator), matcher.CompareTo[0]) + return matcher.FormatFailureMessage(actual, true) +} + +func (matcher *BeNumericallyMatcher) FormatFailureMessage(actual interface{}, negated bool) (message string) { + if len(matcher.CompareTo) == 1 { + message = fmt.Sprintf("to be %s", matcher.Comparator) + } else { + message = fmt.Sprintf("to be within %v of %s", matcher.CompareTo[1], matcher.Comparator) + } + if negated { + message = "not " + message + } + return format.Message(actual, message, matcher.CompareTo[0]) } func (matcher *BeNumericallyMatcher) Match(actual interface{}) (success bool, err error) { diff --git a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go index bd385b7f..c7d7c3f7 100644 --- a/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go +++ b/vendor/github.com/onsi/gomega/matchers/be_numerically_matcher_test.go @@ -74,6 +74,18 @@ var _ = Describe("BeNumerically", func() { Expect(5.00000001).Should(BeNumerically("~", 5.00000002)) Expect(5.00000001).ShouldNot(BeNumerically("~", 5.0000001)) }) + + It("should show failure message", func(){ + actual := BeNumerically("~", 4.98).FailureMessage(123) + expected := "Expected\n : 123\nto be ~\n : 4.98" + Expect(actual).To(Equal(expected)) + }) + + It("should show negated failure message", func(){ + actual := BeNumerically("~", 4.98).NegatedFailureMessage(123) + expected := "Expected\n : 123\nnot to be ~\n : 4.98" + Expect(actual).To(Equal(expected)) + }) }) Context("and there is a precision parameter", func() { @@ -83,6 +95,18 @@ var _ = Describe("BeNumerically", func() { Expect(5.1).ShouldNot(BeNumerically("~", 5.22, 0.1)) Expect(5.1).ShouldNot(BeNumerically("~", 4.98, 0.1)) }) + + It("should show precision in failure message", func(){ + actual := BeNumerically("~", 4.98, 0.1).FailureMessage(123) + expected := "Expected\n : 123\nto be within 0.1 of ~\n : 4.98" + Expect(actual).To(Equal(expected)) + }) + + It("should show precision in negated failure message", func(){ + actual := BeNumerically("~", 4.98, 0.1).NegatedFailureMessage(123) + expected := "Expected\n : 123\nnot to be within 0.1 of ~\n : 4.98" + Expect(actual).To(Equal(expected)) + }) }) }) diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go index 499bb583..f962f139 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_json_matcher.go @@ -4,8 +4,6 @@ import ( "bytes" "encoding/json" "fmt" - "reflect" - "strings" "github.com/onsi/gomega/format" ) @@ -42,32 +40,6 @@ func (matcher *MatchJSONMatcher) NegatedFailureMessage(actual interface{}) (mess return formattedMessage(format.Message(actualString, "not to match JSON of", expectedString), matcher.firstFailurePath) } -func formattedMessage(comparisonMessage string, failurePath []interface{}) string { - var diffMessage string - if len(failurePath) == 0 { - diffMessage = "" - } else { - diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath)) - } - return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) -} - -func formattedFailurePath(failurePath []interface{}) string { - formattedPaths := []string{} - for i := len(failurePath) - 1; i >= 0; i-- { - switch p := failurePath[i].(type) { - case int: - formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p)) - default: - if i != len(failurePath)-1 { - formattedPaths = append(formattedPaths, ".") - } - formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p)) - } - } - return strings.Join(formattedPaths, "") -} - func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatted, expectedFormatted string, err error) { actualString, ok := toString(actual) if !ok { @@ -91,45 +63,3 @@ func (matcher *MatchJSONMatcher) prettyPrint(actual interface{}) (actualFormatte return abuf.String(), ebuf.String(), nil } - -func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { - var errorPath []interface{} - if reflect.TypeOf(a) != reflect.TypeOf(b) { - return false, errorPath - } - - switch a.(type) { - case []interface{}: - if len(a.([]interface{})) != len(b.([]interface{})) { - return false, errorPath - } - - for i, v := range a.([]interface{}) { - elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) - if !elementEqual { - return false, append(keyPath, i) - } - } - return true, errorPath - - case map[string]interface{}: - if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { - return false, errorPath - } - - for k, v1 := range a.(map[string]interface{}) { - v2, ok := b.(map[string]interface{})[k] - if !ok { - return false, errorPath - } - elementEqual, keyPath := deepEqual(v1, v2) - if !elementEqual { - return false, append(keyPath, k) - } - } - return true, errorPath - - default: - return a == b, errorPath - } -} diff --git a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go b/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go index 690c83f9..4a1a9db2 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go +++ b/vendor/github.com/onsi/gomega/matchers/match_json_matcher_test.go @@ -1,6 +1,8 @@ package matchers_test import ( + "encoding/json" + . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" . "github.com/onsi/gomega/matchers" @@ -29,6 +31,10 @@ var _ = Describe("MatchJSONMatcher", func() { Expect("{}").Should(MatchJSON([]byte("{}"))) Expect([]byte("{}")).Should(MatchJSON("{}")) }) + + It("should work with json.RawMessage", func() { + Expect([]byte(`{"a": 1}`)).Should(MatchJSON(json.RawMessage(`{"a": 1}`))) + }) }) Context("when a key mismatch is found", func() { diff --git a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go index 69fb51a8..070d6026 100644 --- a/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go +++ b/vendor/github.com/onsi/gomega/matchers/match_yaml_matcher.go @@ -2,7 +2,6 @@ package matchers import ( "fmt" - "reflect" "strings" "github.com/onsi/gomega/format" @@ -10,7 +9,8 @@ import ( ) type MatchYAMLMatcher struct { - YAMLToMatch interface{} + YAMLToMatch interface{} + firstFailurePath []interface{} } func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err error) { @@ -29,17 +29,19 @@ func (matcher *MatchYAMLMatcher) Match(actual interface{}) (success bool, err er return false, fmt.Errorf("Expected '%s' should be valid YAML, but it is not.\nUnderlying error:%s", expectedString, err) } - return reflect.DeepEqual(aval, eval), nil + var equal bool + equal, matcher.firstFailurePath = deepEqual(aval, eval) + return equal, nil } func (matcher *MatchYAMLMatcher) FailureMessage(actual interface{}) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return format.Message(actualString, "to match YAML of", expectedString) + return formattedMessage(format.Message(actualString, "to match YAML of", expectedString), matcher.firstFailurePath) } func (matcher *MatchYAMLMatcher) NegatedFailureMessage(actual interface{}) (message string) { actualString, expectedString, _ := matcher.toNormalisedStrings(actual) - return format.Message(actualString, "not to match YAML of", expectedString) + return formattedMessage(format.Message(actualString, "not to match YAML of", expectedString), matcher.firstFailurePath) } func (matcher *MatchYAMLMatcher) toNormalisedStrings(actual interface{}) (actualFormatted, expectedFormatted string, err error) { diff --git a/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go b/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go new file mode 100644 index 00000000..63929568 --- /dev/null +++ b/vendor/github.com/onsi/gomega/matchers/semi_structured_data_support.go @@ -0,0 +1,92 @@ +package matchers + +import ( + "fmt" + "reflect" + "strings" +) + +func formattedMessage(comparisonMessage string, failurePath []interface{}) string { + var diffMessage string + if len(failurePath) == 0 { + diffMessage = "" + } else { + diffMessage = fmt.Sprintf("\n\nfirst mismatched key: %s", formattedFailurePath(failurePath)) + } + return fmt.Sprintf("%s%s", comparisonMessage, diffMessage) +} + +func formattedFailurePath(failurePath []interface{}) string { + formattedPaths := []string{} + for i := len(failurePath) - 1; i >= 0; i-- { + switch p := failurePath[i].(type) { + case int: + formattedPaths = append(formattedPaths, fmt.Sprintf(`[%d]`, p)) + default: + if i != len(failurePath)-1 { + formattedPaths = append(formattedPaths, ".") + } + formattedPaths = append(formattedPaths, fmt.Sprintf(`"%s"`, p)) + } + } + return strings.Join(formattedPaths, "") +} + +func deepEqual(a interface{}, b interface{}) (bool, []interface{}) { + var errorPath []interface{} + if reflect.TypeOf(a) != reflect.TypeOf(b) { + return false, errorPath + } + + switch a.(type) { + case []interface{}: + if len(a.([]interface{})) != len(b.([]interface{})) { + return false, errorPath + } + + for i, v := range a.([]interface{}) { + elementEqual, keyPath := deepEqual(v, b.([]interface{})[i]) + if !elementEqual { + return false, append(keyPath, i) + } + } + return true, errorPath + + case map[interface{}]interface{}: + if len(a.(map[interface{}]interface{})) != len(b.(map[interface{}]interface{})) { + return false, errorPath + } + + for k, v1 := range a.(map[interface{}]interface{}) { + v2, ok := b.(map[interface{}]interface{})[k] + if !ok { + return false, errorPath + } + elementEqual, keyPath := deepEqual(v1, v2) + if !elementEqual { + return false, append(keyPath, k) + } + } + return true, errorPath + + case map[string]interface{}: + if len(a.(map[string]interface{})) != len(b.(map[string]interface{})) { + return false, errorPath + } + + for k, v1 := range a.(map[string]interface{}) { + v2, ok := b.(map[string]interface{})[k] + if !ok { + return false, errorPath + } + elementEqual, keyPath := deepEqual(v1, v2) + if !elementEqual { + return false, append(keyPath, k) + } + } + return true, errorPath + + default: + return a == b, errorPath + } +} diff --git a/vendor/github.com/onsi/gomega/matchers/type_support.go b/vendor/github.com/onsi/gomega/matchers/type_support.go index b05a5e75..75afcd84 100644 --- a/vendor/github.com/onsi/gomega/matchers/type_support.go +++ b/vendor/github.com/onsi/gomega/matchers/type_support.go @@ -9,6 +9,7 @@ http://onsi.github.io/gomega/ package matchers import ( + "encoding/json" "fmt" "reflect" ) @@ -133,6 +134,11 @@ func toString(a interface{}) (string, bool) { return aStringer.String(), true } + aJSONRawMessage, isJSONRawMessage := a.(json.RawMessage) + if isJSONRawMessage { + return string(aJSONRawMessage), true + } + return "", false } diff --git a/vendor/github.com/onsi/gomega/types/types.go b/vendor/github.com/onsi/gomega/types/types.go index 51256ede..ac59a3a5 100644 --- a/vendor/github.com/onsi/gomega/types/types.go +++ b/vendor/github.com/onsi/gomega/types/types.go @@ -1,7 +1,16 @@ package types +type TWithHelper interface { + Helper() +} + type GomegaFailHandler func(message string, callerSkip ...int) +type GomegaFailWrapper struct { + Fail GomegaFailHandler + TWithHelper TWithHelper +} + //A simple *testing.T interface wrapper type GomegaTestingT interface { Fatalf(format string, args ...interface{}) diff --git a/vendor/github.com/spf13/afero/go.mod b/vendor/github.com/spf13/afero/go.mod new file mode 100644 index 00000000..9eff4fed --- /dev/null +++ b/vendor/github.com/spf13/afero/go.mod @@ -0,0 +1 @@ +module github.com/spf13/afero diff --git a/vendor/github.com/spf13/jwalterweatherman/go.mod b/vendor/github.com/spf13/jwalterweatherman/go.mod new file mode 100644 index 00000000..bce549c0 --- /dev/null +++ b/vendor/github.com/spf13/jwalterweatherman/go.mod @@ -0,0 +1 @@ +module github.com/spf13/jwalterweatherman diff --git a/vendor/golang.org/x/crypto/acme/autocert/example_test.go b/vendor/golang.org/x/crypto/acme/autocert/example_test.go index 89e2d836..d4225e5c 100644 --- a/vendor/golang.org/x/crypto/acme/autocert/example_test.go +++ b/vendor/golang.org/x/crypto/acme/autocert/example_test.go @@ -24,7 +24,7 @@ func ExampleManager() { m := &autocert.Manager{ Cache: autocert.DirCache("secret-dir"), Prompt: autocert.AcceptTOS, - HostPolicy: autocert.HostWhitelist("example.org"), + HostPolicy: autocert.HostWhitelist("example.org", "www.example.org"), } s := &http.Server{ Addr: ":https", diff --git a/vendor/golang.org/x/crypto/openpgp/keys.go b/vendor/golang.org/x/crypto/openpgp/keys.go index a79a8c13..efe6e730 100644 --- a/vendor/golang.org/x/crypto/openpgp/keys.go +++ b/vendor/golang.org/x/crypto/openpgp/keys.go @@ -333,7 +333,6 @@ func ReadEntity(packets *packet.Reader) (*Entity, error) { return nil, errors.StructuralError("primary key cannot be used for signatures") } - var current *Identity var revocations []*packet.Signature EachPacket: for { @@ -349,7 +348,7 @@ EachPacket: // Make a new Identity object, that we might wind up throwing away. // We'll only add it if we get a valid self-signature over this // userID. - current = new(Identity) + current := new(Identity) current.Name = pkt.Id current.UserId = pkt @@ -384,11 +383,9 @@ EachPacket: // TODO: RFC4880 5.2.1 permits signatures // directly on keys (eg. to bind additional // revocation keys). - } else if current == nil { - return nil, errors.StructuralError("signature packet found before user id packet") - } else { - current.Signatures = append(current.Signatures, pkt) } + // Else, ignoring the signature as it does not follow anything + // we would know to attach it to. case *packet.PrivateKey: if pkt.IsSubkey == false { packets.Unread(p) @@ -433,26 +430,45 @@ func addSubkey(e *Entity, packets *packet.Reader, pub *packet.PublicKey, priv *p var subKey Subkey subKey.PublicKey = pub subKey.PrivateKey = priv - p, err := packets.Next() - if err == io.EOF { - return io.ErrUnexpectedEOF - } - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) + + for { + p, err := packets.Next() + if err == io.EOF { + break + } else if err != nil { + return errors.StructuralError("subkey signature invalid: " + err.Error()) + } + + sig, ok := p.(*packet.Signature) + if !ok { + packets.Unread(p) + break + } + + if sig.SigType != packet.SigTypeSubkeyBinding && sig.SigType != packet.SigTypeSubkeyRevocation { + return errors.StructuralError("subkey signature with wrong type") + } + + if err := e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, sig); err != nil { + return errors.StructuralError("subkey signature invalid: " + err.Error()) + } + + switch sig.SigType { + case packet.SigTypeSubkeyRevocation: + subKey.Sig = sig + case packet.SigTypeSubkeyBinding: + if subKey.Sig == nil { + subKey.Sig = sig + } + } } - var ok bool - subKey.Sig, ok = p.(*packet.Signature) - if !ok { + + if subKey.Sig == nil { return errors.StructuralError("subkey packet not followed by signature") } - if subKey.Sig.SigType != packet.SigTypeSubkeyBinding && subKey.Sig.SigType != packet.SigTypeSubkeyRevocation { - return errors.StructuralError("subkey signature with wrong type") - } - err = e.PrimaryKey.VerifyKeySignature(subKey.PublicKey, subKey.Sig) - if err != nil { - return errors.StructuralError("subkey signature invalid: " + err.Error()) - } + e.Subkeys = append(e.Subkeys, subKey) + return nil } diff --git a/vendor/golang.org/x/crypto/openpgp/keys_test.go b/vendor/golang.org/x/crypto/openpgp/keys_test.go index d877589a..46225d4d 100644 --- a/vendor/golang.org/x/crypto/openpgp/keys_test.go +++ b/vendor/golang.org/x/crypto/openpgp/keys_test.go @@ -180,6 +180,44 @@ func TestKeyRevocation(t *testing.T) { } } +func TestKeyWithRevokedSubKey(t *testing.T) { + // This key contains a revoked sub key: + // pub rsa1024/0x4CBD826C39074E38 2018-06-14 [SC] + // Key fingerprint = 3F95 169F 3FFA 7D3F 2B47 6F0C 4CBD 826C 3907 4E38 + // uid Golang Gopher + // sub rsa1024/0x945DB1AF61D85727 2018-06-14 [S] [revoked: 2018-06-14] + + keys, err := ReadArmoredKeyRing(bytes.NewBufferString(keyWithSubKey)) + if err != nil { + t.Fatal(err) + } + + if len(keys) != 1 { + t.Fatal("Failed to read key with a sub key") + } + + identity := keys[0].Identities["Golang Gopher "] + + // Test for an issue where Subkey Binding Signatures (RFC 4880 5.2.1) were added to the identity + // preceding the Subkey Packet if the Subkey Packet was followed by more than one signature. + // For example, the current key has the following layout: + // PUBKEY UID SELFSIG SUBKEY REV SELFSIG + // The last SELFSIG would be added to the UID's signatures. This is wrong. + if numIdentitySigs, numExpected := len(identity.Signatures), 0; numIdentitySigs != numExpected { + t.Fatalf("got %d identity signatures, expected %d", numIdentitySigs, numExpected) + } + + if numSubKeys, numExpected := len(keys[0].Subkeys), 1; numSubKeys != numExpected { + t.Fatalf("got %d subkeys, expected %d", numSubKeys, numExpected) + } + + subKey := keys[0].Subkeys[0] + if subKey.Sig == nil { + t.Fatalf("subkey signature is nil") + } + +} + func TestSubkeyRevocation(t *testing.T) { kring, err := ReadKeyRing(readerFromHex(revokedSubkeyHex)) if err != nil { @@ -547,3 +585,31 @@ heiQvzkApQup5c+BhH5zFDFdKJ2CBByxw9+7QjMFI/wgLixKuE0Ob2kAokXf7RlB 7qTZOahrETw= =IKnw -----END PGP PUBLIC KEY BLOCK-----` + +const keyWithSubKey = `-----BEGIN PGP PUBLIC KEY BLOCK----- + +mI0EWyKwKQEEALwXhKBnyaaNFeK3ljfc/qn9X/QFw+28EUfgZPHjRmHubuXLE2uR +s3ZoSXY2z7Dkv+NyHYMt8p+X8q5fR7JvUjK2XbPyKoiJVnHINll83yl67DaWfKNL +EjNoO0kIfbXfCkZ7EG6DL+iKtuxniGTcnGT47e+HJSqb/STpLMnWwXjBABEBAAG0 +I0dvbGFuZyBHb3BoZXIgPG5vLXJlcGx5QGdvbGFuZy5jb20+iM4EEwEKADgWIQQ/ +lRafP/p9PytHbwxMvYJsOQdOOAUCWyKwKQIbAwULCQgHAwUVCgkICwUWAgMBAAIe +AQIXgAAKCRBMvYJsOQdOOOsFBAC62mXww8XuqvYLcVOvHkWLT6mhxrQOJXnlfpn7 +2uBV9CMhoG/Ycd43NONsJrB95Apr9TDIqWnVszNbqPCuBhZQSGLdbiDKjxnCWBk0 +69qv4RNtkpOhYB7jK4s8F5oQZqId6JasT/PmJTH92mhBYhhTQr0GYFuPX2UJdkw9 +Sn9C67iNBFsisDUBBAC3A+Yo9lgCnxi/pfskyLrweYif6kIXWLAtLTsM6g/6jt7b +wTrknuCPyTv0QKGXsAEe/cK/Xq3HvX9WfXPGIHc/X56ZIsHQ+RLowbZV/Lhok1IW +FAuQm8axr/by80cRwFnzhfPc/ukkAq2Qyj4hLsGblu6mxeAhzcp8aqmWOO2H9QAR +AQABiLYEKAEKACAWIQQ/lRafP/p9PytHbwxMvYJsOQdOOAUCWyK16gIdAAAKCRBM +vYJsOQdOOB1vA/4u4uLONsE+2GVOyBsHyy7uTdkuxaR9b54A/cz6jT/tzUbeIzgx +22neWhgvIEghnUZd0vEyK9k1wy5vbDlEo6nKzHso32N1QExGr5upRERAxweDxGOj +7luDwNypI7QcifE64lS/JmlnunwRCdRWMKc0Fp+7jtRc5mpwyHN/Suf5RokBagQY +AQoAIBYhBD+VFp8/+n0/K0dvDEy9gmw5B044BQJbIrA1AhsCAL8JEEy9gmw5B044 +tCAEGQEKAB0WIQSNdnkaWY6t62iX336UXbGvYdhXJwUCWyKwNQAKCRCUXbGvYdhX +JxJSA/9fCPHP6sUtGF1o3G1a3yvOUDGr1JWcct9U+QpbCt1mZoNopCNDDQAJvDWl +mvDgHfuogmgNJRjOMznvahbF+wpTXmB7LS0SK412gJzl1fFIpK4bgnhu0TwxNsO1 +8UkCZWqxRMgcNUn9z6XWONK8dgt5JNvHSHrwF4CxxwjL23AAtK+FA/UUoi3U4kbC +0XnSr1Sl+mrzQi1+H7xyMe7zjqe+gGANtskqexHzwWPUJCPZ5qpIa2l8ghiUim6b +4ymJ+N8/T8Yva1FaPEqfMzzqJr8McYFm0URioXJPvOAlRxdHPteZ0qUopt/Jawxl +Xt6B9h1YpeLoJwjwsvbi98UTRs0jXwoY +=3fWu +-----END PGP PUBLIC KEY BLOCK-----` diff --git a/vendor/golang.org/x/crypto/ssh/keys.go b/vendor/golang.org/x/crypto/ssh/keys.go index 34d95822..2261dc38 100644 --- a/vendor/golang.org/x/crypto/ssh/keys.go +++ b/vendor/golang.org/x/crypto/ssh/keys.go @@ -903,8 +903,8 @@ func ParseDSAPrivateKey(der []byte) (*dsa.PrivateKey, error) { // Implemented based on the documentation at // https://github.com/openssh/openssh-portable/blob/master/PROTOCOL.key func parseOpenSSHPrivateKey(key []byte) (crypto.PrivateKey, error) { - magic := append([]byte("openssh-key-v1"), 0) - if !bytes.Equal(magic, key[0:len(magic)]) { + const magic = "openssh-key-v1\x00" + if len(key) < len(magic) || string(key[:len(magic)]) != magic { return nil, errors.New("ssh: invalid openssh private key format") } remaining := key[len(magic):] diff --git a/vendor/golang.org/x/crypto/ssh/keys_test.go b/vendor/golang.org/x/crypto/ssh/keys_test.go index 9a90abc0..f28725f1 100644 --- a/vendor/golang.org/x/crypto/ssh/keys_test.go +++ b/vendor/golang.org/x/crypto/ssh/keys_test.go @@ -13,7 +13,9 @@ import ( "crypto/rsa" "crypto/x509" "encoding/base64" + "encoding/pem" "fmt" + "io" "reflect" "strings" "testing" @@ -498,3 +500,32 @@ func TestFingerprintSHA256(t *testing.T) { t.Errorf("got fingerprint %q want %q", fingerprint, want) } } + +func TestInvalidKeys(t *testing.T) { + keyTypes := []string{ + "RSA PRIVATE KEY", + "PRIVATE KEY", + "EC PRIVATE KEY", + "DSA PRIVATE KEY", + "OPENSSH PRIVATE KEY", + } + + for _, keyType := range keyTypes { + for _, dataLen := range []int{0, 1, 2, 5, 10, 20} { + data := make([]byte, dataLen) + if _, err := io.ReadFull(rand.Reader, data); err != nil { + t.Fatal(err) + } + + var buf bytes.Buffer + pem.Encode(&buf, &pem.Block{ + Type: keyType, + Bytes: data, + }) + + // This test is just to ensure that the function + // doesn't panic so the return value is ignored. + ParseRawPrivateKey(buf.Bytes()) + } + } +} diff --git a/vendor/golang.org/x/net/html/parse.go b/vendor/golang.org/x/net/html/parse.go index 1489ff92..091fb0d1 100644 --- a/vendor/golang.org/x/net/html/parse.go +++ b/vendor/golang.org/x/net/html/parse.go @@ -209,27 +209,6 @@ loop: p.oe = p.oe[:i+1] } -// generateAllImpliedEndTags pops nodes off the stack of open elements as long as -// the top node has a tag name of caption, colgroup, dd, div, dt, li, optgroup, option, p, rb, -// rp, rt, rtc, span, tbody, td, tfoot, th, thead or tr. -func (p *parser) generateAllImpliedEndTags() { - var i int - for i = len(p.oe) - 1; i >= 0; i-- { - n := p.oe[i] - if n.Type == ElementNode { - switch n.DataAtom { - // TODO: remove this divergence from the HTML5 spec - case a.Caption, a.Colgroup, a.Dd, a.Div, a.Dt, a.Li, a.Optgroup, a.Option, a.P, a.Rb, - a.Rp, a.Rt, a.Rtc, a.Span, a.Tbody, a.Td, a.Tfoot, a.Th, a.Thead, a.Tr: - continue - } - } - break - } - - p.oe = p.oe[:i+1] -} - // addChild adds a child node n to the top element, and pushes n onto the stack // of open elements if it is an element node. func (p *parser) addChild(n *Node) { @@ -276,7 +255,7 @@ func (p *parser) fosterParent(n *Node) { } } - if template != nil && (table == nil || j < i) { + if template != nil && (table == nil || j > i) { template.AppendChild(n) return } @@ -679,8 +658,16 @@ func inHeadIM(p *parser) bool { if !p.oe.contains(a.Template) { return true } - p.generateAllImpliedEndTags() - p.popUntil(defaultScope, a.Template) + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.generateImpliedEndTags() + for i := len(p.oe) - 1; i >= 0; i-- { + if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template { + p.oe = p.oe[:i] + break + } + } p.clearActiveFormattingElements() p.templateStack.pop() p.resetInsertionMode() @@ -1342,9 +1329,6 @@ func textIM(p *parser) bool { // Section 12.2.6.4.9. func inTableIM(p *parser) bool { switch p.tok.Type { - case ErrorToken: - // Stop parsing. - return true case TextToken: p.tok.Data = strings.Replace(p.tok.Data, "\x00", "", -1) switch p.oe.top().DataAtom { @@ -1439,6 +1423,8 @@ func inTableIM(p *parser) bool { case DoctypeToken: // Ignore the token. return true + case ErrorToken: + return inBodyIM(p) } p.fosterParenting = true @@ -1541,6 +1527,8 @@ func inColumnGroupIM(p *parser) bool { case a.Template: return inHeadIM(p) } + case ErrorToken: + return inBodyIM(p) } if p.oe.top().DataAtom != a.Colgroup { return true @@ -1705,9 +1693,6 @@ func inCellIM(p *parser) bool { // Section 12.2.6.4.16. func inSelectIM(p *parser) bool { switch p.tok.Type { - case ErrorToken: - // Stop parsing. - return true case TextToken: p.addText(strings.Replace(p.tok.Data, "\x00", "", -1)) case StartTagToken: @@ -1771,6 +1756,8 @@ func inSelectIM(p *parser) bool { case DoctypeToken: // Ignore the token. return true + case ErrorToken: + return inBodyIM(p) } return true @@ -1837,15 +1824,26 @@ func inTemplateIM(p *parser) bool { // Ignore the token. return true } + case ErrorToken: + if !p.oe.contains(a.Template) { + // Ignore the token. + return true + } + // TODO: remove this divergence from the HTML5 spec. + // + // See https://bugs.chromium.org/p/chromium/issues/detail?id=829668 + p.generateImpliedEndTags() + for i := len(p.oe) - 1; i >= 0; i-- { + if n := p.oe[i]; n.Namespace == "" && n.DataAtom == a.Template { + p.oe = p.oe[:i] + break + } + } + p.clearActiveFormattingElements() + p.templateStack.pop() + p.resetInsertionMode() + return false } - if !p.oe.contains(a.Template) { - // Ignore the token. - return true - } - p.popUntil(defaultScope, a.Template) - p.clearActiveFormattingElements() - p.templateStack.pop() - p.resetInsertionMode() return false } @@ -2211,6 +2209,15 @@ func (p *parser) parse() error { } // Parse returns the parse tree for the HTML from the given Reader. +// +// It implements the HTML5 parsing algorithm +// (https://html.spec.whatwg.org/multipage/syntax.html#tree-construction), +// which is very complicated. The resultant tree can contain implicitly created +// nodes that have no explicit listed in r's data, and nodes' parents can +// differ from the nesting implied by a naive processing of start and end +// s. Conversely, explicit s in r's data can be silently dropped, +// with no corresponding node in the resulting tree. +// // The input is assumed to be UTF-8 encoded. func Parse(r io.Reader) (*Node, error) { p := &parser{ @@ -2232,6 +2239,8 @@ func Parse(r io.Reader) (*Node, error) { // ParseFragment parses a fragment of HTML and returns the nodes that were // found. If the fragment is the InnerHTML for an existing element, pass that // element in context. +// +// It has the same intricacies as Parse. func ParseFragment(r io.Reader, context *Node) ([]*Node, error) { contextTag := "" if context != nil { diff --git a/vendor/golang.org/x/net/html/parse_test.go b/vendor/golang.org/x/net/html/parse_test.go index 0b72a12b..1c232c71 100644 --- a/vendor/golang.org/x/net/html/parse_test.go +++ b/vendor/golang.org/x/net/html/parse_test.go @@ -329,6 +329,7 @@ var renderTestBlacklist = map[string]bool{ `ababrx
aoe`: true, `