Security: Add "header" package for setting common response headers #98
Signed-off-by: Michael Mayer <michael@photoprism.app>
This commit is contained in:
parent
6038af786e
commit
dc39fc44d2
|
@ -70,10 +70,6 @@ func startAction(ctx *cli.Context) error {
|
|||
// Pass this context down the chain.
|
||||
cctx, cancel := context.WithCancel(context.Background())
|
||||
|
||||
if err := conf.Init(); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// Initialize the index database.
|
||||
conf.InitDb()
|
||||
|
||||
|
|
|
@ -2,7 +2,7 @@ package config
|
|||
|
||||
// ClientExt returns optional client config values by namespace.
|
||||
func ClientExt(c *Config, t ClientType) Values {
|
||||
configs := Extensions()
|
||||
configs := Ext()
|
||||
result := make(Values, len(configs))
|
||||
|
||||
for _, conf := range configs {
|
||||
|
|
|
@ -111,16 +111,7 @@ func NewConfig(ctx *cli.Context) *Config {
|
|||
}
|
||||
}
|
||||
|
||||
// Initialize package extensions.
|
||||
for _, ext := range Extensions() {
|
||||
start := time.Now()
|
||||
|
||||
if err := ext.init(c); err != nil {
|
||||
log.Warnf("config: %s in %s extension[%s]", err, clean.Log(ext.name), time.Since(start))
|
||||
} else {
|
||||
log.Debugf("config: %s extension loaded [%s]", clean.Log(ext.name), time.Since(start))
|
||||
}
|
||||
}
|
||||
Ext().Init(c)
|
||||
|
||||
return c
|
||||
}
|
||||
|
|
|
@ -1,34 +0,0 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
var (
|
||||
extMutex sync.Mutex
|
||||
extensions atomic.Value
|
||||
)
|
||||
|
||||
// Extension represents a named package extension with callbacks.
|
||||
type Extension struct {
|
||||
name string
|
||||
init func(c *Config) error
|
||||
clientValues func(c *Config, t ClientType) Values
|
||||
}
|
||||
|
||||
// Register registers a new package extension.
|
||||
func Register(name string, initConfig func(c *Config) error, clientConfig func(c *Config, t ClientType) Values) {
|
||||
extMutex.Lock()
|
||||
n, _ := extensions.Load().([]Extension)
|
||||
extensions.Store(append(n, Extension{name, initConfig, clientConfig}))
|
||||
extMutex.Unlock()
|
||||
}
|
||||
|
||||
// Extensions returns all registered package extensions.
|
||||
func Extensions() (ext []Extension) {
|
||||
extMutex.Lock()
|
||||
ext, _ = extensions.Load().([]Extension)
|
||||
extMutex.Unlock()
|
||||
return ext
|
||||
}
|
56
internal/config/extensions.go
Normal file
56
internal/config/extensions.go
Normal file
|
@ -0,0 +1,56 @@
|
|||
package config
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/photoprism/photoprism/pkg/clean"
|
||||
)
|
||||
|
||||
var (
|
||||
extInit sync.Once
|
||||
extMutex sync.Mutex
|
||||
extensions atomic.Value
|
||||
)
|
||||
|
||||
// Register registers a new package extension.
|
||||
func Register(name string, initConfig func(c *Config) error, clientConfig func(c *Config, t ClientType) Values) {
|
||||
extMutex.Lock()
|
||||
n, _ := extensions.Load().(Extensions)
|
||||
extensions.Store(append(n, Extension{name: name, init: initConfig, clientValues: clientConfig}))
|
||||
extMutex.Unlock()
|
||||
}
|
||||
|
||||
// Ext returns all registered package extensions.
|
||||
func Ext() (ext Extensions) {
|
||||
extMutex.Lock()
|
||||
ext, _ = extensions.Load().(Extensions)
|
||||
extMutex.Unlock()
|
||||
return ext
|
||||
}
|
||||
|
||||
// Extensions represents a list of package extensions.
|
||||
type Extensions []Extension
|
||||
|
||||
// Extension represents a named package extension with callbacks.
|
||||
type Extension struct {
|
||||
name string
|
||||
init func(c *Config) error
|
||||
clientValues func(c *Config, t ClientType) Values
|
||||
}
|
||||
|
||||
// Init initializes the registered extensions.
|
||||
func (ext Extensions) Init(c *Config) {
|
||||
extInit.Do(func() {
|
||||
for _, e := range ext {
|
||||
start := time.Now()
|
||||
|
||||
if err := e.init(c); err != nil {
|
||||
log.Warnf("config: %s in %s extension [%s]", err, clean.Log(e.name), time.Since(start))
|
||||
} else {
|
||||
log.Infof("config: %s extension loaded [%s]", clean.Log(e.name), time.Since(start))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
|
@ -30,7 +30,7 @@ func (m *Session) SignIn(f form.Login, c *gin.Context) (err error) {
|
|||
if user == nil {
|
||||
message := "account not found"
|
||||
event.AuditWarn([]string{m.IP(), "session %s", "login as %s", message}, m.RefID, clean.LogQuote(name))
|
||||
event.LoginError(m.IP(), name, m.UserAgent, message)
|
||||
event.LoginError(m.IP(), "api", name, m.UserAgent, message)
|
||||
m.Status = http.StatusUnauthorized
|
||||
return i18n.Error(i18n.ErrInvalidCredentials)
|
||||
}
|
||||
|
@ -39,7 +39,7 @@ func (m *Session) SignIn(f form.Login, c *gin.Context) (err error) {
|
|||
if !user.LoginAllowed() {
|
||||
message := "account disabled"
|
||||
event.AuditWarn([]string{m.IP(), "session %s", "login as %s", message}, m.RefID, clean.LogQuote(name))
|
||||
event.LoginError(m.IP(), name, m.UserAgent, message)
|
||||
event.LoginError(m.IP(), "api", name, m.UserAgent, message)
|
||||
m.Status = http.StatusUnauthorized
|
||||
return i18n.Error(i18n.ErrInvalidCredentials)
|
||||
}
|
||||
|
@ -48,12 +48,12 @@ func (m *Session) SignIn(f form.Login, c *gin.Context) (err error) {
|
|||
if user.InvalidPassword(f.Password) {
|
||||
message := "incorrect password"
|
||||
event.AuditErr([]string{m.IP(), "session %s", "login as %s", message}, m.RefID, clean.LogQuote(name))
|
||||
event.LoginError(m.IP(), name, m.UserAgent, message)
|
||||
event.LoginError(m.IP(), "api", name, m.UserAgent, message)
|
||||
m.Status = http.StatusUnauthorized
|
||||
return i18n.Error(i18n.ErrInvalidCredentials)
|
||||
} else {
|
||||
event.AuditInfo([]string{m.IP(), "session %s", "login as %s", "succeeded"}, m.RefID, clean.LogQuote(name))
|
||||
event.LoginSuccess(m.IP(), name, m.UserAgent)
|
||||
event.LoginSuccess(m.IP(), "api", name, m.UserAgent)
|
||||
}
|
||||
|
||||
m.SetUser(user)
|
||||
|
@ -77,7 +77,7 @@ func (m *Session) SignIn(f form.Login, c *gin.Context) (err error) {
|
|||
return i18n.Error(i18n.ErrUnexpected)
|
||||
} else if shares := data.RedeemToken(f.AuthToken); shares == 0 {
|
||||
event.AuditWarn([]string{m.IP(), "session %s", "share token %s is invalid"}, m.RefID, clean.LogQuote(f.AuthToken))
|
||||
event.LoginError(m.IP(), "", m.UserAgent, "invalid share token")
|
||||
event.LoginError(m.IP(), "api", "", m.UserAgent, "invalid share token")
|
||||
m.Status = http.StatusNotFound
|
||||
return i18n.Error(i18n.ErrInvalidLink)
|
||||
} else {
|
||||
|
|
|
@ -7,23 +7,24 @@ import (
|
|||
)
|
||||
|
||||
// LoginData returns a login event message.
|
||||
func LoginData(level logrus.Level, ip, username, useragent, error string) Data {
|
||||
func LoginData(level logrus.Level, ip, realm, name, browser, message string) Data {
|
||||
return Data{
|
||||
"time": TimeStamp(),
|
||||
"level": level.String(),
|
||||
"ip": txt.Clip(ip, txt.ClipIP),
|
||||
"message": txt.Clip(error, txt.ClipLog),
|
||||
"username": txt.Clip(username, txt.ClipUserName),
|
||||
"useragent": txt.Clip(useragent, txt.ClipLog),
|
||||
"realm": txt.Clip(realm, txt.ClipRealm),
|
||||
"name": txt.Clip(name, txt.ClipUserName),
|
||||
"browser": txt.Clip(browser, txt.ClipLog),
|
||||
"message": txt.Clip(message, txt.ClipLog),
|
||||
}
|
||||
}
|
||||
|
||||
// LoginSuccess publishes a successful login event.
|
||||
func LoginSuccess(ip, username, useragent string) {
|
||||
Publish("audit.login", LoginData(logrus.InfoLevel, ip, username, useragent, ""))
|
||||
func LoginSuccess(ip, realm, name, browser string) {
|
||||
Publish("audit.login", LoginData(logrus.InfoLevel, ip, realm, name, browser, ""))
|
||||
}
|
||||
|
||||
// LoginError publishes a login error event.
|
||||
func LoginError(ip, username, useragent, error string) {
|
||||
Publish("audit.login", LoginData(logrus.ErrorLevel, ip, username, useragent, error))
|
||||
func LoginError(ip, realm, name, browser, error string) {
|
||||
Publish("audit.login", LoginData(logrus.ErrorLevel, ip, realm, name, browser, error))
|
||||
}
|
||||
|
|
|
@ -76,23 +76,23 @@ func BasicAuth() gin.HandlerFunc {
|
|||
message := "account not found"
|
||||
|
||||
event.AuditWarn([]string{api.ClientIP(c), "webdav login as %s", message}, clean.LogQuote(name))
|
||||
event.LoginError(api.ClientIP(c), name, api.UserAgent(c), message)
|
||||
event.LoginError(api.ClientIP(c), "webdav", name, api.UserAgent(c), message)
|
||||
} else if !user.SyncAllowed() {
|
||||
// Sync disabled for this account.
|
||||
message := "sync disabled"
|
||||
|
||||
event.AuditWarn([]string{api.ClientIP(c), "webdav login as %s", message}, clean.LogQuote(name))
|
||||
event.LoginError(api.ClientIP(c), name, api.UserAgent(c), message)
|
||||
event.LoginError(api.ClientIP(c), "webdav", name, api.UserAgent(c), message)
|
||||
} else if valid = !user.InvalidPassword(password); !valid {
|
||||
// Wrong password.
|
||||
message := "incorrect password"
|
||||
|
||||
event.AuditErr([]string{api.ClientIP(c), "webdav login as %s", message}, clean.LogQuote(name))
|
||||
event.LoginError(api.ClientIP(c), name, api.UserAgent(c), message)
|
||||
event.LoginError(api.ClientIP(c), "webdav", name, api.UserAgent(c), message)
|
||||
} else {
|
||||
// Successfully authenticated.
|
||||
event.AuditInfo([]string{api.ClientIP(c), "webdav login as %s", "succeeded"}, clean.LogQuote(name))
|
||||
event.LoginSuccess(api.ClientIP(c), name, api.UserAgent(c))
|
||||
event.LoginSuccess(api.ClientIP(c), "webdav", name, api.UserAgent(c))
|
||||
|
||||
// Cache successful authentication.
|
||||
basicAuthCache.SetDefault(key, user)
|
||||
|
|
58
internal/server/extensions.go
Normal file
58
internal/server/extensions.go
Normal file
|
@ -0,0 +1,58 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
"github.com/photoprism/photoprism/pkg/clean"
|
||||
)
|
||||
|
||||
var (
|
||||
extInit sync.Once
|
||||
extMutex sync.Mutex
|
||||
extensions atomic.Value
|
||||
)
|
||||
|
||||
// Register registers a new package extension.
|
||||
func Register(name string, init func(router *gin.Engine, conf *config.Config) error) {
|
||||
extMutex.Lock()
|
||||
h, _ := extensions.Load().(Extensions)
|
||||
extensions.Store(append(h, Extension{name: name, init: init}))
|
||||
extMutex.Unlock()
|
||||
}
|
||||
|
||||
// Ext returns all registered package extensions.
|
||||
func Ext() (ext Extensions) {
|
||||
extMutex.Lock()
|
||||
ext, _ = extensions.Load().(Extensions)
|
||||
extMutex.Unlock()
|
||||
return ext
|
||||
}
|
||||
|
||||
// Extension represents a named package extension with callbacks.
|
||||
type Extension struct {
|
||||
name string
|
||||
init func(router *gin.Engine, conf *config.Config) error
|
||||
}
|
||||
|
||||
// Extensions represents a list of package extensions.
|
||||
type Extensions []Extension
|
||||
|
||||
// Init initializes the registered extensions.
|
||||
func (ext Extensions) Init(router *gin.Engine, conf *config.Config) {
|
||||
extInit.Do(func() {
|
||||
for _, e := range ext {
|
||||
start := time.Now()
|
||||
|
||||
if err := e.init(router, conf); err != nil {
|
||||
log.Warnf("server: %s in %s extension [%s]", err, clean.Log(e.name), time.Since(start))
|
||||
} else {
|
||||
log.Infof("server: %s extension loaded [%s]", clean.Log(e.name), time.Since(start))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
6
internal/server/header/default.go
Normal file
6
internal/server/header/default.go
Normal file
|
@ -0,0 +1,6 @@
|
|||
package header
|
||||
|
||||
var (
|
||||
DefaultContentSecurityPolicy = "frame-ancestors 'none';"
|
||||
DefaultFrameOptions = "DENY"
|
||||
)
|
|
@ -1,5 +1,5 @@
|
|||
/*
|
||||
Package server provides REST and web server routing, request handling and logging.
|
||||
Package header provides common response header names and default values.
|
||||
|
||||
Copyright (c) 2018 - 2022 PhotoPrism UG. All rights reserved.
|
||||
|
||||
|
@ -22,4 +22,4 @@ want to support our work, or just want to say hello.
|
|||
Additional information can be found in our Developer Guide:
|
||||
<https://docs.photoprism.app/developer-guide/>
|
||||
*/
|
||||
package server
|
||||
package header
|
12
internal/server/header/security.go
Normal file
12
internal/server/header/security.go
Normal file
|
@ -0,0 +1,12 @@
|
|||
package header
|
||||
|
||||
const (
|
||||
ContentSecurityPolicy = "Content-Security-Policy" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
|
||||
StrictTransportSecurity = "Strict-Transport-Security" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
|
||||
CrossOriginOpenerPolicy = "Cross-Origin-Opener-Policy" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy
|
||||
ReferrerPolicy = "Referrer-Policy" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy
|
||||
ContentTypeOptions = "X-Content-Type-Options" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
|
||||
XSSProtection = "X-XSS-Protection" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection
|
||||
FrameOptions = "X-Frame-Options" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
|
||||
ForwardedProto = "X-Forwarded-Proto" // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-Proto
|
||||
)
|
|
@ -3,13 +3,11 @@ package server
|
|||
import (
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/internal/api"
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
"github.com/photoprism/photoprism/pkg/clean"
|
||||
)
|
||||
|
||||
func registerRoutes(router *gin.Engine, conf *config.Config) {
|
||||
|
@ -206,17 +204,6 @@ func registerRoutes(router *gin.Engine, conf *config.Config) {
|
|||
}
|
||||
}
|
||||
|
||||
// Initialize package extensions.
|
||||
for _, ext := range Extensions() {
|
||||
start := time.Now()
|
||||
|
||||
if err := ext.init(router, conf); err != nil {
|
||||
log.Warnf("server: %s in %s extension[%s]", err, clean.Log(ext.name), time.Since(start))
|
||||
} else {
|
||||
log.Debugf("server: %s extension loaded [%s]", clean.Log(ext.name), time.Since(start))
|
||||
}
|
||||
}
|
||||
|
||||
// Default HTML page for client-side rendering and routing via VueJS.
|
||||
router.NoRoute(func(c *gin.Context) {
|
||||
signUp := gin.H{"message": config.MsgSponsor, "url": config.SignUpURL}
|
||||
|
|
|
@ -1,180 +1,16 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/pkg/clean"
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
"github.com/photoprism/photoprism/internal/server/header"
|
||||
)
|
||||
|
||||
const (
|
||||
stsHeader = "Strict-Transport-Security"
|
||||
stsSubdomainString = "; includeSubdomains"
|
||||
frameOptionsHeader = "X-Frame-Options"
|
||||
frameOptionsValue = "DENY"
|
||||
contentTypeHeader = "X-Content-Type-Options"
|
||||
contentTypeValue = "nosniff"
|
||||
xssProtectionHeader = "X-XSS-Protection"
|
||||
xssProtectionValue = "1; mode=block"
|
||||
cspHeader = "Content-Security-Policy"
|
||||
)
|
||||
|
||||
func defaultBadHostHandler(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "Bad Host", http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
// SecurityOptions is a struct for specifying configuration options for the HTTP security middleware.
|
||||
type SecurityOptions struct {
|
||||
// AllowedHosts is a list of fully qualified domain names that are allowed. Default is empty list, which allows any and all host names.
|
||||
AllowedHosts []string
|
||||
// If SSLRedirect is set to true, then only allow https requests. Default is false.
|
||||
SSLRedirect bool
|
||||
// If SSLTemporaryRedirect is true, a 302 will be used while redirecting. Default is false (301).
|
||||
SSLTemporaryRedirect bool
|
||||
// SSLHost is the host name that is used to redirect http requests to https. Default is "", which indicates to use the same host.
|
||||
SSLHost string
|
||||
// SSLProxyHeaders is set of header keys with associated values that would indicate a valid https request. Useful when using Nginx: `map[string]string{"X-Forwarded-Proto": "https"}`. Default is blank map.
|
||||
SSLProxyHeaders map[string]string
|
||||
// STSSeconds is the max-age of the Strict-Transport-Security header. Default is 0, which would NOT include the header.
|
||||
STSSeconds int64
|
||||
// If STSIncludeSubdomains is set to true, the `includeSubdomains` will be appended to the Strict-Transport-Security header. Default is false.
|
||||
STSIncludeSubdomains bool
|
||||
// If FrameDeny is set to true, adds the X-Frame-Options header with the value of `DENY`. Default is false.
|
||||
FrameDeny bool
|
||||
// CustomFrameOptionsValue allows the X-Frame-Options header value to be set with a custom value. This overrides the FrameDeny option.
|
||||
CustomFrameOptionsValue string
|
||||
// If ContentTypeNosniff is true, adds the X-Content-Type-Options header with the value `nosniff`. Default is false.
|
||||
ContentTypeNosniff bool
|
||||
// If BrowserXssFilter is true, adds the X-XSS-Protection header with the value `1; mode=block`. Default is false.
|
||||
BrowserXssFilter bool
|
||||
// ContentSecurityPolicy allows the Content-Security-Policy header value to be set with a custom value. Default is "".
|
||||
ContentSecurityPolicy string
|
||||
// When developing, the AllowedHosts, SSL, and STS options can cause some unwanted effects. Usually testing happens on http, not https, and on localhost, not your production domain... so set this to true for dev environment.
|
||||
// If you would like your development environment to mimic production with complete Host blocking, SSL redirects, and STS headers, leave this as false. Default if false.
|
||||
IsDevelopment bool
|
||||
|
||||
// Handlers for when an error occurs (ie bad host).
|
||||
BadHostHandler http.Handler
|
||||
}
|
||||
|
||||
// security is an HTTP middleware that enables basic security features. A single SecurityOptions struct can be
|
||||
// provided to configure which features should be enabled, and the ability to override a few of the default values.
|
||||
// Code is based on https://github.com/gin-gonic/contrib/tree/master/secure released under the MIT license:
|
||||
// https://github.com/gin-gonic/contrib/blob/master/LICENSE
|
||||
type security struct {
|
||||
// Customize with an SecurityOptions struct.
|
||||
opt SecurityOptions
|
||||
}
|
||||
|
||||
// process handles an HTTP request.
|
||||
func (s *security) process(w http.ResponseWriter, r *http.Request) error {
|
||||
// Allowed hosts check.
|
||||
if len(s.opt.AllowedHosts) > 0 && !s.opt.IsDevelopment {
|
||||
isGoodHost := false
|
||||
for _, allowedHost := range s.opt.AllowedHosts {
|
||||
if strings.EqualFold(allowedHost, r.Host) {
|
||||
isGoodHost = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !isGoodHost {
|
||||
s.opt.BadHostHandler.ServeHTTP(w, r)
|
||||
return fmt.Errorf("server: bad host %s", clean.Log(r.Host))
|
||||
}
|
||||
}
|
||||
|
||||
// SSL check.
|
||||
if s.opt.SSLRedirect && s.opt.IsDevelopment == false {
|
||||
isSSL := false
|
||||
if strings.EqualFold(r.URL.Scheme, "https") || r.TLS != nil {
|
||||
isSSL = true
|
||||
} else {
|
||||
for k, v := range s.opt.SSLProxyHeaders {
|
||||
if r.Header.Get(k) == v {
|
||||
isSSL = true
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if isSSL == false {
|
||||
url := r.URL
|
||||
url.Scheme = "https"
|
||||
url.Host = r.Host
|
||||
|
||||
if len(s.opt.SSLHost) > 0 {
|
||||
url.Host = s.opt.SSLHost
|
||||
}
|
||||
|
||||
status := http.StatusMovedPermanently
|
||||
if s.opt.SSLTemporaryRedirect {
|
||||
status = http.StatusTemporaryRedirect
|
||||
}
|
||||
|
||||
http.Redirect(w, r, url.String(), status)
|
||||
return fmt.Errorf("server: https redirect")
|
||||
}
|
||||
}
|
||||
|
||||
// Strict Transport Security header.
|
||||
if s.opt.STSSeconds != 0 && !s.opt.IsDevelopment {
|
||||
stsSub := ""
|
||||
if s.opt.STSIncludeSubdomains {
|
||||
stsSub = stsSubdomainString
|
||||
}
|
||||
|
||||
w.Header().Add(stsHeader, fmt.Sprintf("max-age=%d%s", s.opt.STSSeconds, stsSub))
|
||||
}
|
||||
|
||||
// Frame Options header.
|
||||
if len(s.opt.CustomFrameOptionsValue) > 0 {
|
||||
w.Header().Add(frameOptionsHeader, s.opt.CustomFrameOptionsValue)
|
||||
} else if s.opt.FrameDeny {
|
||||
w.Header().Add(frameOptionsHeader, frameOptionsValue)
|
||||
}
|
||||
|
||||
// Content Type Options header.
|
||||
if s.opt.ContentTypeNosniff {
|
||||
w.Header().Add(contentTypeHeader, contentTypeValue)
|
||||
}
|
||||
|
||||
// XSS Protection header.
|
||||
if s.opt.BrowserXssFilter {
|
||||
w.Header().Add(xssProtectionHeader, xssProtectionValue)
|
||||
}
|
||||
|
||||
// Content Security Policy header.
|
||||
if len(s.opt.ContentSecurityPolicy) > 0 {
|
||||
w.Header().Add(cspHeader, s.opt.ContentSecurityPolicy)
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
}
|
||||
|
||||
// Security registers the HTTP security middleware.
|
||||
func Security(options SecurityOptions) gin.HandlerFunc {
|
||||
if options.BadHostHandler == nil {
|
||||
options.BadHostHandler = http.HandlerFunc(defaultBadHostHandler)
|
||||
}
|
||||
|
||||
s := &security{
|
||||
opt: options,
|
||||
}
|
||||
|
||||
// Security adds common HTTP security headers to the response.
|
||||
var Security = func(conf *config.Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
err := s.process(c.Writer, c.Request)
|
||||
if err != nil {
|
||||
if c.Writer.Written() {
|
||||
c.AbortWithStatus(c.Writer.Status())
|
||||
} else {
|
||||
_ = c.AbortWithError(http.StatusInternalServerError, err)
|
||||
c.Writer.Header().Set(header.ContentSecurityPolicy, header.DefaultContentSecurityPolicy)
|
||||
c.Writer.Header().Set(header.FrameOptions, header.DefaultFrameOptions)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,104 +1,25 @@
|
|||
/*
|
||||
Package server provides REST and web server routing, request handling and logging.
|
||||
|
||||
Copyright (c) 2018 - 2022 PhotoPrism UG. All rights reserved.
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under Version 3 of the GNU Affero General Public License (the "AGPL"):
|
||||
<https://docs.photoprism.app/license/agpl>
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
The AGPL is supplemented by our Trademark and Brand Guidelines,
|
||||
which describe how our Brand Assets may be used:
|
||||
<https://photoprism.app/trademark>
|
||||
|
||||
Feel free to send an email to hello@photoprism.app if you have questions,
|
||||
want to support our work, or just want to say hello.
|
||||
|
||||
Additional information can be found in our Developer Guide:
|
||||
<https://docs.photoprism.app/developer-guide/>
|
||||
*/
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
"github.com/photoprism/photoprism/internal/event"
|
||||
)
|
||||
|
||||
var log = event.Log
|
||||
|
||||
// Start the REST API server using the configuration provided
|
||||
func Start(ctx context.Context, conf *config.Config) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
// Set HTTP server mode.
|
||||
if conf.HttpMode() != "" {
|
||||
gin.SetMode(conf.HttpMode())
|
||||
} else if conf.Debug() == false {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
// Create new HTTP router engine without standard middleware.
|
||||
router := gin.New()
|
||||
|
||||
// Register logger middleware.
|
||||
router.Use(Logger(), Recovery())
|
||||
|
||||
// Register security middleware.
|
||||
router.Use(Security(SecurityOptions{
|
||||
IsDevelopment: gin.Mode() != gin.ReleaseMode || conf.Test(),
|
||||
AllowedHosts: []string{},
|
||||
SSLRedirect: false,
|
||||
SSLHost: "",
|
||||
SSLProxyHeaders: map[string]string{"X-Forwarded-Proto": "https"},
|
||||
STSSeconds: 0,
|
||||
STSIncludeSubdomains: false,
|
||||
FrameDeny: true,
|
||||
ContentTypeNosniff: false,
|
||||
BrowserXssFilter: false,
|
||||
ContentSecurityPolicy: "frame-ancestors 'none';",
|
||||
}))
|
||||
|
||||
// Enable HTTP compression?
|
||||
switch conf.HttpCompression() {
|
||||
case "gzip":
|
||||
log.Infof("server: enabling gzip compression")
|
||||
router.Use(gzip.Gzip(
|
||||
gzip.DefaultCompression,
|
||||
gzip.WithExcludedPaths([]string{
|
||||
conf.BaseUri(config.ApiUri + "/t"),
|
||||
conf.BaseUri(config.ApiUri + "/folders/t"),
|
||||
conf.BaseUri(config.ApiUri + "/zip"),
|
||||
conf.BaseUri(config.ApiUri + "/albums"),
|
||||
conf.BaseUri(config.ApiUri + "/labels"),
|
||||
conf.BaseUri(config.ApiUri + "/videos"),
|
||||
})))
|
||||
}
|
||||
|
||||
// Find and load templates.
|
||||
router.LoadHTMLFiles(conf.TemplateFiles()...)
|
||||
|
||||
// Register HTTP route handlers.
|
||||
registerRoutes(router, conf)
|
||||
|
||||
// Create new HTTP server instance.
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%d", conf.HttpHost(), conf.HttpPort()),
|
||||
Handler: router,
|
||||
}
|
||||
|
||||
// Start HTTP server.
|
||||
go func() {
|
||||
log.Infof("server: listening on %s [%s]", server.Addr, time.Since(start))
|
||||
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
if err == http.ErrServerClosed {
|
||||
log.Info("server: shutdown complete")
|
||||
} else {
|
||||
log.Errorf("server: %s", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Graceful HTTP server shutdown.
|
||||
<-ctx.Done()
|
||||
log.Info("server: shutting down")
|
||||
err := server.Close()
|
||||
if err != nil {
|
||||
log.Errorf("server: shutdown failed (%s)", err)
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,37 +0,0 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
)
|
||||
|
||||
var (
|
||||
extMutex sync.Mutex
|
||||
extensions atomic.Value
|
||||
)
|
||||
|
||||
// Extension represents a named package extension with callbacks.
|
||||
type Extension struct {
|
||||
name string
|
||||
init func(router *gin.Engine, conf *config.Config) error
|
||||
}
|
||||
|
||||
// Register registers a new package extension.
|
||||
func Register(name string, init func(router *gin.Engine, conf *config.Config) error) {
|
||||
extMutex.Lock()
|
||||
h, _ := extensions.Load().([]Extension)
|
||||
extensions.Store(append(h, Extension{name, init}))
|
||||
extMutex.Unlock()
|
||||
}
|
||||
|
||||
// Extensions returns all registered package extensions.
|
||||
func Extensions() (ext []Extension) {
|
||||
extMutex.Lock()
|
||||
ext, _ = extensions.Load().([]Extension)
|
||||
extMutex.Unlock()
|
||||
return ext
|
||||
}
|
92
internal/server/start.go
Normal file
92
internal/server/start.go
Normal file
|
@ -0,0 +1,92 @@
|
|||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/photoprism/photoprism/internal/config"
|
||||
"github.com/photoprism/photoprism/internal/event"
|
||||
)
|
||||
|
||||
var log = event.Log
|
||||
|
||||
// Start the REST API server using the configuration provided
|
||||
func Start(ctx context.Context, conf *config.Config) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
log.Error(err)
|
||||
}
|
||||
}()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
// Set HTTP server mode.
|
||||
if conf.HttpMode() != "" {
|
||||
gin.SetMode(conf.HttpMode())
|
||||
} else if conf.Debug() == false {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
}
|
||||
|
||||
// Create new HTTP router engine without standard middleware.
|
||||
router := gin.New()
|
||||
|
||||
// Register common middleware.
|
||||
router.Use(Logger(), Recovery(), Security(conf))
|
||||
|
||||
// Initialize package extensions.
|
||||
Ext().Init(router, conf)
|
||||
|
||||
// Enable HTTP compression?
|
||||
switch conf.HttpCompression() {
|
||||
case "gzip":
|
||||
log.Infof("server: enabling gzip compression")
|
||||
router.Use(gzip.Gzip(
|
||||
gzip.DefaultCompression,
|
||||
gzip.WithExcludedPaths([]string{
|
||||
conf.BaseUri(config.ApiUri + "/t"),
|
||||
conf.BaseUri(config.ApiUri + "/folders/t"),
|
||||
conf.BaseUri(config.ApiUri + "/zip"),
|
||||
conf.BaseUri(config.ApiUri + "/albums"),
|
||||
conf.BaseUri(config.ApiUri + "/labels"),
|
||||
conf.BaseUri(config.ApiUri + "/videos"),
|
||||
})))
|
||||
}
|
||||
|
||||
// Find and load templates.
|
||||
router.LoadHTMLFiles(conf.TemplateFiles()...)
|
||||
|
||||
// Register HTTP route handlers.
|
||||
registerRoutes(router, conf)
|
||||
|
||||
// Create new HTTP server instance.
|
||||
server := &http.Server{
|
||||
Addr: fmt.Sprintf("%s:%d", conf.HttpHost(), conf.HttpPort()),
|
||||
Handler: router,
|
||||
}
|
||||
|
||||
// Start HTTP server.
|
||||
go func() {
|
||||
log.Infof("server: listening on %s [%s]", server.Addr, time.Since(start))
|
||||
|
||||
if err := server.ListenAndServe(); err != nil {
|
||||
if err == http.ErrServerClosed {
|
||||
log.Info("server: shutdown complete")
|
||||
} else {
|
||||
log.Errorf("server: %s", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Graceful HTTP server shutdown.
|
||||
<-ctx.Done()
|
||||
log.Info("server: shutting down")
|
||||
err := server.Close()
|
||||
if err != nil {
|
||||
log.Errorf("server: shutdown failed (%s)", err)
|
||||
}
|
||||
}
|
|
@ -9,6 +9,7 @@ const (
|
|||
ClipRole = 32
|
||||
ClipKeyword = 40
|
||||
ClipIP = 48
|
||||
ClipRealm = 64
|
||||
ClipUserName = 64
|
||||
ClipSlug = 80
|
||||
ClipCategory = 100
|
||||
|
|
Loading…
Reference in a new issue