Git Product home page Git Product logo

cors's Introduction

cors gives you easy control over Cross Origin Resource Sharing for your site.

It allows you to whitelist particular domains per route, or to simply allow all domains * If desired you may customize nearly every aspect of the specification.

Syntax

cors [path] [domains...] {
	origin            [origin]
	origin_regexp     [regexp]
	methods           [methods]
	allow_credentials [allowCredentials]
	max_age           [maxAge]
	allowed_headers   [allowedHeaders]
	exposed_headers   [exposedHeaders]
}
  • path is the file or directory this applies to (default is /).
  • domains is a space-seperated list of domains to allow. If ommitted, all domains will be granted access.
  • origin is a domain to grant access to. May be specified multiple times or ommitted.
  • origin_regexp is a regexp that will be matched to the Origin header. Access will be granted accordingly. It can be used in conjonction with the origin config (executed as a fallback to origin). May be specified multiple times or ommitted.
  • methods is set of http methods to allow. Default is these: POST,GET,OPTIONS,PUT,DELETE.
  • allow_credentials sets the value of the Access-Control-Allow-Credentials header. Can be true or false. By default, header will not be included.
  • max_age is the length of time in seconds to cache preflight info. Not set by default.
  • allowed_headers is a comma-seperated list of request headers a client may send.
  • exposed_headers is a comma-seperated list of response headers a client may access.

Examples

Simply allow all domains to request any path:

cors

Protect specific paths only, and only allow a few domains:

cors /foo http://mysite.com http://anothertrustedsite.com

Full configuration:

cors / {
  origin            http://allowedSite.com
  origin            http://anotherSite.org https://anotherSite.org
  origin_regexp     .+\.example\.com$
  methods           POST,PUT
  allow_credentials false
  max_age           3600
  allowed_headers   X-Custom-Header,X-Foobar
  exposed_headers   X-Something-Special,SomethingElse
}

cors's People

Contributors

baldinof avatar captncraig avatar lioman avatar michele avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

cors's Issues

Couple of syntax recommendations

I noticed while going through the docs for cors that allowedHeaders and exposedHeaders are comma-separated lists (and I think methods and origin might be, too). Caddyfile generally separates arguments using spaces, so instead of:

allowedHeaders   X-Custom-Header,X-Foobar

you would have:

allowedHeaders   X-Custom-Header X-Foobar

Would this be a change you'd agree with making, for consistency?

Also, the camelCasing or whatever it's called of some of the keywords like allowCredentials is a little inconsistent; typically we stick with all lowercase words or, if necessary, separate the words with underscore: allow_credentials. (proxy was the first to do this, I think - but it stuck) What would you think about either finding shorter names or switching to the underscore syntax?

Duplicate access-control-allow-origin on GET request

Trying to use the InfluxDB UI which is proxied by Caddy. The OPTIONS request looks fine, but on the subsequent GET request I get a CORS error because of the duplicate headers:

access-control-allow-origin:https://influx.mydomain.com
access-control-allow-origin:https://influx.mydomain.com

My Caddyfile looks like:

https://influx.mydomain.com {
  # tls ...
  # basicauth ...
  proxy / http://influxdb:8083/
}

https://influx.mydomain.com:8086 {
  # tls ...
  proxy / http://influxdb:8086/
  cors / {
    origin https://influx.mydomain.com
    allowed_headers Authorization
  }
}

Any ideas why this is happening?

Cors directive/plugin being ignored

1. What version of Caddy are you using (caddy -version)?

Caddy 0.10.10

2. What are you trying to do?

Enable cors for a file in my site. Using the cors plugin

3. What is your entire Caddyfile?


mysite.org {
tls [email protected]
root /srv
cors /config.json  {
		origin *
		methods GET,POST,OPTIONS
		allowed_headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
		exposed_headers DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
		}

}

subsite.org {
tls myemail
proxy / 192.168.34.56
}

4. How did you run Caddy (give the full command and describe the execution environment)?

caddy --conf /root/.caddy/Caddyfile --log stdout

5. Please paste any relevant HTTP request(s) here.

curl -vvv https://mapa.rutasdelamemoria.org/config.json

6. What did you expect to see?

Using another site as reference i expected something like :

* TCP_NODELAY set
* Connected to sandbox.uchaguzi.or.ke (23.253.46.148) port 443 (#0)
* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* NPN, negotiated HTTP1.1
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Unknown (67):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server did not agree to a protocol
* Server certificate:
*  subject: CN=sandbox.uchaguzi.or.ke
*  start date: Oct  5 17:19:23 2017 GMT
*  expire date: Jan  3 17:19:23 2018 GMT
*  subjectAltName: host "sandbox.uchaguzi.or.ke" matched cert's "sandbox.uchaguzi.or.ke"
*  issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
*  SSL certificate verify ok.
> GET /config.json HTTP/1.1
> Host: sandbox.uchaguzi.or.ke
> User-Agent: curl/7.55.1
> Accept: */*
> 
< HTTP/1.1 200 OK
< Server: nginx/1.4.6 (Ubuntu)
< Date: Mon, 13 Nov 2017 15:06:26 GMT
< Content-Type: application/json
< Content-Length: 332
< Last-Modified: Tue, 31 Oct 2017 15:36:29 GMT
< Connection: keep-alive
< ETag: "59f8987d-14c"
< Access-Control-Allow-Origin: *
< Access-Control-Allow-Methods: GET, POST, OPTIONS
< Access-Control-Allow-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
< Access-Control-Expose-Headers: DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range
< Accept-Ranges: bytes
< 

7. What did you see instead (give full error messages and/or log)?

* ALPN, offering h2
* ALPN, offering http/1.1
* Cipher selection: ALL:!EXPORT:!EXPORT40:!EXPORT56:!aNULL:!LOW:!RC4:@STRENGTH
* successfully set certificate verify locations:
*   CAfile: /etc/ssl/certs/ca-certificates.crt
  CApath: none
* TLSv1.2 (OUT), TLS handshake, Client hello (1):
* TLSv1.2 (IN), TLS handshake, Server hello (2):
* TLSv1.2 (IN), TLS handshake, Certificate (11):
* TLSv1.2 (IN), TLS handshake, Server key exchange (12):
* TLSv1.2 (IN), TLS handshake, Server finished (14):
* TLSv1.2 (OUT), TLS handshake, Client key exchange (16):
* TLSv1.2 (OUT), TLS change cipher, Client hello (1):
* TLSv1.2 (OUT), TLS handshake, Finished (20):
* TLSv1.2 (IN), TLS handshake, Finished (20):
* SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384
* ALPN, server accepted to use h2
* Server certificate:
*  subject: CN=mapa.rutasdelamemoria.org
*  start date: Oct 26 00:27:46 2017 GMT
*  expire date: Jan 24 00:27:46 2018 GMT
*  subjectAltName: host "mapa.rutasdelamemoria.org" matched cert's "mapa.rutasdelamemoria.org"
*  issuer: C=US; O=Let's Encrypt; CN=Let's Encrypt Authority X3
*  SSL certificate verify ok.
* Using HTTP2, server supports multi-use
* Connection state changed (HTTP/2 confirmed)
* Copying HTTP/2 data in stream buffer to connection buffer after upgrade: len=0
* Using Stream ID: 1 (easy handle 0x55db30d1ac10)
> GET /config.json HTTP/2
> Host: mapa.rutasdelamemoria.org
> User-Agent: curl/7.55.1
> Accept: */*
> 
* Connection state changed (MAX_CONCURRENT_STREAMS updated)!
< HTTP/2 200 
< accept-ranges: bytes
< content-type: text/plain; charset=utf-8
< etag: "ozcxw0cr"
< last-modified: Mon, 13 Nov 2017 13:09:36 GMT
< server: Caddy
< content-length: 459
< date: Mon, 13 Nov 2017 15:05:54 GMT
< 

No error logs generated by Caddy.

8. How can someone who is starting from scratch reproduce the bug as minimally as possible?

Run Caddy 0.10.10 with cors directive, and multiple site in 1 conf file. Not sure if the problem is the mulsite conf.

Using docker container for caddy : abiosoft/caddy:latest

Cannot build with the plugin

When I tried to build with the cors plugin by following steps (from https://github.com/caddyserver/caddy/tree/v1#install), the cors plugin cannot be compiled in:

  1. Create a new folder and within a main.go file as:
package main

import (
	"github.com/caddyserver/caddy/caddy/caddymain"
	_ "github.com/captncraig/cors"
        _ "github.com/caddyserver/forwardproxy"
)
func main() {
	// optional: disable telemetry
	// caddymain.EnableTelemetry = false
	caddymain.Run()
}
  1. Run go mod init caddy

  2. Run go get -u github.com/caddyserver/caddy
    image

  3. Run go build
    image

After the Caddy binary generated, I ran ./caddy -plugins and didn’t see the http.cors plugin listed, however the http.forwardproxy plugin can be seen.
image

Caddy's import path has changed

Caddy's import path (and Go module name) has changed from

github.com/mholt/caddy

to

github.com/caddyserver/caddy

Unfortunately, Go modules are not yet mature enough to handle a change like this (see https://golang.org/issue/26904 - "haven't implemented that part yet" but high on priority list for Go 1.14) which caught me off-guard. Using Go module's replace feature didn't act the way I expected, either. Caddy now fails to build with plugins until they update their import paths.

I've hacked a fix into the build server, so downloading Caddy with your plugin from our website should continue working without any changes on your part, for now. However, please take a moment and update your import paths, and do a new deploy on the website, because the workaround involves ignoring module checksums and performing a delicate recursive search-and-replace.

I'm terribly sorry about this. I did a number of tests and dry-runs to ensure the change would be smooth, but apparently some unknown combination of GOPATH, Go modules' lack of maturity, and other hidden variables in the system or environment must have covered up something I missed.

This bash script should make it easy (run it from your project's top-level directory):

find . -name '*.go' | while read -r f; do
	sed -i.bak 's/\/mholt\/caddy/\/caddyserver\/caddy/g' $f && rm $f.bak
done

We use this script in the build server as part of the temporary workaround.

Let me know if you have any questions! Sorry again for the inconvenience.

Calling next middleware on failed CORS request

Thanks for providing this plugin. Always great to see open source efforts coming together.

Recently I ran into an issue with mailout (or at least I thought it was the issue source). I'm using CORS to prevent other sides from requesting/sending emails and therefore used the cors plugin.

Config:

cors / https://example.com

So only requests from example.com should be able to send mail/request/post to the given url.
The result is that the request seems to fail on the client-side with:

XMLHttpRequest cannot load https://mailout.example.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:1313' is therefore not allowed access.
jquery.min.js:4 XHR failed loading: POST "https://mailout.example.com/".

What I thought would happen:
No email would be send and an error would be returned for the request.

What happened:
Email was sent (mailout middleware was called), POST request returned 200.

Might that be an issue with how the CORS middleware handles this or should am I doing something strange on the clientside?

For reference: mailout issue

No Injected Headers when using Proxy

It appears that when using the proxy directive, the CORS headers are not being added. Not sure if this is intended behavior or not.

Caddyfile:

localhost:80
cors
proxy / localhost:8000

As a work around, I've been able to just use the header directive, but it would be nice to see this work with the cors addon.

Caddyfile with Workaround:

localhost:80
header / {
      Access-Control-Allow-Origin  *
      Access-Control-Allow-Methods "GET, POST, OPTIONS"
      Access-Control-Allow-Headers "Authorization"
}
proxy / localhost:8000

Update to 0.9 plugin format

I forgot to leave a PR here, but until this plugin is updated for the Caddy 0.9 format I can't include it on the download page. Sorry for the inconvenience. :-/

Submit this plugin to the new Caddy website

Is there anything I can do to help you add this and your other plugins to the new Caddy site? It should make things easier for you in the long run, at least, that's my hope.

I know you've been super busy with the DNS stuff for Stack (which is fabulous, by the way) -- I just wanted to check in and make sure there's nothing else I can do before April 20 to convince you. :)

CORS adding multiple values in Access-Control-Allow-Origin?

Hi,

I'm setting up my environment using Caddy + CORS but I'm getting the error:

Access to fetch at 'https://mydomain.cloud/api/v1/auth' from origin 'http://localhost:3000' has been blocked by CORS policy: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:3000, http://localhost:3000', but only one is allowed. Have the server send the header with a valid value, or, if an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

even if my cors is setting up like this:

     cors / {
        origin            http://localhost:3000
        methods           POST,PUT,GET,OPTIONS
        allow_credentials true
        max_age           1728000
        allowed_headers   Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Access-Control-Allow-Headers
        exposed_headers   Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range,Access-Control-Allow-Headers
     }

Am I doing something wrong?

Thanks,

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.