feat(BREAKING): extend cors functionality (#25)

This commit is contained in:
Steven Vandevelde
2019-06-11 13:02:10 +01:00
committed by Henrique Dias
parent 764a69cd33
commit 7358553e69
3 changed files with 82 additions and 31 deletions
+18 -2
View File
@@ -28,8 +28,17 @@ rules: []
# CORS configuration # CORS configuration
cors: cors:
- enabled: false enabled: true
allowed_hosts: [] credentials: true
allowed_headers:
- Depth
allowed_hosts:
- http://localhost:8080
allowed_methods:
- GET
exposed_headers:
- Content-Length
- Content-Range
users: users:
- username: admin - username: admin
@@ -54,6 +63,13 @@ There are more ways to customize how you run WebDAV through flags and environmen
An example of how to use this with `systemd` is on [webdav.service.example](/webdav.service.example). An example of how to use this with `systemd` is on [webdav.service.example](/webdav.service.example).
### CORS
The `allowed_*` properties are optional, the default value for each of them will be `*`. `exposed_headers` is optional as well, but is not set if not defined. Setting `credentials` to `true` will allow you to:
1. Use `withCredentials = true` in javascript.
2. Use the `username:password@host` syntax.
## License ## License
MIT © [Henrique Dias](https://hacdias.com) MIT © [Henrique Dias](https://hacdias.com)
+32 -18
View File
@@ -123,30 +123,44 @@ func parseUsers(raw []interface{}, c *webdav.Config) {
} }
} }
func parseCors(raw []interface{}, c *webdav.Config) { func parseCors(cfg map[string]interface{}, c *webdav.Config) {
hosts := []string{}
for _, v := range raw {
if cfg, ok := v.(map[interface{}]interface{}); ok {
cors := webdav.CorsCfg{ cors := webdav.CorsCfg{
Enabled: cfg["enabled"].(bool), Enabled: cfg["enabled"].(bool),
AllowedHosts: []string{}, Credentials: cfg["credentials"].(bool),
} }
if allowedHosts, ok := cfg["allowed_hosts"]; ok { cors.AllowedHeaders = corsProperty("allowed_headers", cfg)
hosts = append(hosts, strings.Split(allowedHosts.(string), ",")...) cors.AllowedHosts = corsProperty("allowed_hosts", cfg)
} cors.AllowedMethods = corsProperty("allowed_methods", cfg)
cors.ExposedHeaders = corsProperty("exposed_headers", cfg)
if len(hosts) == 0 {
hosts = append(hosts, "*")
}
cors.AllowedHosts = hosts
c.Cors = cors c.Cors = cors
} }
func corsProperty(property string, cfg map[string]interface{}) []string {
var def []string
if property == "exposed_headers" {
def = []string{}
} else {
def = []string{"*"}
} }
if allowed, ok := cfg[property].([]interface{}); ok {
items := make([]string, len(allowed))
for idx, a := range allowed {
items[idx] = a.(string)
}
if len(items) == 0 {
return def
} else {
return items
}
}
return def
} }
func readConfig(flags *pflag.FlagSet) *webdav.Config { func readConfig(flags *pflag.FlagSet) *webdav.Config {
@@ -163,7 +177,7 @@ func readConfig(flags *pflag.FlagSet) *webdav.Config {
Auth: getOptB(flags, "auth"), Auth: getOptB(flags, "auth"),
Cors: webdav.CorsCfg{ Cors: webdav.CorsCfg{
Enabled: false, Enabled: false,
AllowedHosts: []string{}, Credentials: false,
}, },
Users: map[string]*webdav.User{}, Users: map[string]*webdav.User{},
} }
@@ -179,7 +193,7 @@ func readConfig(flags *pflag.FlagSet) *webdav.Config {
} }
rawCors := v.Get("cors") rawCors := v.Get("cors")
if cors, ok := rawCors.([]interface{}); ok { if cors, ok := rawCors.(map[string]interface{}); ok {
parseCors(cors, cfg) parseCors(cors, cfg)
} }
+29 -8
View File
@@ -4,12 +4,17 @@ import (
"context" "context"
"log" "log"
"net/http" "net/http"
"strings"
) )
// CorsCfg is the CORS config. // CorsCfg is the CORS config.
type CorsCfg struct { type CorsCfg struct {
Enabled bool Enabled bool
Credentials bool
AllowedHeaders []string
AllowedHosts []string AllowedHosts []string
AllowedMethods []string
ExposedHeaders []string
} }
// Config is the configuration of a WebDAV instance. // Config is the configuration of a WebDAV instance.
@@ -25,19 +30,34 @@ func (c *Config) ServeHTTP(w http.ResponseWriter, r *http.Request) {
u := c.User u := c.User
requestOrigin := r.Header.Get("Origin") requestOrigin := r.Header.Get("Origin")
// add cors headers before any operation so even on 401 unauthorized cors will working only when Origin header is present so request came from browser // Add CORS headers before any operation so even on a 401 unauthorized status, CORS will work.
if c.Cors.Enabled && requestOrigin != "" { if c.Cors.Enabled && requestOrigin != "" {
headers := w.Header() headers := w.Header()
if len(c.Cors.AllowedHosts) == 1 && c.Cors.AllowedHosts[0] == "*" { allowedHeaders := strings.Join(c.Cors.AllowedHeaders, ", ")
headers.Set("Access-Control-Allow-Methods", "*") allowedMethods := strings.Join(c.Cors.AllowedMethods, ", ")
headers.Set("Access-Control-Allow-Headers", "*") exposedHeaders := strings.Join(c.Cors.ExposedHeaders, ", ")
allowAllHosts := len(c.Cors.AllowedHosts) == 1 && c.Cors.AllowedHosts[0] == "*"
allowedHost := isAllowedHost(c.Cors.AllowedHosts, requestOrigin)
if allowAllHosts {
headers.Set("Access-Control-Allow-Origin", "*") headers.Set("Access-Control-Allow-Origin", "*")
} else if isAllowedHost(c.Cors.AllowedHosts, requestOrigin) { } else if allowedHost {
headers.Set("Access-Control-Allow-Origin", requestOrigin) headers.Set("Access-Control-Allow-Origin", requestOrigin)
headers.Set("Access-Control-Allow-Headers", "*") }
headers.Set("Access-Control-Allow-Methods", "*")
if allowAllHosts || allowedHost {
headers.Set("Access-Control-Allow-Headers", allowedHeaders)
headers.Set("Access-Control-Allow-Methods", allowedMethods)
if c.Cors.Credentials {
headers.Set("Access-Control-Allow-Credentials", "true")
}
if len(c.Cors.ExposedHeaders) > 0 {
headers.Set("Access-Control-Expose-Headers", exposedHeaders)
}
} }
} }
@@ -45,6 +65,7 @@ func (c *Config) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return return
} }
// Authentication
if c.Auth { if c.Auth {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)