diff --git a/Makefile b/Makefile index 7920faa21..aa8bfb296 100644 --- a/Makefile +++ b/Makefile @@ -83,6 +83,12 @@ format: ## Format code install-tools: ## Install dependencies in tools.go @grep _ ./scripts/tools.go | awk '{print $$2}' | xargs -tI % go install % +generate-swagger: ## Generates swagger.json from source code + swagger generate spec -o ./docs/swagger.json --scan-models + +launch-swagger-ui: generate-swagger ## Launch Swagger UI + swagger serve ./docs/swagger.json -F=swagger --port=8082 --no-open + # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Local Packaging # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # diff --git a/README.md b/README.md index a48c36c7a..62f6d881d 100644 --- a/README.md +++ b/README.md @@ -182,6 +182,17 @@ api: The mock control plane can use either gRPC or REST protocols to communicate with NGINX Agent. +### Launching Swagger UI +To use the Swagger UI, goswagger needs to be installed first. Instructions on how to install goswagger can be found here https://goswagger.io/install.html. + +To launch the Swagger UI for the REST interface run the following command + +``` +make launch-swagger-ui +``` + +Open a web browser to view the Swagger UI at http://localhost:8082/docs. + ## Starting NGINX Agent If already running, restart NGINX Agent to apply the new configuration. Alternatively, if NGINX Agent is not running, you may run it from the source code root directory. diff --git a/docs/swagger.json b/docs/swagger.json new file mode 100644 index 000000000..5704ee04b --- /dev/null +++ b/docs/swagger.json @@ -0,0 +1,366 @@ +{ + "swagger": "2.0", + "info": {}, + "host": "localhost:8081", + "paths": { + "/metrics/": { + "get": { + "description": "# Returns prometheus metrics", + "produces": [ + "text/plain" + ], + "tags": [ + "nginx-agent" + ], + "summary": "Get Prometheus Metrics", + "operationId": "get-prometheus-metrics", + "responses": { + "200": { + "$ref": "#/responses/MetricsResponse" + } + } + } + }, + "/nginx/": { + "get": { + "description": "# Returns a list of NGINX instances", + "tags": [ + "nginx-agent" + ], + "summary": "Get NGINX Instances", + "operationId": "get-nginx-instances", + "responses": { + "200": { + "description": "NginxDetails", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/NginxDetails" + } + } + } + } + } + }, + "/nginx/config/": { + "put": { + "description": "# Returns a config apply status", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json" + ], + "tags": [ + "nginx-agent" + ], + "summary": "Apply NGINX configuration to all NGINX instances", + "operationId": "apply-nginx-config", + "parameters": [ + { + "type": "file", + "x-go-name": "File", + "name": "file", + "in": "formData" + } + ], + "responses": { + "200": { + "description": "AgentAPIConfigApplyResponse", + "schema": { + "$ref": "#/definitions/AgentAPIConfigApplyResponse" + } + }, + "400": { + "description": "AgentAPICommonResponse", + "schema": { + "$ref": "#/definitions/AgentAPICommonResponse" + } + }, + "408": { + "description": "AgentAPIConfigApplyStatusResponse", + "schema": { + "$ref": "#/definitions/AgentAPIConfigApplyStatusResponse" + } + }, + "500": { + "description": "AgentAPICommonResponse", + "schema": { + "$ref": "#/definitions/AgentAPICommonResponse" + } + } + } + } + }, + "/nginx/config/status": { + "get": { + "description": "# Returns status NGINX config apply", + "tags": [ + "nginx-agent" + ], + "summary": "Get status NGINX config apply", + "operationId": "get-nginx-config-status", + "parameters": [ + { + "type": "string", + "description": "Correlation ID of a NGINX config apply request", + "name": "correlation_id", + "in": "query", + "required": true + } + ], + "responses": { + "200": { + "description": "AgentAPIConfigApplyResponse", + "schema": { + "$ref": "#/definitions/AgentAPIConfigApplyResponse" + } + }, + "400": { + "description": "AgentAPIConfigApplyStatusResponse", + "schema": { + "$ref": "#/definitions/AgentAPIConfigApplyStatusResponse" + } + }, + "404": { + "description": "AgentAPIConfigApplyStatusResponse", + "schema": { + "$ref": "#/definitions/AgentAPIConfigApplyStatusResponse" + } + } + } + } + } + }, + "definitions": { + "AgentAPICommonResponse": { + "type": "object", + "properties": { + "correlation_id": { + "description": "Correlation ID", + "type": "string", + "x-go-name": "CorrelationId", + "example": "6204037c-30e6-408b-8aaa-dd8219860b4b" + }, + "message": { + "description": "Message", + "type": "string", + "x-go-name": "Message", + "example": "No NGINX instances found" + } + }, + "x-go-package": "github.com/nginx/agent/v2/src/plugins" + }, + "AgentAPIConfigApplyResponse": { + "type": "object", + "properties": { + "correlation_id": { + "description": "Correlation ID", + "type": "string", + "x-go-name": "CorrelationId", + "example": "6204037c-30e6-408b-8aaa-dd8219860b4b" + }, + "nginx_instances": { + "description": "NGINX Instances", + "type": "array", + "items": { + "$ref": "#/definitions/NginxInstanceResponse" + }, + "x-go-name": "NginxInstances" + } + }, + "x-go-package": "github.com/nginx/agent/v2/src/plugins" + }, + "AgentAPIConfigApplyStatusResponse": { + "type": "object", + "properties": { + "correlation_id": { + "description": "Correlation ID", + "type": "string", + "x-go-name": "CorrelationId", + "example": "6204037c-30e6-408b-8aaa-dd8219860b4b" + }, + "message": { + "description": "Message", + "type": "string", + "x-go-name": "Message", + "example": "pending config apply" + }, + "status": { + "description": "Status", + "type": "string", + "x-go-name": "Status", + "example": "PENDING" + } + }, + "x-go-package": "github.com/nginx/agent/v2/src/plugins" + }, + "NginxDetails": { + "type": "object", + "properties": { + "built_from_source": { + "description": "Was NGINX built from source", + "type": "boolean", + "x-go-name": "BuiltFromSource", + "example": false + }, + "conf_path": { + "description": "Path to configuration file", + "type": "string", + "x-go-name": "ConfPath", + "example": "/usr/local/nginx/conf/nginx.conf" + }, + "configure_args": { + "description": "Configuration arguments", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "ConfigureArgs", + "example": [ + "", + "with-http_stub_status_module" + ] + }, + "loadable_modules": { + "description": "List of loadable modules", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "LoadableModules", + "example": [] + }, + "nginx_id": { + "description": "NGINX ID", + "type": "string", + "x-go-name": "NginxId", + "example": "b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437" + }, + "plus": { + "$ref": "#/definitions/NginxPlusMetaData" + }, + "process_id": { + "description": "Process ID", + "type": "string", + "x-go-name": "ProcessId", + "example": "8" + }, + "process_path": { + "description": "Process Path", + "type": "string", + "x-go-name": "ProcessPath", + "example": "/usr/local/nginx/sbin/nginx" + }, + "runtime_modules": { + "description": "List of runtime modules", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "RuntimeModules", + "example": [ + "http_stub_status_module" + ] + }, + "ssl": { + "$ref": "#/definitions/NginxSslMetaData" + }, + "start_time": { + "description": "Start Time", + "type": "integer", + "format": "int64", + "x-go-name": "StartTime", + "example": 1670429190000 + }, + "status_url": { + "description": "Status URL", + "type": "string", + "x-go-name": "StatusUrl", + "example": "http://localhost:8080/api" + }, + "version": { + "description": "Version of NGINX", + "type": "string", + "x-go-name": "Version", + "example": "1.23.2" + } + }, + "x-go-package": "github.com/nginx/agent/sdk/v2/proto" + }, + "NginxInstanceResponse": { + "type": "object", + "properties": { + "message": { + "description": "Message", + "type": "string", + "x-go-name": "Message", + "example": "config applied successfully" + }, + "nginx_id": { + "description": "NGINX ID", + "type": "string", + "x-go-name": "NginxId", + "example": "b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437" + }, + "status": { + "description": "Status", + "type": "string", + "x-go-name": "Status", + "example": "OK" + } + }, + "x-go-package": "github.com/nginx/agent/v2/src/plugins" + }, + "NginxPlusMetaData": { + "type": "object", + "properties": { + "enabled": { + "description": "Is NGINX instance a plus instance", + "type": "boolean", + "x-go-name": "Enabled", + "example": true + }, + "release": { + "description": "NGINX plus release", + "type": "string", + "x-go-name": "Release", + "example": "R27" + } + }, + "x-go-package": "github.com/nginx/agent/sdk/v2/proto" + }, + "NginxSslMetaData": { + "type": "object", + "properties": { + "details": { + "description": "SSL details", + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "Details", + "example": null + }, + "ssl_type": { + "$ref": "#/definitions/NginxSslMetaData_NginxSslType" + } + }, + "x-go-package": "github.com/nginx/agent/sdk/v2/proto" + }, + "NginxSslMetaData_NginxSslType": { + "description": "SSL type enum", + "type": "integer", + "format": "int32", + "x-go-package": "github.com/nginx/agent/sdk/v2/proto" + } + }, + "responses": { + "MetricsResponse": { + "description": "", + "schema": { + "type": "string" + } + } + } +} \ No newline at end of file diff --git a/go.mod b/go.mod index e71e8ac54..0d0fcaab9 100644 --- a/go.mod +++ b/go.mod @@ -41,6 +41,7 @@ require ( github.com/go-resty/resty/v2 v2.7.0 github.com/nginx/agent/sdk/v2 v2.0.0-00010101000000-000000000000 github.com/prometheus/client_golang v1.13.0 + github.com/rs/cors v1.8.2 gopkg.in/yaml.v2 v2.4.0 ) diff --git a/go.sum b/go.sum index b7392e772..2160266b4 100644 --- a/go.sum +++ b/go.sum @@ -295,6 +295,8 @@ github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0ua github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= +github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= +github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sclevine/spec v1.4.0 h1:z/Q9idDcay5m5irkZ28M7PtQM4aOISzOpj4bUPkDee8= github.com/sclevine/spec v1.4.0/go.mod h1:LvpgJaFyvQzRvc1kaDs0bulYwzC70PbiYjC4QnFHkOM= diff --git a/go.work.sum b/go.work.sum index 32633b18a..9b1408ec8 100644 --- a/go.work.sum +++ b/go.work.sum @@ -30,6 +30,8 @@ github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3 github.com/Knetic/govaluate v3.0.1-0.20171022003610-9aa49832a739+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= github.com/OneOfOne/xxhash v1.2.2 h1:KMrpdQIwFcEqXDklaen+P1axHaj9BSKzvpUUfnHldSE= github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU= +github.com/PuerkitoBio/purell v1.1.1 h1:WEQqlqaGbrPkxLJWfBwQmfEAE1Z7ONdDLqrN38tNFfI= +github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578 h1:d+Bc7a5rLufV/sSk/8dngufqelfh6jnri85riMAaF/M= github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= @@ -71,7 +73,6 @@ github.com/coreos/go-semver v0.3.0 h1:wkHLiw0WNATZnSG7epLsujiMCgPAc9xhjJ4tgnAxmf github.com/coreos/go-systemd v0.0.0-20180511133405-39ca1b05acc7/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/coreos/go-systemd/v22 v22.3.2 h1:D9/bQk5vlXQFZ6Kwuu6zaiXJ9oTPe68++AzAJc1DzSI= github.com/coreos/pkg v0.0.0-20160727233714-3ac0863d7acf/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA= -github.com/cpuguy83/go-md2man/v2 v2.0.0-20190314233015-f79a8a8ca69d/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU= github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w= github.com/creack/pty v1.1.7/go.mod h1:lj5s0c3V2DBrqTV7llrYr5NG6My20zk30Fl46Y7DoTY= github.com/creack/pty v1.1.9 h1:uDmaGzcdjhF4i/plgjmEsriH11Y0o7RKapEf/LDaM3w= @@ -224,6 +225,7 @@ github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxzi github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nginxinc/nginx-plus-go-client v0.8.0/go.mod h1:DBAmdDP71tOhgFPdCMVusegzdKmLVpVL0nVcMX17pbY= github.com/nginxinc/nginx-prometheus-exporter v0.9.0/go.mod h1:IDlTI98WaztOTMWG68EjsUTM9epAvLrYD1P9pGh/QDk= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= github.com/oklog/oklog v0.3.2/go.mod h1:FCV+B7mhrz4o+ueLpx+KqkyXRGMWOYEvfiXtdGtbWGs= github.com/oklog/run v1.0.0/go.mod h1:dlhp/R75TPv97u0XWUtDeV/lRKWPKSdTuV0TZvrmrQA= github.com/olekukonko/tablewriter v0.0.0-20170122224234-a0225b3f23b5/go.mod h1:vsDQFd/mU46D+Z4whnwzcISnGGzXWMclvtLoiIKAKIo= @@ -271,6 +273,7 @@ github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf github.com/sagikazarmark/crypt v0.6.0 h1:REOEXCs/NFY/1jOCEouMuT4zEniE5YoXbvpC5X/TLF8= github.com/sagikazarmark/crypt v0.6.0/go.mod h1:U8+INwJo3nBv1m6A/8OBXAq7Jnpspk5AxSgDyEQcea8= github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E= +github.com/shurcooL/sanitized_anchor_name v1.0.0 h1:PdmoCO6wvbs+7yrJyMORt4/BmY5IYyJwS/kOiWx8mHo= github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= github.com/sony/gobreaker v0.4.1/go.mod h1:ZKptC7FHNvhBz7dN2LGjPVBz2sZJmc0/PkyDJOjmxWY= github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72 h1:qLC7fQah7D6K1B0ujays3HV9gkFtllcxhzImRR7ArPQ= @@ -281,12 +284,12 @@ github.com/spf13/pflag v1.0.1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnIn github.com/streadway/amqp v0.0.0-20190404075320-75d898a42a94/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/amqp v0.0.0-20190827072141-edfb9018d271/go.mod h1:AZpEONHx3DKn8O/DFsRAY58/XVQiIPMTMB1SddzLXVw= github.com/streadway/handy v0.0.0-20190108123426-d5acb3125c2a/go.mod h1:qNTQ5P5JnDBl6z3cMAg/SywNDC5ABu5ApDIw6lUbRmI= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/subosito/gotenv v1.3.0/go.mod h1:YzJjq/33h7nrwdY+iHMhEOEEbW0ovIz0tB6t6PwAXzs= github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM= github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0= +github.com/urfave/cli/v2 v2.3.0 h1:qph92Y649prgesehzOrQjdWyxFOp/QVM+6imKHad91M= github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= gitlab.com/f5/nginx/agent/product/nginx-agent/sdk/v2 v2.16.7 h1:BP5fSvOYAYE8JM2Bh+mqPk4x+0tzgA2T8dofOuuwEtY= diff --git a/sdk/proto/nginx.pb.go b/sdk/proto/nginx.pb.go index 1f61fa231..a8ab6ef23 100644 --- a/sdk/proto/nginx.pb.go +++ b/sdk/proto/nginx.pb.go @@ -60,6 +60,7 @@ func (NginxConfigAction) EnumDescriptor() ([]byte, []int) { return fileDescriptor_917f1a70b1fd7255, []int{0} } +// SSL type enum type NginxSslMetaData_NginxSslType int32 const ( @@ -278,24 +279,49 @@ func (m *PathInfo) GetConf() string { return "" } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. type NginxDetails struct { - NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` - ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` - ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` - ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` - StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` - BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` - LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` - RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` - Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` - Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` - StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` - ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 + NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` + // Version of NGINX + // example: 1.23.2 + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf + ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` + // Process ID + // example: 8 + ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` + // Process Path + // example: /usr/local/nginx/sbin/nginx + ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` + // Start Time + // example: 1670429190000 + StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` + // Was NGINX built from source + // example: false + BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` + // List of loadable modules + // example: [] + LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` + // List of runtime modules + // example: [ "http_stub_status_module" ] + RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` + // NGINX plus metadata + Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` + // SSL metadata + Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` + // Status URL + // example: http://localhost:8080/api + StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] + ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxDetails) Reset() { *m = NginxDetails{} } @@ -422,8 +448,13 @@ func (m *NginxDetails) GetConfigureArgs() []string { return nil } +// swagger:model NginxPlusMetaData type NginxPlusMetaData struct { - Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // Is NGINX instance a plus instance + // example: true + Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // NGINX plus release + // example: R27 Release string `protobuf:"bytes,2,opt,name=release,proto3" json:"release"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` @@ -477,12 +508,17 @@ func (m *NginxPlusMetaData) GetRelease() string { return "" } +// swagger:model NginxSslMetaData type NginxSslMetaData struct { - SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` - Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // SSL type + // example: 0 + SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` + // SSL details + // example: null + Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxSslMetaData) Reset() { *m = NginxSslMetaData{} } diff --git a/sdk/proto/nginx.proto b/sdk/proto/nginx.proto index f61c33ce6..305809568 100644 --- a/sdk/proto/nginx.proto +++ b/sdk/proto/nginx.proto @@ -21,34 +21,70 @@ message PathInfo { string conf = 2 [(gogoproto.jsontag) = "conf" ]; } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. message NginxDetails { + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 string nginx_id = 1 [(gogoproto.jsontag) = "nginx_id" ]; + // Version of NGINX + // example: 1.23.2 string version = 2 [(gogoproto.jsontag) = "version" ]; + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf string conf_path = 3 [(gogoproto.jsontag) = "conf_path" ]; + // Process ID + // example: 8 string process_id = 4 [(gogoproto.jsontag) = "process_id" ]; + // Process Path + // example: /usr/local/nginx/sbin/nginx string process_path = 5 [(gogoproto.jsontag) = "process_path" ]; + // Start Time + // example: 1670429190000 int64 start_time = 6 [(gogoproto.jsontag) = "start_time" ]; + // Was NGINX built from source + // example: false bool built_from_source = 7 [(gogoproto.jsontag) = "built_from_source" ]; + // List of loadable modules + // example: [] repeated string loadable_modules = 8 [(gogoproto.jsontag) = "loadable_modules" ]; + // List of runtime modules + // example: [ "http_stub_status_module" ] repeated string runtime_modules = 9 [(gogoproto.jsontag) = "runtime_modules" ]; + // NGINX plus metadata NginxPlusMetaData plus = 10 [(gogoproto.jsontag) = "plus" ]; + // SSL metadata NginxSslMetaData ssl = 11 [(gogoproto.jsontag) = "ssl" ]; + // Status URL + // example: http://localhost:8080/api string status_url = 12 [(gogoproto.jsontag) = "status_url" ]; + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] repeated string configure_args = 13 [(gogoproto.jsontag) = "configure_args" ]; } +// swagger:model NginxPlusMetaData message NginxPlusMetaData { + // Is NGINX instance a plus instance + // example: true bool enabled = 1 [(gogoproto.jsontag) = "enabled" ]; + // NGINX plus release + // example: R27 string release = 2 [(gogoproto.jsontag) = "release" ]; } +// swagger:model NginxSslMetaData message NginxSslMetaData { + // SSL type enum enum NginxSslType { BUILT = 0; RUN = 1; } - NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL type + // example: 0 + NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL details + // example: null repeated string details = 2 [(gogoproto.jsontag) = "details" ]; } diff --git a/src/plugins/agent_api.go b/src/plugins/agent_api.go index 6a871c37c..a3a626ddd 100644 --- a/src/plugins/agent_api.go +++ b/src/plugins/agent_api.go @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +// Host: localhost:8081 +// swagger:meta package plugins import ( @@ -26,9 +28,14 @@ import ( prometheus_metrics "github.com/nginx/agent/v2/src/extensions/prometheus-metrics" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" log "github.com/sirupsen/logrus" ) +// swagger:response MetricsResponse +// in: body +type _ string + const ( okStatus = "OK" pendingStatus = "PENDING" @@ -61,31 +68,61 @@ type NginxHandler struct { configResponseStatuses map[string]*proto.NginxConfigStatus } +// swagger:parameters apply-nginx-config +type ParameterRequest struct { + // in: formData + // swagger:file + File interface{} `json:"file"` +} + type AgentAPIConfigApplyRequest struct { correlationId string config *proto.NginxConfig } +// swagger:model NginxInstanceResponse type NginxInstanceResponse struct { + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 NginxId string `json:"nginx_id"` + // Message + // example: config applied successfully Message string `json:"message"` - Status string `json:"status"` + // Status + // example: OK + Status string `json:"status"` } +// swagger:model AgentAPIConfigApplyResponse type AgentAPIConfigApplyResponse struct { - CorrelationId string `json:"correlation_id"` + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b + CorrelationId string `json:"correlation_id"` + // NGINX Instances NginxInstances []NginxInstanceResponse `json:"nginx_instances"` } +// swagger:model AgentAPICommonResponse type AgentAPICommonResponse struct { + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b CorrelationId string `json:"correlation_id"` - Message string `json:"message"` + // Message + // example: No NGINX instances found + Message string `json:"message"` } +// swagger:model AgentAPIConfigApplyStatusResponse type AgentAPIConfigApplyStatusResponse struct { + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b CorrelationId string `json:"correlation_id"` - Message string `json:"message"` - Status string `json:"status"` + // Message + // example: pending config apply + Message string `json:"message"` + // Status + // example: PENDING + Status string `json:"status"` } const ( @@ -168,16 +205,14 @@ func (a *AgentAPI) createHttpServer() { } mux := http.NewServeMux() - registerer := prometheus.DefaultRegisterer - gatherer := prometheus.DefaultGatherer - registerer.MustRegister(a.exporter) - mux.Handle("/metrics/", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})) + mux.Handle("/metrics/", a.getPrometheusHandler()) mux.Handle("/nginx/", a.nginxHandler) + handler := cors.New(cors.Options{AllowedMethods: []string{"OPTIONS", "GET", "PUT"}}).Handler(mux) a.server = http.Server{ Addr: fmt.Sprintf(":%d", a.config.AgentAPI.Port), - Handler: mux, + Handler: handler, } if a.config.AgentAPI.Cert != "" && a.config.AgentAPI.Key != "" && a.config.AgentAPI.Port != 0 { @@ -195,8 +230,29 @@ func (a *AgentAPI) createHttpServer() { } } +// swagger:route GET /metrics/ nginx-agent get-prometheus-metrics +// +// # Get Prometheus Metrics +// +// # Returns prometheus metrics +// +// Produces: +// - text/plain +// +// responses: +// +// 200: MetricsResponse +func (a *AgentAPI) getPrometheusHandler() http.Handler { + registerer := prometheus.DefaultRegisterer + gatherer := prometheus.DefaultGatherer + + registerer.MustRegister(a.exporter) + return promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{}) +} + func (h *NginxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set(contentTypeHeader, jsonMimeType) + switch { case instancesRegex.MatchString(r.URL.Path): if r.Method != http.MethodGet { @@ -237,6 +293,16 @@ func (h *NginxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +// swagger:route GET /nginx/ nginx-agent get-nginx-instances +// +// # Get NGINX Instances +// +// # Returns a list of NGINX instances +// +// responses: +// +// 200: []NginxDetails +// 500 func (h *NginxHandler) sendInstanceDetailsPayload(w http.ResponseWriter, r *http.Request) error { nginxDetails := h.getNginxDetails() w.WriteHeader(http.StatusOK) @@ -254,6 +320,23 @@ func (h *NginxHandler) sendInstanceDetailsPayload(w http.ResponseWriter, r *http return writeObjectToResponseBody(w, nginxDetails) } +// swagger:route PUT /nginx/config/ nginx-agent apply-nginx-config +// +// # Apply NGINX configuration to all NGINX instances +// +// # Returns a config apply status +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// +// responses: +// +// 200: AgentAPIConfigApplyResponse +// 400: AgentAPICommonResponse +// 408: AgentAPIConfigApplyStatusResponse +// 500: AgentAPICommonResponse func (h *NginxHandler) updateConfig(w http.ResponseWriter, r *http.Request) error { correlationId := uuid.New().String() @@ -316,7 +399,7 @@ func (h *NginxHandler) updateConfig(w http.ResponseWriter, r *http.Request) erro w.WriteHeader(http.StatusRequestTimeout) agentAPIConfigApplyStatusResponse := AgentAPIConfigApplyStatusResponse{ CorrelationId: correlationId, - Message: "Pending config apply", + Message: "pending config apply", Status: pendingStatus, } @@ -410,6 +493,25 @@ func (h *NginxHandler) applyNginxConfig(nginxDetail *proto.NginxDetails, buf *by return nil } +// swagger:route GET /nginx/config/status nginx-agent get-nginx-config-status +// +// # Get status NGINX config apply +// +// # Returns status NGINX config apply +// +// Parameters: +// + name: correlation_id +// in: query +// description: Correlation ID of a NGINX config apply request +// required: true +// type: string +// +// responses: +// +// 200: AgentAPIConfigApplyResponse +// 400: AgentAPIConfigApplyStatusResponse +// 404: AgentAPIConfigApplyStatusResponse +// 500 func (h *NginxHandler) getConfigStatus(w http.ResponseWriter, r *http.Request) error { correlationId := r.URL.Query().Get("correlation_id") diff --git a/src/plugins/agent_api_test.go b/src/plugins/agent_api_test.go index 877643120..4a74a673e 100644 --- a/src/plugins/agent_api_test.go +++ b/src/plugins/agent_api_test.go @@ -175,7 +175,7 @@ func TestNginxHandler_updateConfig(t *testing.T) { response: nil, nginxInstancesPresent: true, expectedStatusCode: 408, - expectedMessage: "Pending config apply", + expectedMessage: "pending config apply", expectedStatus: "PENDING", }, { diff --git a/test/performance/go.mod b/test/performance/go.mod index 4b8e4f360..4042ab27c 100644 --- a/test/performance/go.mod +++ b/test/performance/go.mod @@ -52,6 +52,7 @@ require ( github.com/prometheus/client_model v0.2.0 // indirect github.com/prometheus/common v0.37.0 // indirect github.com/prometheus/procfs v0.8.0 // indirect + github.com/rs/cors v1.8.2 // indirect github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/shirou/gopsutil/v3 v3.22.7 // indirect github.com/spf13/afero v1.9.2 // indirect diff --git a/test/performance/go.sum b/test/performance/go.sum index e04f9a4a1..50581e3f9 100644 --- a/test/performance/go.sum +++ b/test/performance/go.sum @@ -300,6 +300,8 @@ github.com/prometheus/procfs v0.8.0/go.mod h1:z7EfXMXOkbkqb9IINtpCn86r/to3BnA0ua github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k= +github.com/rs/cors v1.8.2 h1:KCooALfAYGs415Cwu5ABvv9n9509fSiG5SQJn/AQo4U= +github.com/rs/cors v1.8.2/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sanity-io/litter v1.5.5 h1:iE+sBxPBzoK6uaEP5Lt3fHNgpKcHXc/A2HGETy0uJQo= github.com/sanity-io/litter v1.5.5/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U= diff --git a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go index 1f61fa231..a8ab6ef23 100644 --- a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go +++ b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go @@ -60,6 +60,7 @@ func (NginxConfigAction) EnumDescriptor() ([]byte, []int) { return fileDescriptor_917f1a70b1fd7255, []int{0} } +// SSL type enum type NginxSslMetaData_NginxSslType int32 const ( @@ -278,24 +279,49 @@ func (m *PathInfo) GetConf() string { return "" } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. type NginxDetails struct { - NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` - ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` - ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` - ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` - StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` - BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` - LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` - RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` - Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` - Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` - StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` - ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 + NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` + // Version of NGINX + // example: 1.23.2 + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf + ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` + // Process ID + // example: 8 + ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` + // Process Path + // example: /usr/local/nginx/sbin/nginx + ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` + // Start Time + // example: 1670429190000 + StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` + // Was NGINX built from source + // example: false + BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` + // List of loadable modules + // example: [] + LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` + // List of runtime modules + // example: [ "http_stub_status_module" ] + RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` + // NGINX plus metadata + Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` + // SSL metadata + Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` + // Status URL + // example: http://localhost:8080/api + StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] + ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxDetails) Reset() { *m = NginxDetails{} } @@ -422,8 +448,13 @@ func (m *NginxDetails) GetConfigureArgs() []string { return nil } +// swagger:model NginxPlusMetaData type NginxPlusMetaData struct { - Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // Is NGINX instance a plus instance + // example: true + Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // NGINX plus release + // example: R27 Release string `protobuf:"bytes,2,opt,name=release,proto3" json:"release"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` @@ -477,12 +508,17 @@ func (m *NginxPlusMetaData) GetRelease() string { return "" } +// swagger:model NginxSslMetaData type NginxSslMetaData struct { - SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` - Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // SSL type + // example: 0 + SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` + // SSL details + // example: null + Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxSslMetaData) Reset() { *m = NginxSslMetaData{} } diff --git a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto index f61c33ce6..305809568 100644 --- a/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto +++ b/test/performance/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto @@ -21,34 +21,70 @@ message PathInfo { string conf = 2 [(gogoproto.jsontag) = "conf" ]; } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. message NginxDetails { + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 string nginx_id = 1 [(gogoproto.jsontag) = "nginx_id" ]; + // Version of NGINX + // example: 1.23.2 string version = 2 [(gogoproto.jsontag) = "version" ]; + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf string conf_path = 3 [(gogoproto.jsontag) = "conf_path" ]; + // Process ID + // example: 8 string process_id = 4 [(gogoproto.jsontag) = "process_id" ]; + // Process Path + // example: /usr/local/nginx/sbin/nginx string process_path = 5 [(gogoproto.jsontag) = "process_path" ]; + // Start Time + // example: 1670429190000 int64 start_time = 6 [(gogoproto.jsontag) = "start_time" ]; + // Was NGINX built from source + // example: false bool built_from_source = 7 [(gogoproto.jsontag) = "built_from_source" ]; + // List of loadable modules + // example: [] repeated string loadable_modules = 8 [(gogoproto.jsontag) = "loadable_modules" ]; + // List of runtime modules + // example: [ "http_stub_status_module" ] repeated string runtime_modules = 9 [(gogoproto.jsontag) = "runtime_modules" ]; + // NGINX plus metadata NginxPlusMetaData plus = 10 [(gogoproto.jsontag) = "plus" ]; + // SSL metadata NginxSslMetaData ssl = 11 [(gogoproto.jsontag) = "ssl" ]; + // Status URL + // example: http://localhost:8080/api string status_url = 12 [(gogoproto.jsontag) = "status_url" ]; + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] repeated string configure_args = 13 [(gogoproto.jsontag) = "configure_args" ]; } +// swagger:model NginxPlusMetaData message NginxPlusMetaData { + // Is NGINX instance a plus instance + // example: true bool enabled = 1 [(gogoproto.jsontag) = "enabled" ]; + // NGINX plus release + // example: R27 string release = 2 [(gogoproto.jsontag) = "release" ]; } +// swagger:model NginxSslMetaData message NginxSslMetaData { + // SSL type enum enum NginxSslType { BUILT = 0; RUN = 1; } - NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL type + // example: 0 + NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL details + // example: null repeated string details = 2 [(gogoproto.jsontag) = "details" ]; } diff --git a/test/performance/vendor/github.com/nginx/agent/v2/src/plugins/agent_api.go b/test/performance/vendor/github.com/nginx/agent/v2/src/plugins/agent_api.go index 6a871c37c..a3a626ddd 100644 --- a/test/performance/vendor/github.com/nginx/agent/v2/src/plugins/agent_api.go +++ b/test/performance/vendor/github.com/nginx/agent/v2/src/plugins/agent_api.go @@ -5,6 +5,8 @@ * LICENSE file in the root directory of this source tree. */ +// Host: localhost:8081 +// swagger:meta package plugins import ( @@ -26,9 +28,14 @@ import ( prometheus_metrics "github.com/nginx/agent/v2/src/extensions/prometheus-metrics" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/client_golang/prometheus/promhttp" + "github.com/rs/cors" log "github.com/sirupsen/logrus" ) +// swagger:response MetricsResponse +// in: body +type _ string + const ( okStatus = "OK" pendingStatus = "PENDING" @@ -61,31 +68,61 @@ type NginxHandler struct { configResponseStatuses map[string]*proto.NginxConfigStatus } +// swagger:parameters apply-nginx-config +type ParameterRequest struct { + // in: formData + // swagger:file + File interface{} `json:"file"` +} + type AgentAPIConfigApplyRequest struct { correlationId string config *proto.NginxConfig } +// swagger:model NginxInstanceResponse type NginxInstanceResponse struct { + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 NginxId string `json:"nginx_id"` + // Message + // example: config applied successfully Message string `json:"message"` - Status string `json:"status"` + // Status + // example: OK + Status string `json:"status"` } +// swagger:model AgentAPIConfigApplyResponse type AgentAPIConfigApplyResponse struct { - CorrelationId string `json:"correlation_id"` + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b + CorrelationId string `json:"correlation_id"` + // NGINX Instances NginxInstances []NginxInstanceResponse `json:"nginx_instances"` } +// swagger:model AgentAPICommonResponse type AgentAPICommonResponse struct { + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b CorrelationId string `json:"correlation_id"` - Message string `json:"message"` + // Message + // example: No NGINX instances found + Message string `json:"message"` } +// swagger:model AgentAPIConfigApplyStatusResponse type AgentAPIConfigApplyStatusResponse struct { + // Correlation ID + // example: 6204037c-30e6-408b-8aaa-dd8219860b4b CorrelationId string `json:"correlation_id"` - Message string `json:"message"` - Status string `json:"status"` + // Message + // example: pending config apply + Message string `json:"message"` + // Status + // example: PENDING + Status string `json:"status"` } const ( @@ -168,16 +205,14 @@ func (a *AgentAPI) createHttpServer() { } mux := http.NewServeMux() - registerer := prometheus.DefaultRegisterer - gatherer := prometheus.DefaultGatherer - registerer.MustRegister(a.exporter) - mux.Handle("/metrics/", promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{})) + mux.Handle("/metrics/", a.getPrometheusHandler()) mux.Handle("/nginx/", a.nginxHandler) + handler := cors.New(cors.Options{AllowedMethods: []string{"OPTIONS", "GET", "PUT"}}).Handler(mux) a.server = http.Server{ Addr: fmt.Sprintf(":%d", a.config.AgentAPI.Port), - Handler: mux, + Handler: handler, } if a.config.AgentAPI.Cert != "" && a.config.AgentAPI.Key != "" && a.config.AgentAPI.Port != 0 { @@ -195,8 +230,29 @@ func (a *AgentAPI) createHttpServer() { } } +// swagger:route GET /metrics/ nginx-agent get-prometheus-metrics +// +// # Get Prometheus Metrics +// +// # Returns prometheus metrics +// +// Produces: +// - text/plain +// +// responses: +// +// 200: MetricsResponse +func (a *AgentAPI) getPrometheusHandler() http.Handler { + registerer := prometheus.DefaultRegisterer + gatherer := prometheus.DefaultGatherer + + registerer.MustRegister(a.exporter) + return promhttp.HandlerFor(gatherer, promhttp.HandlerOpts{}) +} + func (h *NginxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set(contentTypeHeader, jsonMimeType) + switch { case instancesRegex.MatchString(r.URL.Path): if r.Method != http.MethodGet { @@ -237,6 +293,16 @@ func (h *NginxHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +// swagger:route GET /nginx/ nginx-agent get-nginx-instances +// +// # Get NGINX Instances +// +// # Returns a list of NGINX instances +// +// responses: +// +// 200: []NginxDetails +// 500 func (h *NginxHandler) sendInstanceDetailsPayload(w http.ResponseWriter, r *http.Request) error { nginxDetails := h.getNginxDetails() w.WriteHeader(http.StatusOK) @@ -254,6 +320,23 @@ func (h *NginxHandler) sendInstanceDetailsPayload(w http.ResponseWriter, r *http return writeObjectToResponseBody(w, nginxDetails) } +// swagger:route PUT /nginx/config/ nginx-agent apply-nginx-config +// +// # Apply NGINX configuration to all NGINX instances +// +// # Returns a config apply status +// Consumes: +// - multipart/form-data +// +// Produces: +// - application/json +// +// responses: +// +// 200: AgentAPIConfigApplyResponse +// 400: AgentAPICommonResponse +// 408: AgentAPIConfigApplyStatusResponse +// 500: AgentAPICommonResponse func (h *NginxHandler) updateConfig(w http.ResponseWriter, r *http.Request) error { correlationId := uuid.New().String() @@ -316,7 +399,7 @@ func (h *NginxHandler) updateConfig(w http.ResponseWriter, r *http.Request) erro w.WriteHeader(http.StatusRequestTimeout) agentAPIConfigApplyStatusResponse := AgentAPIConfigApplyStatusResponse{ CorrelationId: correlationId, - Message: "Pending config apply", + Message: "pending config apply", Status: pendingStatus, } @@ -410,6 +493,25 @@ func (h *NginxHandler) applyNginxConfig(nginxDetail *proto.NginxDetails, buf *by return nil } +// swagger:route GET /nginx/config/status nginx-agent get-nginx-config-status +// +// # Get status NGINX config apply +// +// # Returns status NGINX config apply +// +// Parameters: +// + name: correlation_id +// in: query +// description: Correlation ID of a NGINX config apply request +// required: true +// type: string +// +// responses: +// +// 200: AgentAPIConfigApplyResponse +// 400: AgentAPIConfigApplyStatusResponse +// 404: AgentAPIConfigApplyStatusResponse +// 500 func (h *NginxHandler) getConfigStatus(w http.ResponseWriter, r *http.Request) error { correlationId := r.URL.Query().Get("correlation_id") diff --git a/test/performance/vendor/github.com/rs/cors/LICENSE b/test/performance/vendor/github.com/rs/cors/LICENSE new file mode 100644 index 000000000..d8e2df5a4 --- /dev/null +++ b/test/performance/vendor/github.com/rs/cors/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Olivier Poitrey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/test/performance/vendor/github.com/rs/cors/README.md b/test/performance/vendor/github.com/rs/cors/README.md new file mode 100644 index 000000000..0ad3e94e1 --- /dev/null +++ b/test/performance/vendor/github.com/rs/cors/README.md @@ -0,0 +1,116 @@ +# Go CORS handler [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/cors) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/cors/master/LICENSE) [![build](https://img.shields.io/travis/rs/cors.svg?style=flat)](https://travis-ci.org/rs/cors) [![Coverage](http://gocover.io/_badge/github.com/rs/cors)](http://gocover.io/github.com/rs/cors) + +CORS is a `net/http` handler implementing [Cross Origin Resource Sharing W3 specification](http://www.w3.org/TR/cors/) in Golang. + +## Getting Started + +After installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`. + +```go +package main + +import ( + "net/http" + + "github.com/rs/cors" +) + +func main() { + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte("{\"hello\": \"world\"}")) + }) + + // cors.Default() setup the middleware with default options being + // all origins accepted with simple methods (GET, POST). See + // documentation below for more options. + handler := cors.Default().Handler(mux) + http.ListenAndServe(":8080", handler) +} +``` + +Install `cors`: + + go get github.com/rs/cors + +Then run your server: + + go run server.go + +The server now runs on `localhost:8080`: + + $ curl -D - -H 'Origin: http://foo.com' http://localhost:8080/ + HTTP/1.1 200 OK + Access-Control-Allow-Origin: foo.com + Content-Type: application/json + Date: Sat, 25 Oct 2014 03:43:57 GMT + Content-Length: 18 + + {"hello": "world"} + +### Allow * With Credentials Security Protection + +This library has been modified to avoid a well known security issue when configured with `AllowedOrigins` to `*` and `AllowCredentials` to `true`. Such setup used to make the library reflects the request `Origin` header value, working around a security protection embedded into the standard that makes clients to refuse such configuration. This behavior has been removed with [#55](https://github.com/rs/cors/issues/55) and [#57](https://github.com/rs/cors/issues/57). + +If you depend on this behavior and understand the implications, you can restore it using the `AllowOriginFunc` with `func(origin string) {return true}`. + +Please refer to [#55](https://github.com/rs/cors/issues/55) for more information about the security implications. + +### More Examples + +* `net/http`: [examples/nethttp/server.go](https://github.com/rs/cors/blob/master/examples/nethttp/server.go) +* [Goji](https://goji.io): [examples/goji/server.go](https://github.com/rs/cors/blob/master/examples/goji/server.go) +* [Martini](http://martini.codegangsta.io): [examples/martini/server.go](https://github.com/rs/cors/blob/master/examples/martini/server.go) +* [Negroni](https://github.com/codegangsta/negroni): [examples/negroni/server.go](https://github.com/rs/cors/blob/master/examples/negroni/server.go) +* [Alice](https://github.com/justinas/alice): [examples/alice/server.go](https://github.com/rs/cors/blob/master/examples/alice/server.go) +* [HttpRouter](https://github.com/julienschmidt/httprouter): [examples/httprouter/server.go](https://github.com/rs/cors/blob/master/examples/httprouter/server.go) +* [Gorilla](http://www.gorillatoolkit.org/pkg/mux): [examples/gorilla/server.go](https://github.com/rs/cors/blob/master/examples/gorilla/server.go) +* [Buffalo](https://gobuffalo.io): [examples/buffalo/server.go](https://github.com/rs/cors/blob/master/examples/buffalo/server.go) +* [Gin](https://gin-gonic.github.io/gin): [examples/gin/server.go](https://github.com/rs/cors/blob/master/examples/gin/server.go) +* [Chi](https://github.com/go-chi/chi): [examples/chi/server.go](https://github.com/rs/cors/blob/master/examples/chi/server.go) + +## Parameters + +Parameters are passed to the middleware thru the `cors.New` method as follow: + +```go +c := cors.New(cors.Options{ + AllowedOrigins: []string{"http://foo.com", "http://foo.com:8080"}, + AllowCredentials: true, + // Enable Debugging for testing, consider disabling in production + Debug: true, +}) + +// Insert the middleware +handler = c.Handler(handler) +``` + +* **AllowedOrigins** `[]string`: A list of origins a cross-domain request can be executed from. If the special `*` value is present in the list, all origins will be allowed. An origin may contain a wildcard (`*`) to replace 0 or more characters (i.e.: `http://*.domain.com`). Usage of wildcards implies a small performance penality. Only one wildcard can be used per origin. The default value is `*`. +* **AllowOriginFunc** `func (origin string) bool`: A custom function to validate the origin. It takes the origin as an argument and returns true if allowed, or false otherwise. If this option is set, the content of `AllowedOrigins` is ignored. +* **AllowOriginRequestFunc** `func (r *http.Request, origin string) bool`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` and `AllowOriginFunc` is ignored +* **AllowedMethods** `[]string`: A list of methods the client is allowed to use with cross-domain requests. Default value is simple methods (`GET` and `POST`). +* **AllowedHeaders** `[]string`: A list of non simple headers the client is allowed to use with cross-domain requests. +* **ExposedHeaders** `[]string`: Indicates which headers are safe to expose to the API of a CORS API specification +* **AllowCredentials** `bool`: Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates. The default is `false`. +* **MaxAge** `int`: Indicates how long (in seconds) the results of a preflight request can be cached. The default is `0` which stands for no max age. +* **OptionsPassthrough** `bool`: Instructs preflight to let other potential next handlers to process the `OPTIONS` method. Turn this on if your application handles `OPTIONS`. +* **OptionsSuccessStatus** `int`: Provides a status code to use for successful OPTIONS requests. Default value is `http.StatusNoContent` (`204`). +* **Debug** `bool`: Debugging flag adds additional output to debug server side CORS issues. + +See [API documentation](http://godoc.org/github.com/rs/cors) for more info. + +## Benchmarks + + BenchmarkWithout 20000000 64.6 ns/op 8 B/op 1 allocs/op + BenchmarkDefault 3000000 469 ns/op 114 B/op 2 allocs/op + BenchmarkAllowedOrigin 3000000 608 ns/op 114 B/op 2 allocs/op + BenchmarkPreflight 20000000 73.2 ns/op 0 B/op 0 allocs/op + BenchmarkPreflightHeader 20000000 73.6 ns/op 0 B/op 0 allocs/op + BenchmarkParseHeaderList 2000000 847 ns/op 184 B/op 6 allocs/op + BenchmarkParse…Single 5000000 290 ns/op 32 B/op 3 allocs/op + BenchmarkParse…Normalized 2000000 776 ns/op 160 B/op 6 allocs/op + +## Licenses + +All source code is licensed under the [MIT License](https://raw.github.com/rs/cors/master/LICENSE). diff --git a/test/performance/vendor/github.com/rs/cors/cors.go b/test/performance/vendor/github.com/rs/cors/cors.go new file mode 100644 index 000000000..2ce24e3f3 --- /dev/null +++ b/test/performance/vendor/github.com/rs/cors/cors.go @@ -0,0 +1,446 @@ +/* +Package cors is net/http handler to handle CORS related requests +as defined by http://www.w3.org/TR/cors/ + +You can configure it by passing an option struct to cors.New: + + c := cors.New(cors.Options{ + AllowedOrigins: []string{"foo.com"}, + AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete}, + AllowCredentials: true, + }) + +Then insert the handler in the chain: + + handler = c.Handler(handler) + +See Options documentation for more options. + +The resulting handler is a standard net/http handler. +*/ +package cors + +import ( + "log" + "net/http" + "os" + "strconv" + "strings" +) + +// Options is a configuration container to setup the CORS middleware. +type Options struct { + // AllowedOrigins is a list of origins a cross-domain request can be executed from. + // If the special "*" value is present in the list, all origins will be allowed. + // An origin may contain a wildcard (*) to replace 0 or more characters + // (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty. + // Only one wildcard can be used per origin. + // Default value is ["*"] + AllowedOrigins []string + // AllowOriginFunc is a custom function to validate the origin. It take the origin + // as argument and returns true if allowed or false otherwise. If this option is + // set, the content of AllowedOrigins is ignored. + AllowOriginFunc func(origin string) bool + // AllowOriginRequestFunc is a custom function to validate the origin. It takes the HTTP Request object and the origin as + // argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` + // and `AllowOriginFunc` is ignored. + AllowOriginRequestFunc func(r *http.Request, origin string) bool + // AllowedMethods is a list of methods the client is allowed to use with + // cross-domain requests. Default value is simple methods (HEAD, GET and POST). + AllowedMethods []string + // AllowedHeaders is list of non simple headers the client is allowed to use with + // cross-domain requests. + // If the special "*" value is present in the list, all headers will be allowed. + // Default value is [] but "Origin" is always appended to the list. + AllowedHeaders []string + // ExposedHeaders indicates which headers are safe to expose to the API of a CORS + // API specification + ExposedHeaders []string + // MaxAge indicates how long (in seconds) the results of a preflight request + // can be cached + MaxAge int + // AllowCredentials indicates whether the request can include user credentials like + // cookies, HTTP authentication or client side SSL certificates. + AllowCredentials bool + // OptionsPassthrough instructs preflight to let other potential next handlers to + // process the OPTIONS method. Turn this on if your application handles OPTIONS. + OptionsPassthrough bool + // Provides a status code to use for successful OPTIONS requests. + // Default value is http.StatusNoContent (204). + OptionsSuccessStatus int + // Debugging flag adds additional output to debug server side CORS issues + Debug bool +} + +// Logger generic interface for logger +type Logger interface { + Printf(string, ...interface{}) +} + +// Cors http handler +type Cors struct { + // Debug logger + Log Logger + // Normalized list of plain allowed origins + allowedOrigins []string + // List of allowed origins containing wildcards + allowedWOrigins []wildcard + // Optional origin validator function + allowOriginFunc func(origin string) bool + // Optional origin validator (with request) function + allowOriginRequestFunc func(r *http.Request, origin string) bool + // Normalized list of allowed headers + allowedHeaders []string + // Normalized list of allowed methods + allowedMethods []string + // Normalized list of exposed headers + exposedHeaders []string + maxAge int + // Set to true when allowed origins contains a "*" + allowedOriginsAll bool + // Set to true when allowed headers contains a "*" + allowedHeadersAll bool + // Status code to use for successful OPTIONS requests + optionsSuccessStatus int + allowCredentials bool + optionPassthrough bool +} + +// New creates a new Cors handler with the provided options. +func New(options Options) *Cors { + c := &Cors{ + exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey), + allowOriginFunc: options.AllowOriginFunc, + allowOriginRequestFunc: options.AllowOriginRequestFunc, + allowCredentials: options.AllowCredentials, + maxAge: options.MaxAge, + optionPassthrough: options.OptionsPassthrough, + } + if options.Debug && c.Log == nil { + c.Log = log.New(os.Stdout, "[cors] ", log.LstdFlags) + } + + // Normalize options + // Note: for origins and methods matching, the spec requires a case-sensitive matching. + // As it may error prone, we chose to ignore the spec here. + + // Allowed Origins + if len(options.AllowedOrigins) == 0 { + if options.AllowOriginFunc == nil && options.AllowOriginRequestFunc == nil { + // Default is all origins + c.allowedOriginsAll = true + } + } else { + c.allowedOrigins = []string{} + c.allowedWOrigins = []wildcard{} + for _, origin := range options.AllowedOrigins { + // Normalize + origin = strings.ToLower(origin) + if origin == "*" { + // If "*" is present in the list, turn the whole list into a match all + c.allowedOriginsAll = true + c.allowedOrigins = nil + c.allowedWOrigins = nil + break + } else if i := strings.IndexByte(origin, '*'); i >= 0 { + // Split the origin in two: start and end string without the * + w := wildcard{origin[0:i], origin[i+1:]} + c.allowedWOrigins = append(c.allowedWOrigins, w) + } else { + c.allowedOrigins = append(c.allowedOrigins, origin) + } + } + } + + // Allowed Headers + if len(options.AllowedHeaders) == 0 { + // Use sensible defaults + c.allowedHeaders = []string{"Origin", "Accept", "Content-Type", "X-Requested-With"} + } else { + // Origin is always appended as some browsers will always request for this header at preflight + c.allowedHeaders = convert(append(options.AllowedHeaders, "Origin"), http.CanonicalHeaderKey) + for _, h := range options.AllowedHeaders { + if h == "*" { + c.allowedHeadersAll = true + c.allowedHeaders = nil + break + } + } + } + + // Allowed Methods + if len(options.AllowedMethods) == 0 { + // Default is spec's "simple" methods + c.allowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodHead} + } else { + c.allowedMethods = convert(options.AllowedMethods, strings.ToUpper) + } + + // Options Success Status Code + if options.OptionsSuccessStatus == 0 { + c.optionsSuccessStatus = http.StatusNoContent + } else { + c.optionsSuccessStatus = options.OptionsSuccessStatus + } + + return c +} + +// Default creates a new Cors handler with default options. +func Default() *Cors { + return New(Options{}) +} + +// AllowAll create a new Cors handler with permissive configuration allowing all +// origins with all standard methods with any header and credentials. +func AllowAll() *Cors { + return New(Options{ + AllowedOrigins: []string{"*"}, + AllowedMethods: []string{ + http.MethodHead, + http.MethodGet, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete, + }, + AllowedHeaders: []string{"*"}, + AllowCredentials: false, + }) +} + +// Handler apply the CORS specification on the request, and add relevant CORS headers +// as necessary. +func (c *Cors) Handler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("Handler: Preflight request") + c.handlePreflight(w, r) + // Preflight requests are standalone and should stop the chain as some other + // middleware may not handle OPTIONS requests correctly. One typical example + // is authentication middleware ; OPTIONS requests won't carry authentication + // headers (see #1) + if c.optionPassthrough { + h.ServeHTTP(w, r) + } else { + w.WriteHeader(c.optionsSuccessStatus) + } + } else { + c.logf("Handler: Actual request") + c.handleActualRequest(w, r) + h.ServeHTTP(w, r) + } + }) +} + +// HandlerFunc provides Martini compatible handler +func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("HandlerFunc: Preflight request") + c.handlePreflight(w, r) + + w.WriteHeader(c.optionsSuccessStatus) + } else { + c.logf("HandlerFunc: Actual request") + c.handleActualRequest(w, r) + } +} + +// Negroni compatible interface +func (c *Cors) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("ServeHTTP: Preflight request") + c.handlePreflight(w, r) + // Preflight requests are standalone and should stop the chain as some other + // middleware may not handle OPTIONS requests correctly. One typical example + // is authentication middleware ; OPTIONS requests won't carry authentication + // headers (see #1) + if c.optionPassthrough { + next(w, r) + } else { + w.WriteHeader(c.optionsSuccessStatus) + } + } else { + c.logf("ServeHTTP: Actual request") + c.handleActualRequest(w, r) + next(w, r) + } +} + +// handlePreflight handles pre-flight CORS requests +func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) { + headers := w.Header() + origin := r.Header.Get("Origin") + + if r.Method != http.MethodOptions { + c.logf(" Preflight aborted: %s!=OPTIONS", r.Method) + return + } + // Always set Vary headers + // see https://github.com/rs/cors/issues/10, + // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001 + headers.Add("Vary", "Origin") + headers.Add("Vary", "Access-Control-Request-Method") + headers.Add("Vary", "Access-Control-Request-Headers") + + if origin == "" { + c.logf(" Preflight aborted: empty origin") + return + } + if !c.isOriginAllowed(r, origin) { + c.logf(" Preflight aborted: origin '%s' not allowed", origin) + return + } + + reqMethod := r.Header.Get("Access-Control-Request-Method") + if !c.isMethodAllowed(reqMethod) { + c.logf(" Preflight aborted: method '%s' not allowed", reqMethod) + return + } + reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers")) + if !c.areHeadersAllowed(reqHeaders) { + c.logf(" Preflight aborted: headers '%v' not allowed", reqHeaders) + return + } + if c.allowedOriginsAll { + headers.Set("Access-Control-Allow-Origin", "*") + } else { + headers.Set("Access-Control-Allow-Origin", origin) + } + // Spec says: Since the list of methods can be unbounded, simply returning the method indicated + // by Access-Control-Request-Method (if supported) can be enough + headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod)) + if len(reqHeaders) > 0 { + + // Spec says: Since the list of headers can be unbounded, simply returning supported headers + // from Access-Control-Request-Headers can be enough + headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", ")) + } + if c.allowCredentials { + headers.Set("Access-Control-Allow-Credentials", "true") + } + if c.maxAge > 0 { + headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge)) + } + c.logf(" Preflight response headers: %v", headers) +} + +// handleActualRequest handles simple cross-origin requests, actual request or redirects +func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) { + headers := w.Header() + origin := r.Header.Get("Origin") + + // Always set Vary, see https://github.com/rs/cors/issues/10 + headers.Add("Vary", "Origin") + if origin == "" { + c.logf(" Actual request no headers added: missing origin") + return + } + if !c.isOriginAllowed(r, origin) { + c.logf(" Actual request no headers added: origin '%s' not allowed", origin) + return + } + + // Note that spec does define a way to specifically disallow a simple method like GET or + // POST. Access-Control-Allow-Methods is only used for pre-flight requests and the + // spec doesn't instruct to check the allowed methods for simple cross-origin requests. + // We think it's a nice feature to be able to have control on those methods though. + if !c.isMethodAllowed(r.Method) { + c.logf(" Actual request no headers added: method '%s' not allowed", r.Method) + + return + } + if c.allowedOriginsAll { + headers.Set("Access-Control-Allow-Origin", "*") + } else { + headers.Set("Access-Control-Allow-Origin", origin) + } + if len(c.exposedHeaders) > 0 { + headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", ")) + } + if c.allowCredentials { + headers.Set("Access-Control-Allow-Credentials", "true") + } + c.logf(" Actual response added headers: %v", headers) +} + +// convenience method. checks if a logger is set. +func (c *Cors) logf(format string, a ...interface{}) { + if c.Log != nil { + c.Log.Printf(format, a...) + } +} + +// check the Origin of a request. No origin at all is also allowed. +func (c *Cors) OriginAllowed(r *http.Request) bool { + origin := r.Header.Get("Origin") + return c.isOriginAllowed(r, origin) +} + +// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests +// on the endpoint +func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool { + if c.allowOriginRequestFunc != nil { + return c.allowOriginRequestFunc(r, origin) + } + if c.allowOriginFunc != nil { + return c.allowOriginFunc(origin) + } + if c.allowedOriginsAll { + return true + } + origin = strings.ToLower(origin) + for _, o := range c.allowedOrigins { + if o == origin { + return true + } + } + for _, w := range c.allowedWOrigins { + if w.match(origin) { + return true + } + } + return false +} + +// isMethodAllowed checks if a given method can be used as part of a cross-domain request +// on the endpoint +func (c *Cors) isMethodAllowed(method string) bool { + if len(c.allowedMethods) == 0 { + // If no method allowed, always return false, even for preflight request + return false + } + method = strings.ToUpper(method) + if method == http.MethodOptions { + // Always allow preflight requests + return true + } + for _, m := range c.allowedMethods { + if m == method { + return true + } + } + return false +} + +// areHeadersAllowed checks if a given list of headers are allowed to used within +// a cross-domain request. +func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool { + if c.allowedHeadersAll || len(requestedHeaders) == 0 { + return true + } + for _, header := range requestedHeaders { + header = http.CanonicalHeaderKey(header) + found := false + for _, h := range c.allowedHeaders { + if h == header { + found = true + break + } + } + if !found { + return false + } + } + return true +} diff --git a/test/performance/vendor/github.com/rs/cors/utils.go b/test/performance/vendor/github.com/rs/cors/utils.go new file mode 100644 index 000000000..6bb120cae --- /dev/null +++ b/test/performance/vendor/github.com/rs/cors/utils.go @@ -0,0 +1,71 @@ +package cors + +import "strings" + +const toLower = 'a' - 'A' + +type converter func(string) string + +type wildcard struct { + prefix string + suffix string +} + +func (w wildcard) match(s string) bool { + return len(s) >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix) +} + +// convert converts a list of string using the passed converter function +func convert(s []string, c converter) []string { + out := []string{} + for _, i := range s { + out = append(out, c(i)) + } + return out +} + +// parseHeaderList tokenize + normalize a string containing a list of headers +func parseHeaderList(headerList string) []string { + l := len(headerList) + h := make([]byte, 0, l) + upper := true + // Estimate the number headers in order to allocate the right splice size + t := 0 + for i := 0; i < l; i++ { + if headerList[i] == ',' { + t++ + } + } + headers := make([]string, 0, t) + for i := 0; i < l; i++ { + b := headerList[i] + switch { + case b >= 'a' && b <= 'z': + if upper { + h = append(h, b-toLower) + } else { + h = append(h, b) + } + case b >= 'A' && b <= 'Z': + if !upper { + h = append(h, b+toLower) + } else { + h = append(h, b) + } + case b == '-' || b == '_' || b == '.' || (b >= '0' && b <= '9'): + h = append(h, b) + } + + if b == ' ' || b == ',' || i == l-1 { + if len(h) > 0 { + // Flush the found header + headers = append(headers, string(h)) + h = h[:0] + upper = true + } + } else { + upper = b == '-' || b == '_' + } + } + return headers +} diff --git a/test/performance/vendor/modules.txt b/test/performance/vendor/modules.txt index 4a03b06ec..38b0e816d 100644 --- a/test/performance/vendor/modules.txt +++ b/test/performance/vendor/modules.txt @@ -209,6 +209,9 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util +# github.com/rs/cors v1.8.2 +## explicit; go 1.13 +github.com/rs/cors # github.com/sanity-io/litter v1.5.5 ## explicit; go 1.16 github.com/sanity-io/litter diff --git a/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go b/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go index 1f61fa231..a8ab6ef23 100644 --- a/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go +++ b/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.pb.go @@ -60,6 +60,7 @@ func (NginxConfigAction) EnumDescriptor() ([]byte, []int) { return fileDescriptor_917f1a70b1fd7255, []int{0} } +// SSL type enum type NginxSslMetaData_NginxSslType int32 const ( @@ -278,24 +279,49 @@ func (m *PathInfo) GetConf() string { return "" } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. type NginxDetails struct { - NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` - Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` - ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` - ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` - ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` - StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` - BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` - LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` - RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` - Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` - Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` - StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` - ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 + NginxId string `protobuf:"bytes,1,opt,name=nginx_id,json=nginxId,proto3" json:"nginx_id"` + // Version of NGINX + // example: 1.23.2 + Version string `protobuf:"bytes,2,opt,name=version,proto3" json:"version"` + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf + ConfPath string `protobuf:"bytes,3,opt,name=conf_path,json=confPath,proto3" json:"conf_path"` + // Process ID + // example: 8 + ProcessId string `protobuf:"bytes,4,opt,name=process_id,json=processId,proto3" json:"process_id"` + // Process Path + // example: /usr/local/nginx/sbin/nginx + ProcessPath string `protobuf:"bytes,5,opt,name=process_path,json=processPath,proto3" json:"process_path"` + // Start Time + // example: 1670429190000 + StartTime int64 `protobuf:"varint,6,opt,name=start_time,json=startTime,proto3" json:"start_time"` + // Was NGINX built from source + // example: false + BuiltFromSource bool `protobuf:"varint,7,opt,name=built_from_source,json=builtFromSource,proto3" json:"built_from_source"` + // List of loadable modules + // example: [] + LoadableModules []string `protobuf:"bytes,8,rep,name=loadable_modules,json=loadableModules,proto3" json:"loadable_modules"` + // List of runtime modules + // example: [ "http_stub_status_module" ] + RuntimeModules []string `protobuf:"bytes,9,rep,name=runtime_modules,json=runtimeModules,proto3" json:"runtime_modules"` + // NGINX plus metadata + Plus *NginxPlusMetaData `protobuf:"bytes,10,opt,name=plus,proto3" json:"plus"` + // SSL metadata + Ssl *NginxSslMetaData `protobuf:"bytes,11,opt,name=ssl,proto3" json:"ssl"` + // Status URL + // example: http://localhost:8080/api + StatusUrl string `protobuf:"bytes,12,opt,name=status_url,json=statusUrl,proto3" json:"status_url"` + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] + ConfigureArgs []string `protobuf:"bytes,13,rep,name=configure_args,json=configureArgs,proto3" json:"configure_args"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxDetails) Reset() { *m = NginxDetails{} } @@ -422,8 +448,13 @@ func (m *NginxDetails) GetConfigureArgs() []string { return nil } +// swagger:model NginxPlusMetaData type NginxPlusMetaData struct { - Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // Is NGINX instance a plus instance + // example: true + Enabled bool `protobuf:"varint,1,opt,name=enabled,proto3" json:"enabled"` + // NGINX plus release + // example: R27 Release string `protobuf:"bytes,2,opt,name=release,proto3" json:"release"` XXX_NoUnkeyedLiteral struct{} `json:"-"` XXX_unrecognized []byte `json:"-"` @@ -477,12 +508,17 @@ func (m *NginxPlusMetaData) GetRelease() string { return "" } +// swagger:model NginxSslMetaData type NginxSslMetaData struct { - SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` - Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` - XXX_NoUnkeyedLiteral struct{} `json:"-"` - XXX_unrecognized []byte `json:"-"` - XXX_sizecache int32 `json:"-"` + // SSL type + // example: 0 + SslType NginxSslMetaData_NginxSslType `protobuf:"varint,1,opt,name=ssl_type,json=sslType,proto3,enum=f5.nginx.agent.sdk.NginxSslMetaData_NginxSslType" json:"ssl_type"` + // SSL details + // example: null + Details []string `protobuf:"bytes,2,rep,name=details,proto3" json:"details"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` } func (m *NginxSslMetaData) Reset() { *m = NginxSslMetaData{} } diff --git a/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto b/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto index f61c33ce6..305809568 100644 --- a/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto +++ b/vendor/github.com/nginx/agent/sdk/v2/proto/nginx.proto @@ -21,34 +21,70 @@ message PathInfo { string conf = 2 [(gogoproto.jsontag) = "conf" ]; } +// swagger:model NginxDetails // Each NGINXDetails is associated with with a single NGINX instance. message NginxDetails { + // NGINX ID + // example: b636d4376dea15405589692d3c5d3869ff3a9b26b0e7bb4bb1aa7e658ace1437 string nginx_id = 1 [(gogoproto.jsontag) = "nginx_id" ]; + // Version of NGINX + // example: 1.23.2 string version = 2 [(gogoproto.jsontag) = "version" ]; + // Path to configuration file + // example: /usr/local/nginx/conf/nginx.conf string conf_path = 3 [(gogoproto.jsontag) = "conf_path" ]; + // Process ID + // example: 8 string process_id = 4 [(gogoproto.jsontag) = "process_id" ]; + // Process Path + // example: /usr/local/nginx/sbin/nginx string process_path = 5 [(gogoproto.jsontag) = "process_path" ]; + // Start Time + // example: 1670429190000 int64 start_time = 6 [(gogoproto.jsontag) = "start_time" ]; + // Was NGINX built from source + // example: false bool built_from_source = 7 [(gogoproto.jsontag) = "built_from_source" ]; + // List of loadable modules + // example: [] repeated string loadable_modules = 8 [(gogoproto.jsontag) = "loadable_modules" ]; + // List of runtime modules + // example: [ "http_stub_status_module" ] repeated string runtime_modules = 9 [(gogoproto.jsontag) = "runtime_modules" ]; + // NGINX plus metadata NginxPlusMetaData plus = 10 [(gogoproto.jsontag) = "plus" ]; + // SSL metadata NginxSslMetaData ssl = 11 [(gogoproto.jsontag) = "ssl" ]; + // Status URL + // example: http://localhost:8080/api string status_url = 12 [(gogoproto.jsontag) = "status_url" ]; + // Configuration arguments + // example: [ "", "with-http_stub_status_module" ] repeated string configure_args = 13 [(gogoproto.jsontag) = "configure_args" ]; } +// swagger:model NginxPlusMetaData message NginxPlusMetaData { + // Is NGINX instance a plus instance + // example: true bool enabled = 1 [(gogoproto.jsontag) = "enabled" ]; + // NGINX plus release + // example: R27 string release = 2 [(gogoproto.jsontag) = "release" ]; } +// swagger:model NginxSslMetaData message NginxSslMetaData { + // SSL type enum enum NginxSslType { BUILT = 0; RUN = 1; } - NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL type + // example: 0 + NginxSslType ssl_type = 1 [(gogoproto.jsontag) = "ssl_type" ]; + // SSL details + // example: null repeated string details = 2 [(gogoproto.jsontag) = "details" ]; } diff --git a/vendor/github.com/rs/cors/LICENSE b/vendor/github.com/rs/cors/LICENSE new file mode 100644 index 000000000..d8e2df5a4 --- /dev/null +++ b/vendor/github.com/rs/cors/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2014 Olivier Poitrey + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished +to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/rs/cors/README.md b/vendor/github.com/rs/cors/README.md new file mode 100644 index 000000000..0ad3e94e1 --- /dev/null +++ b/vendor/github.com/rs/cors/README.md @@ -0,0 +1,116 @@ +# Go CORS handler [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/cors) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/cors/master/LICENSE) [![build](https://img.shields.io/travis/rs/cors.svg?style=flat)](https://travis-ci.org/rs/cors) [![Coverage](http://gocover.io/_badge/github.com/rs/cors)](http://gocover.io/github.com/rs/cors) + +CORS is a `net/http` handler implementing [Cross Origin Resource Sharing W3 specification](http://www.w3.org/TR/cors/) in Golang. + +## Getting Started + +After installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`. + +```go +package main + +import ( + "net/http" + + "github.com/rs/cors" +) + +func main() { + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.Write([]byte("{\"hello\": \"world\"}")) + }) + + // cors.Default() setup the middleware with default options being + // all origins accepted with simple methods (GET, POST). See + // documentation below for more options. + handler := cors.Default().Handler(mux) + http.ListenAndServe(":8080", handler) +} +``` + +Install `cors`: + + go get github.com/rs/cors + +Then run your server: + + go run server.go + +The server now runs on `localhost:8080`: + + $ curl -D - -H 'Origin: http://foo.com' http://localhost:8080/ + HTTP/1.1 200 OK + Access-Control-Allow-Origin: foo.com + Content-Type: application/json + Date: Sat, 25 Oct 2014 03:43:57 GMT + Content-Length: 18 + + {"hello": "world"} + +### Allow * With Credentials Security Protection + +This library has been modified to avoid a well known security issue when configured with `AllowedOrigins` to `*` and `AllowCredentials` to `true`. Such setup used to make the library reflects the request `Origin` header value, working around a security protection embedded into the standard that makes clients to refuse such configuration. This behavior has been removed with [#55](https://github.com/rs/cors/issues/55) and [#57](https://github.com/rs/cors/issues/57). + +If you depend on this behavior and understand the implications, you can restore it using the `AllowOriginFunc` with `func(origin string) {return true}`. + +Please refer to [#55](https://github.com/rs/cors/issues/55) for more information about the security implications. + +### More Examples + +* `net/http`: [examples/nethttp/server.go](https://github.com/rs/cors/blob/master/examples/nethttp/server.go) +* [Goji](https://goji.io): [examples/goji/server.go](https://github.com/rs/cors/blob/master/examples/goji/server.go) +* [Martini](http://martini.codegangsta.io): [examples/martini/server.go](https://github.com/rs/cors/blob/master/examples/martini/server.go) +* [Negroni](https://github.com/codegangsta/negroni): [examples/negroni/server.go](https://github.com/rs/cors/blob/master/examples/negroni/server.go) +* [Alice](https://github.com/justinas/alice): [examples/alice/server.go](https://github.com/rs/cors/blob/master/examples/alice/server.go) +* [HttpRouter](https://github.com/julienschmidt/httprouter): [examples/httprouter/server.go](https://github.com/rs/cors/blob/master/examples/httprouter/server.go) +* [Gorilla](http://www.gorillatoolkit.org/pkg/mux): [examples/gorilla/server.go](https://github.com/rs/cors/blob/master/examples/gorilla/server.go) +* [Buffalo](https://gobuffalo.io): [examples/buffalo/server.go](https://github.com/rs/cors/blob/master/examples/buffalo/server.go) +* [Gin](https://gin-gonic.github.io/gin): [examples/gin/server.go](https://github.com/rs/cors/blob/master/examples/gin/server.go) +* [Chi](https://github.com/go-chi/chi): [examples/chi/server.go](https://github.com/rs/cors/blob/master/examples/chi/server.go) + +## Parameters + +Parameters are passed to the middleware thru the `cors.New` method as follow: + +```go +c := cors.New(cors.Options{ + AllowedOrigins: []string{"http://foo.com", "http://foo.com:8080"}, + AllowCredentials: true, + // Enable Debugging for testing, consider disabling in production + Debug: true, +}) + +// Insert the middleware +handler = c.Handler(handler) +``` + +* **AllowedOrigins** `[]string`: A list of origins a cross-domain request can be executed from. If the special `*` value is present in the list, all origins will be allowed. An origin may contain a wildcard (`*`) to replace 0 or more characters (i.e.: `http://*.domain.com`). Usage of wildcards implies a small performance penality. Only one wildcard can be used per origin. The default value is `*`. +* **AllowOriginFunc** `func (origin string) bool`: A custom function to validate the origin. It takes the origin as an argument and returns true if allowed, or false otherwise. If this option is set, the content of `AllowedOrigins` is ignored. +* **AllowOriginRequestFunc** `func (r *http.Request, origin string) bool`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` and `AllowOriginFunc` is ignored +* **AllowedMethods** `[]string`: A list of methods the client is allowed to use with cross-domain requests. Default value is simple methods (`GET` and `POST`). +* **AllowedHeaders** `[]string`: A list of non simple headers the client is allowed to use with cross-domain requests. +* **ExposedHeaders** `[]string`: Indicates which headers are safe to expose to the API of a CORS API specification +* **AllowCredentials** `bool`: Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates. The default is `false`. +* **MaxAge** `int`: Indicates how long (in seconds) the results of a preflight request can be cached. The default is `0` which stands for no max age. +* **OptionsPassthrough** `bool`: Instructs preflight to let other potential next handlers to process the `OPTIONS` method. Turn this on if your application handles `OPTIONS`. +* **OptionsSuccessStatus** `int`: Provides a status code to use for successful OPTIONS requests. Default value is `http.StatusNoContent` (`204`). +* **Debug** `bool`: Debugging flag adds additional output to debug server side CORS issues. + +See [API documentation](http://godoc.org/github.com/rs/cors) for more info. + +## Benchmarks + + BenchmarkWithout 20000000 64.6 ns/op 8 B/op 1 allocs/op + BenchmarkDefault 3000000 469 ns/op 114 B/op 2 allocs/op + BenchmarkAllowedOrigin 3000000 608 ns/op 114 B/op 2 allocs/op + BenchmarkPreflight 20000000 73.2 ns/op 0 B/op 0 allocs/op + BenchmarkPreflightHeader 20000000 73.6 ns/op 0 B/op 0 allocs/op + BenchmarkParseHeaderList 2000000 847 ns/op 184 B/op 6 allocs/op + BenchmarkParse…Single 5000000 290 ns/op 32 B/op 3 allocs/op + BenchmarkParse…Normalized 2000000 776 ns/op 160 B/op 6 allocs/op + +## Licenses + +All source code is licensed under the [MIT License](https://raw.github.com/rs/cors/master/LICENSE). diff --git a/vendor/github.com/rs/cors/cors.go b/vendor/github.com/rs/cors/cors.go new file mode 100644 index 000000000..2ce24e3f3 --- /dev/null +++ b/vendor/github.com/rs/cors/cors.go @@ -0,0 +1,446 @@ +/* +Package cors is net/http handler to handle CORS related requests +as defined by http://www.w3.org/TR/cors/ + +You can configure it by passing an option struct to cors.New: + + c := cors.New(cors.Options{ + AllowedOrigins: []string{"foo.com"}, + AllowedMethods: []string{http.MethodGet, http.MethodPost, http.MethodDelete}, + AllowCredentials: true, + }) + +Then insert the handler in the chain: + + handler = c.Handler(handler) + +See Options documentation for more options. + +The resulting handler is a standard net/http handler. +*/ +package cors + +import ( + "log" + "net/http" + "os" + "strconv" + "strings" +) + +// Options is a configuration container to setup the CORS middleware. +type Options struct { + // AllowedOrigins is a list of origins a cross-domain request can be executed from. + // If the special "*" value is present in the list, all origins will be allowed. + // An origin may contain a wildcard (*) to replace 0 or more characters + // (i.e.: http://*.domain.com). Usage of wildcards implies a small performance penalty. + // Only one wildcard can be used per origin. + // Default value is ["*"] + AllowedOrigins []string + // AllowOriginFunc is a custom function to validate the origin. It take the origin + // as argument and returns true if allowed or false otherwise. If this option is + // set, the content of AllowedOrigins is ignored. + AllowOriginFunc func(origin string) bool + // AllowOriginRequestFunc is a custom function to validate the origin. It takes the HTTP Request object and the origin as + // argument and returns true if allowed or false otherwise. If this option is set, the content of `AllowedOrigins` + // and `AllowOriginFunc` is ignored. + AllowOriginRequestFunc func(r *http.Request, origin string) bool + // AllowedMethods is a list of methods the client is allowed to use with + // cross-domain requests. Default value is simple methods (HEAD, GET and POST). + AllowedMethods []string + // AllowedHeaders is list of non simple headers the client is allowed to use with + // cross-domain requests. + // If the special "*" value is present in the list, all headers will be allowed. + // Default value is [] but "Origin" is always appended to the list. + AllowedHeaders []string + // ExposedHeaders indicates which headers are safe to expose to the API of a CORS + // API specification + ExposedHeaders []string + // MaxAge indicates how long (in seconds) the results of a preflight request + // can be cached + MaxAge int + // AllowCredentials indicates whether the request can include user credentials like + // cookies, HTTP authentication or client side SSL certificates. + AllowCredentials bool + // OptionsPassthrough instructs preflight to let other potential next handlers to + // process the OPTIONS method. Turn this on if your application handles OPTIONS. + OptionsPassthrough bool + // Provides a status code to use for successful OPTIONS requests. + // Default value is http.StatusNoContent (204). + OptionsSuccessStatus int + // Debugging flag adds additional output to debug server side CORS issues + Debug bool +} + +// Logger generic interface for logger +type Logger interface { + Printf(string, ...interface{}) +} + +// Cors http handler +type Cors struct { + // Debug logger + Log Logger + // Normalized list of plain allowed origins + allowedOrigins []string + // List of allowed origins containing wildcards + allowedWOrigins []wildcard + // Optional origin validator function + allowOriginFunc func(origin string) bool + // Optional origin validator (with request) function + allowOriginRequestFunc func(r *http.Request, origin string) bool + // Normalized list of allowed headers + allowedHeaders []string + // Normalized list of allowed methods + allowedMethods []string + // Normalized list of exposed headers + exposedHeaders []string + maxAge int + // Set to true when allowed origins contains a "*" + allowedOriginsAll bool + // Set to true when allowed headers contains a "*" + allowedHeadersAll bool + // Status code to use for successful OPTIONS requests + optionsSuccessStatus int + allowCredentials bool + optionPassthrough bool +} + +// New creates a new Cors handler with the provided options. +func New(options Options) *Cors { + c := &Cors{ + exposedHeaders: convert(options.ExposedHeaders, http.CanonicalHeaderKey), + allowOriginFunc: options.AllowOriginFunc, + allowOriginRequestFunc: options.AllowOriginRequestFunc, + allowCredentials: options.AllowCredentials, + maxAge: options.MaxAge, + optionPassthrough: options.OptionsPassthrough, + } + if options.Debug && c.Log == nil { + c.Log = log.New(os.Stdout, "[cors] ", log.LstdFlags) + } + + // Normalize options + // Note: for origins and methods matching, the spec requires a case-sensitive matching. + // As it may error prone, we chose to ignore the spec here. + + // Allowed Origins + if len(options.AllowedOrigins) == 0 { + if options.AllowOriginFunc == nil && options.AllowOriginRequestFunc == nil { + // Default is all origins + c.allowedOriginsAll = true + } + } else { + c.allowedOrigins = []string{} + c.allowedWOrigins = []wildcard{} + for _, origin := range options.AllowedOrigins { + // Normalize + origin = strings.ToLower(origin) + if origin == "*" { + // If "*" is present in the list, turn the whole list into a match all + c.allowedOriginsAll = true + c.allowedOrigins = nil + c.allowedWOrigins = nil + break + } else if i := strings.IndexByte(origin, '*'); i >= 0 { + // Split the origin in two: start and end string without the * + w := wildcard{origin[0:i], origin[i+1:]} + c.allowedWOrigins = append(c.allowedWOrigins, w) + } else { + c.allowedOrigins = append(c.allowedOrigins, origin) + } + } + } + + // Allowed Headers + if len(options.AllowedHeaders) == 0 { + // Use sensible defaults + c.allowedHeaders = []string{"Origin", "Accept", "Content-Type", "X-Requested-With"} + } else { + // Origin is always appended as some browsers will always request for this header at preflight + c.allowedHeaders = convert(append(options.AllowedHeaders, "Origin"), http.CanonicalHeaderKey) + for _, h := range options.AllowedHeaders { + if h == "*" { + c.allowedHeadersAll = true + c.allowedHeaders = nil + break + } + } + } + + // Allowed Methods + if len(options.AllowedMethods) == 0 { + // Default is spec's "simple" methods + c.allowedMethods = []string{http.MethodGet, http.MethodPost, http.MethodHead} + } else { + c.allowedMethods = convert(options.AllowedMethods, strings.ToUpper) + } + + // Options Success Status Code + if options.OptionsSuccessStatus == 0 { + c.optionsSuccessStatus = http.StatusNoContent + } else { + c.optionsSuccessStatus = options.OptionsSuccessStatus + } + + return c +} + +// Default creates a new Cors handler with default options. +func Default() *Cors { + return New(Options{}) +} + +// AllowAll create a new Cors handler with permissive configuration allowing all +// origins with all standard methods with any header and credentials. +func AllowAll() *Cors { + return New(Options{ + AllowedOrigins: []string{"*"}, + AllowedMethods: []string{ + http.MethodHead, + http.MethodGet, + http.MethodPost, + http.MethodPut, + http.MethodPatch, + http.MethodDelete, + }, + AllowedHeaders: []string{"*"}, + AllowCredentials: false, + }) +} + +// Handler apply the CORS specification on the request, and add relevant CORS headers +// as necessary. +func (c *Cors) Handler(h http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("Handler: Preflight request") + c.handlePreflight(w, r) + // Preflight requests are standalone and should stop the chain as some other + // middleware may not handle OPTIONS requests correctly. One typical example + // is authentication middleware ; OPTIONS requests won't carry authentication + // headers (see #1) + if c.optionPassthrough { + h.ServeHTTP(w, r) + } else { + w.WriteHeader(c.optionsSuccessStatus) + } + } else { + c.logf("Handler: Actual request") + c.handleActualRequest(w, r) + h.ServeHTTP(w, r) + } + }) +} + +// HandlerFunc provides Martini compatible handler +func (c *Cors) HandlerFunc(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("HandlerFunc: Preflight request") + c.handlePreflight(w, r) + + w.WriteHeader(c.optionsSuccessStatus) + } else { + c.logf("HandlerFunc: Actual request") + c.handleActualRequest(w, r) + } +} + +// Negroni compatible interface +func (c *Cors) ServeHTTP(w http.ResponseWriter, r *http.Request, next http.HandlerFunc) { + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + c.logf("ServeHTTP: Preflight request") + c.handlePreflight(w, r) + // Preflight requests are standalone and should stop the chain as some other + // middleware may not handle OPTIONS requests correctly. One typical example + // is authentication middleware ; OPTIONS requests won't carry authentication + // headers (see #1) + if c.optionPassthrough { + next(w, r) + } else { + w.WriteHeader(c.optionsSuccessStatus) + } + } else { + c.logf("ServeHTTP: Actual request") + c.handleActualRequest(w, r) + next(w, r) + } +} + +// handlePreflight handles pre-flight CORS requests +func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) { + headers := w.Header() + origin := r.Header.Get("Origin") + + if r.Method != http.MethodOptions { + c.logf(" Preflight aborted: %s!=OPTIONS", r.Method) + return + } + // Always set Vary headers + // see https://github.com/rs/cors/issues/10, + // https://github.com/rs/cors/commit/dbdca4d95feaa7511a46e6f1efb3b3aa505bc43f#commitcomment-12352001 + headers.Add("Vary", "Origin") + headers.Add("Vary", "Access-Control-Request-Method") + headers.Add("Vary", "Access-Control-Request-Headers") + + if origin == "" { + c.logf(" Preflight aborted: empty origin") + return + } + if !c.isOriginAllowed(r, origin) { + c.logf(" Preflight aborted: origin '%s' not allowed", origin) + return + } + + reqMethod := r.Header.Get("Access-Control-Request-Method") + if !c.isMethodAllowed(reqMethod) { + c.logf(" Preflight aborted: method '%s' not allowed", reqMethod) + return + } + reqHeaders := parseHeaderList(r.Header.Get("Access-Control-Request-Headers")) + if !c.areHeadersAllowed(reqHeaders) { + c.logf(" Preflight aborted: headers '%v' not allowed", reqHeaders) + return + } + if c.allowedOriginsAll { + headers.Set("Access-Control-Allow-Origin", "*") + } else { + headers.Set("Access-Control-Allow-Origin", origin) + } + // Spec says: Since the list of methods can be unbounded, simply returning the method indicated + // by Access-Control-Request-Method (if supported) can be enough + headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod)) + if len(reqHeaders) > 0 { + + // Spec says: Since the list of headers can be unbounded, simply returning supported headers + // from Access-Control-Request-Headers can be enough + headers.Set("Access-Control-Allow-Headers", strings.Join(reqHeaders, ", ")) + } + if c.allowCredentials { + headers.Set("Access-Control-Allow-Credentials", "true") + } + if c.maxAge > 0 { + headers.Set("Access-Control-Max-Age", strconv.Itoa(c.maxAge)) + } + c.logf(" Preflight response headers: %v", headers) +} + +// handleActualRequest handles simple cross-origin requests, actual request or redirects +func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) { + headers := w.Header() + origin := r.Header.Get("Origin") + + // Always set Vary, see https://github.com/rs/cors/issues/10 + headers.Add("Vary", "Origin") + if origin == "" { + c.logf(" Actual request no headers added: missing origin") + return + } + if !c.isOriginAllowed(r, origin) { + c.logf(" Actual request no headers added: origin '%s' not allowed", origin) + return + } + + // Note that spec does define a way to specifically disallow a simple method like GET or + // POST. Access-Control-Allow-Methods is only used for pre-flight requests and the + // spec doesn't instruct to check the allowed methods for simple cross-origin requests. + // We think it's a nice feature to be able to have control on those methods though. + if !c.isMethodAllowed(r.Method) { + c.logf(" Actual request no headers added: method '%s' not allowed", r.Method) + + return + } + if c.allowedOriginsAll { + headers.Set("Access-Control-Allow-Origin", "*") + } else { + headers.Set("Access-Control-Allow-Origin", origin) + } + if len(c.exposedHeaders) > 0 { + headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", ")) + } + if c.allowCredentials { + headers.Set("Access-Control-Allow-Credentials", "true") + } + c.logf(" Actual response added headers: %v", headers) +} + +// convenience method. checks if a logger is set. +func (c *Cors) logf(format string, a ...interface{}) { + if c.Log != nil { + c.Log.Printf(format, a...) + } +} + +// check the Origin of a request. No origin at all is also allowed. +func (c *Cors) OriginAllowed(r *http.Request) bool { + origin := r.Header.Get("Origin") + return c.isOriginAllowed(r, origin) +} + +// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests +// on the endpoint +func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool { + if c.allowOriginRequestFunc != nil { + return c.allowOriginRequestFunc(r, origin) + } + if c.allowOriginFunc != nil { + return c.allowOriginFunc(origin) + } + if c.allowedOriginsAll { + return true + } + origin = strings.ToLower(origin) + for _, o := range c.allowedOrigins { + if o == origin { + return true + } + } + for _, w := range c.allowedWOrigins { + if w.match(origin) { + return true + } + } + return false +} + +// isMethodAllowed checks if a given method can be used as part of a cross-domain request +// on the endpoint +func (c *Cors) isMethodAllowed(method string) bool { + if len(c.allowedMethods) == 0 { + // If no method allowed, always return false, even for preflight request + return false + } + method = strings.ToUpper(method) + if method == http.MethodOptions { + // Always allow preflight requests + return true + } + for _, m := range c.allowedMethods { + if m == method { + return true + } + } + return false +} + +// areHeadersAllowed checks if a given list of headers are allowed to used within +// a cross-domain request. +func (c *Cors) areHeadersAllowed(requestedHeaders []string) bool { + if c.allowedHeadersAll || len(requestedHeaders) == 0 { + return true + } + for _, header := range requestedHeaders { + header = http.CanonicalHeaderKey(header) + found := false + for _, h := range c.allowedHeaders { + if h == header { + found = true + break + } + } + if !found { + return false + } + } + return true +} diff --git a/vendor/github.com/rs/cors/utils.go b/vendor/github.com/rs/cors/utils.go new file mode 100644 index 000000000..6bb120cae --- /dev/null +++ b/vendor/github.com/rs/cors/utils.go @@ -0,0 +1,71 @@ +package cors + +import "strings" + +const toLower = 'a' - 'A' + +type converter func(string) string + +type wildcard struct { + prefix string + suffix string +} + +func (w wildcard) match(s string) bool { + return len(s) >= len(w.prefix)+len(w.suffix) && strings.HasPrefix(s, w.prefix) && strings.HasSuffix(s, w.suffix) +} + +// convert converts a list of string using the passed converter function +func convert(s []string, c converter) []string { + out := []string{} + for _, i := range s { + out = append(out, c(i)) + } + return out +} + +// parseHeaderList tokenize + normalize a string containing a list of headers +func parseHeaderList(headerList string) []string { + l := len(headerList) + h := make([]byte, 0, l) + upper := true + // Estimate the number headers in order to allocate the right splice size + t := 0 + for i := 0; i < l; i++ { + if headerList[i] == ',' { + t++ + } + } + headers := make([]string, 0, t) + for i := 0; i < l; i++ { + b := headerList[i] + switch { + case b >= 'a' && b <= 'z': + if upper { + h = append(h, b-toLower) + } else { + h = append(h, b) + } + case b >= 'A' && b <= 'Z': + if !upper { + h = append(h, b+toLower) + } else { + h = append(h, b) + } + case b == '-' || b == '_' || b == '.' || (b >= '0' && b <= '9'): + h = append(h, b) + } + + if b == ' ' || b == ',' || i == l-1 { + if len(h) > 0 { + // Flush the found header + headers = append(headers, string(h)) + h = h[:0] + upper = true + } + } else { + upper = b == '-' || b == '_' + } + } + return headers +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 8165425f1..285066924 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -192,6 +192,9 @@ github.com/prometheus/common/model github.com/prometheus/procfs github.com/prometheus/procfs/internal/fs github.com/prometheus/procfs/internal/util +# github.com/rs/cors v1.8.2 +## explicit; go 1.13 +github.com/rs/cors # github.com/shirou/gopsutil v3.21.11+incompatible ## explicit github.com/shirou/gopsutil/cpu