Commit 3186a01b authored by Nicolas Pernoud's avatar Nicolas Pernoud
Browse files

refactor : replace http error codes by the corresponding enum values

parent 4d5829d6
Pipeline #12454 passed with stages
in 2 minutes and 33 seconds
......@@ -26,13 +26,13 @@ func CreateMockOAuth2() *http.ServeMux {
mux.HandleFunc("/auth", func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
redir := query.Get("redirect_uri") + "?state=" + query.Get("state") + "&code=mock_code"
http.Redirect(w, r, redir, 302)
http.Redirect(w, r, redir, http.StatusFound)
})
// Returns authorization code back to the user, but without the provided state
mux.HandleFunc("/auth-wrong-state", func(w http.ResponseWriter, r *http.Request) {
query := r.URL.Query()
redir := query.Get("redirect_uri") + "?state=" + "a-random-state" + "&code=mock_code"
http.Redirect(w, r, redir, 302)
http.Redirect(w, r, redir, http.StatusFound)
})
// Returns access token back to the user
......
......@@ -60,14 +60,14 @@ func CreateRootMux(port int, appsFile string, davsFile string, staticDir string)
appServer.ProcessApps(w, req)
return
}
http.Error(w, "method not allowed", 405)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
})
commonMux.HandleFunc("/davs", func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodGet {
davServer.ProcessDavs(w, req)
return
}
http.Error(w, "method not allowed", 405)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
})
mainMux.Handle("/api/common/WhoAmI", auth.ValidateAuthMiddleware(auth.WhoAmI(), []string{"*"}, false))
commonMux.HandleFunc("/Share", auth.GetShareToken)
......@@ -122,11 +122,11 @@ func reload(adh *appDavHandler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
err := adh.as.LoadApps()
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
}
err = adh.ds.LoadDavs()
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
} else {
fmt.Fprintf(w, "apps and davs services reloaded")
}
......
This diff is collapsed.
......@@ -64,13 +64,13 @@ func TestServer(t *testing.T) {
code int
body string
}{
{"http://test.proxy/", nil, 200, "OK"},
{"http://foo.test.proxy/", nil, 404, "Not found."},
{"http://footest.proxy/", nil, 404, "Not found."},
{"http://test.wildcard/", nil, 200, "OK"},
{"http://foo.test.wildcard/", nil, 200, "OK"},
{"http://test.static/", nil, 200, "contents of index.html"},
{"http://test.net/", nil, 404, "Not found."},
{"http://test.proxy/", nil, http.StatusOK, "OK"},
{"http://foo.test.proxy/", nil, http.StatusNotFound, "Not found."},
{"http://footest.proxy/", nil, http.StatusNotFound, "Not found."},
{"http://test.wildcard/", nil, http.StatusOK, "OK"},
{"http://foo.test.wildcard/", nil, http.StatusOK, "OK"},
{"http://test.static/", nil, http.StatusOK, "contents of index.html"},
{"http://test.net/", nil, http.StatusNotFound, "Not found."},
}
// Run tests
......@@ -84,9 +84,9 @@ func TestServer(t *testing.T) {
code int
location string
}{
{"http://test.fwdtoredirect", 302, "https://test.fwdtoredirect:443/some/path"},
{"http://test.relativeredirect/", 302, "https://relative.redirect.test.relativeredirect"},
{"http://test.absoluteredirect/", 302, "https://absolute.redirect"},
{"http://test.fwdtoredirect", http.StatusFound, "https://test.fwdtoredirect:443/some/path"},
{"http://test.relativeredirect/", http.StatusFound, "https://relative.redirect.test.relativeredirect"},
{"http://test.absoluteredirect/", http.StatusFound, "https://absolute.redirect"},
}
// Run redirect tests
......
......@@ -53,7 +53,7 @@ func (s *Server) ProcessApps(w http.ResponseWriter, req *http.Request) {
case "DELETE":
s.DeleteApp(w, req)
default:
http.Error(w, "method not allowed", 400)
http.Error(w, "method not allowed", http.StatusBadRequest)
}
}
......@@ -62,7 +62,7 @@ func (s *Server) SendApps(w http.ResponseWriter, req *http.Request) {
var apps []App
err := common.Load(s.file, &apps)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(apps)
......@@ -73,17 +73,17 @@ func (s *Server) AddApp(w http.ResponseWriter, req *http.Request) {
var apps []App
err := common.Load(s.file, &apps)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Body == nil {
http.Error(w, "please send a request body", 400)
http.Error(w, "please send a request body", http.StatusBadRequest)
return
}
var newApp App
err = json.NewDecoder(req.Body).Decode(&newApp)
if _, ok := err.(*json.UnmarshalTypeError); !ok && err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Add the app only if the id doesn't exists yet
......@@ -101,7 +101,7 @@ func (s *Server) AddApp(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(s.file, &apps)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.SendApps(w, req)
......@@ -112,13 +112,13 @@ func (s *Server) DeleteApp(w http.ResponseWriter, req *http.Request) {
var apps []App
err := common.Load(s.file, &apps)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pathElements := strings.Split(req.URL.Path, "/")
idx, err := strconv.Atoi(pathElements[len(pathElements)-1])
if err != nil {
http.Error(w, "please provide an app index", 400)
http.Error(w, "please provide an app index", http.StatusBadRequest)
return
}
// Add the app only if the name doesn't exists yet
......@@ -130,7 +130,7 @@ func (s *Server) DeleteApp(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(s.file, &newApps)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.SendApps(w, req)
......
......@@ -69,7 +69,7 @@ func ValidateAuthMiddleware(next http.Handler, allowedRoles []string, checkXSRF
user, err = getUserDirectly(r.Header.Get("Authorization"))
if err != nil {
w.Header().Set("WWW-Authenticate", `Basic realm="server"`)
http.Error(w, "webdav client authentication", 401)
http.Error(w, "webdav client authentication", http.StatusUnauthorized)
return
}
}
......@@ -93,12 +93,12 @@ func ValidateAuthMiddleware(next http.Handler, allowedRoles []string, checkXSRF
}
// Check XSRF Token
if checkXSRF && r.Header.Get("XSRF-TOKEN") != user.XSRFToken {
http.Error(w, "XSRF protection triggered", 401)
http.Error(w, "XSRF protection triggered", http.StatusUnauthorized)
return
}
err = checkUserHasRole(user, allowedRoles)
if err != nil {
http.Error(w, err.Error(), 403)
http.Error(w, err.Error(), http.StatusForbidden)
return
}
err = checkUserHasRole(user, []string{AdminRole})
......@@ -109,13 +109,13 @@ func ValidateAuthMiddleware(next http.Handler, allowedRoles []string, checkXSRF
if user.URL != "" {
requestURL := strings.Split(r.Host, ":")[0] + r.URL.EscapedPath()
if user.URL != requestURL {
http.Error(w, "token restricted to url: "+user.URL, 401)
http.Error(w, "token restricted to url: "+user.URL, http.StatusUnauthorized)
return
}
}
// Check for method
if user.ReadOnly && r.Method != http.MethodGet {
http.Error(w, "token is read only", 403)
http.Error(w, "token is read only", http.StatusForbidden)
return
}
ctx := context.WithValue(r.Context(), ContextData, user)
......@@ -141,7 +141,7 @@ func WhoAmI() http.Handler {
whoAmI := func(w http.ResponseWriter, r *http.Request) {
user, err := GetTokenData(r)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(user)
......@@ -168,12 +168,12 @@ func checkUserHasRole(user TokenData, allowedRoles []string) error {
func GetShareToken(w http.ResponseWriter, r *http.Request) {
user, err := GetTokenData(r)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var wantedToken struct {
......@@ -184,11 +184,11 @@ func GetShareToken(w http.ResponseWriter, r *http.Request) {
}
err = json.NewDecoder(r.Body).Decode(&wantedToken)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if wantedToken.URL == "" {
http.Error(w, "url cannot be empty", 400)
http.Error(w, "url cannot be empty", http.StatusBadRequest)
return
}
user.Login = user.Login + "_share_for_" + wantedToken.Sharedfor
......@@ -197,7 +197,7 @@ func GetShareToken(w http.ResponseWriter, r *http.Request) {
user.SharingUserLogin = wantedToken.Sharedfor
token, err := tokens.Manager.CreateToken(user, time.Now().Add(time.Hour*time.Duration(24*wantedToken.Lifespan)))
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, token)
......
......@@ -46,19 +46,19 @@ func init() {
// HandleInMemoryLogin validate the username and password provided in the function body against a local file and return a token if the user is found
func (m Manager) HandleInMemoryLogin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", 405)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
var sentUser User
err := json.NewDecoder(r.Body).Decode(&sentUser)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Try to match the user with an user in the database
user, err := MatchUser(sentUser)
if err != nil {
http.Error(w, err.Error(), 403)
http.Error(w, err.Error(), http.StatusForbidden)
log.Logger.Printf("| %v | Login failure | %v | %v", sentUser.Login, r.RemoteAddr, log.GetCityAndCountryFromRequest(r))
return
}
......@@ -67,7 +67,7 @@ func (m Manager) HandleInMemoryLogin(w http.ResponseWriter, r *http.Request) {
// Generate
xsrfToken, err := common.GenerateRandomString(16)
if err != nil {
http.Error(w, "error generating XSRF Token", 500)
http.Error(w, "error generating XSRF Token", http.StatusInternalServerError)
return
}
tokenData := TokenData{User: User{ID: user.ID, Login: user.Login, Email: user.Email, Roles: user.Roles}, XSRFToken: xsrfToken}
......@@ -95,7 +95,7 @@ func ProcessUsers(w http.ResponseWriter, req *http.Request) {
DeleteUser(w, req)
refreshCache()
default:
http.Error(w, "method not allowed", 400)
http.Error(w, "method not allowed", http.StatusBadRequest)
}
}
......@@ -104,7 +104,7 @@ func SendUsers(w http.ResponseWriter, req *http.Request) {
var users []User
err := common.Load(UsersFile, &users)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
json.NewEncoder(w).Encode(users)
......@@ -115,28 +115,28 @@ func AddUser(w http.ResponseWriter, req *http.Request) {
var users []User
err := common.Load(UsersFile, &users)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Body == nil {
http.Error(w, "please send a request body", 400)
http.Error(w, "please send a request body", http.StatusBadRequest)
return
}
var newUser User
err = json.NewDecoder(req.Body).Decode(&newUser)
if _, ok := err.(*json.UnmarshalTypeError); !ok && err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Encrypt the password with bcrypt
if newUser.Password == "" && newUser.PasswordHash == "" {
http.Error(w, "passwords cannot be blank", 400)
http.Error(w, "passwords cannot be blank", http.StatusBadRequest)
return
}
if newUser.Password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(newUser.Password), bcrypt.DefaultCost)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
newUser.PasswordHash = string(hash)
......@@ -149,7 +149,7 @@ func AddUser(w http.ResponseWriter, req *http.Request) {
users[idx] = newUser
isNew = false
} else if val.Login == newUser.Login { // Check for already existing login
http.Error(w, "login already exists", 400)
http.Error(w, "login already exists", http.StatusBadRequest)
return
}
}
......@@ -159,7 +159,7 @@ func AddUser(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(UsersFile, &users)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
SendUsers(w, req)
......@@ -170,13 +170,13 @@ func DeleteUser(w http.ResponseWriter, req *http.Request) {
var users []User
err := common.Load(UsersFile, &users)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pathElements := strings.Split(req.URL.Path, "/")
idx, err := strconv.Atoi(pathElements[len(pathElements)-1])
if err != nil {
http.Error(w, "please provide an user index", 400)
http.Error(w, "please provide an user index", http.StatusBadRequest)
return
}
// Recreate the user list without the deleted user
......@@ -189,7 +189,7 @@ func DeleteUser(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(UsersFile, &newUsers)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
SendUsers(w, req)
......
......@@ -100,12 +100,12 @@ func (m Manager) HandleOAuth2Callback() http.Handler {
// Get user
var user User
if response.Body == nil {
http.Error(w, "no response body", 400)
http.Error(w, "no response body", http.StatusBadRequest)
return
}
err = json.NewDecoder(response.Body).Decode(&user)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Trim the user roles in case they come from LDAP
......@@ -116,7 +116,7 @@ func (m Manager) HandleOAuth2Callback() http.Handler {
// Generate
xsrfToken, err := common.GenerateRandomString(16)
if err != nil {
http.Error(w, "error generating XSRF Token", 500)
http.Error(w, "error generating XSRF Token", http.StatusInternalServerError)
return
}
tokenData := TokenData{User: user, XSRFToken: xsrfToken}
......
package davserver
import (
"net/http"
"net/http/httptest"
"net/url"
"strings"
......@@ -28,7 +29,7 @@ func TestEncryption(t *testing.T) {
t.Errorf("test-ciphered.txt should be 22 bytes")
}
// Try to access a non crypted file on a encrypted unsecured dav (must fail)
do("GET", "/test.txt", noH, "", 500, "unexpected EOF")
do("GET", "/test.txt", noH, "", http.StatusInternalServerError, "unexpected EOF")
// Try to access a crypted file with the wrong key
davAug = NewWebDavAug("", "./testdata", true, "wrong key")
body = do("GET", "/test-ciphered.txt", noH, "", 200, "")
......
......@@ -51,7 +51,7 @@ func (s *Server) ProcessDavs(w http.ResponseWriter, req *http.Request) {
case "DELETE":
s.DeleteDav(w, req)
default:
http.Error(w, "method not allowed", 400)
http.Error(w, "method not allowed", http.StatusBadRequest)
}
}
......@@ -60,13 +60,13 @@ func (s *Server) SendDavs(w http.ResponseWriter, req *http.Request) {
// Get user from request
user, err := auth.GetTokenData(req)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
var davs []Dav
err = common.Load(s.file, &davs)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
for i, dav := range davs {
......@@ -89,17 +89,17 @@ func (s *Server) AddDav(w http.ResponseWriter, req *http.Request) {
var davs []Dav
err := common.Load(s.file, &davs)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if req.Body == nil {
http.Error(w, "please send a request body", 400)
http.Error(w, "please send a request body", http.StatusBadRequest)
return
}
var newDav Dav
err = json.NewDecoder(req.Body).Decode(&newDav)
if _, ok := err.(*json.UnmarshalTypeError); !ok && err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Add the dav only if the id doesn't exists yet
......@@ -117,7 +117,7 @@ func (s *Server) AddDav(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(s.file, &davs)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.SendDavs(w, req)
......@@ -128,13 +128,13 @@ func (s *Server) DeleteDav(w http.ResponseWriter, req *http.Request) {
var davs []Dav
err := common.Load(s.file, &davs)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
pathElements := strings.Split(req.URL.Path, "/")
idx, err := strconv.Atoi(pathElements[len(pathElements)-1])
if err != nil {
http.Error(w, "please provide an dav index", 400)
http.Error(w, "please provide an dav index", http.StatusBadRequest)
return
}
// Add the dav only if the name doesn't exists yet
......@@ -146,7 +146,7 @@ func (s *Server) DeleteDav(w http.ResponseWriter, req *http.Request) {
}
err = common.Save(s.file, &newDavs)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
s.SendDavs(w, req)
......
......@@ -16,7 +16,7 @@ func HandleOpen(fullHostname string) func(w http.ResponseWriter, req *http.Reque
return func(w http.ResponseWriter, req *http.Request) {
t, err := template.ParseFiles("web/onlyoffice/index.tmpl")
if err != nil {
http.Error(w, "could not open onlyoffice template: "+err.Error(), 500)
http.Error(w, "could not open onlyoffice template: "+err.Error(), http.StatusInternalServerError)
return
}
title, _ := common.StringValueFromEnv("ONLYOFFICE_TITLE", "VestibuleOffice")
......@@ -33,11 +33,11 @@ func HandleOpen(fullHostname string) func(w http.ResponseWriter, req *http.Reque
// the body provides information on where to get the altered document, and the query provides information on where to put it
func HandleSaveCallback(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
http.Error(w, "the request method must be POST", 405)
http.Error(w, "the request method must be POST", http.StatusMethodNotAllowed)
return
}
if req.Body == nil {
http.Error(w, "the request must contain a body", 400)
http.Error(w, "the request must contain a body", http.StatusBadRequest)
return
}
var bdy struct {
......@@ -65,7 +65,7 @@ func HandleSaveCallback(w http.ResponseWriter, req *http.Request) {
}
jsonErr := json.NewDecoder(req.Body).Decode(&bdy)
if jsonErr != nil {
http.Error(w, jsonErr.Error(), 400)
http.Error(w, jsonErr.Error(), http.StatusBadRequest)
return
}
// Case of document closed after editing
......@@ -73,7 +73,7 @@ func HandleSaveCallback(w http.ResponseWriter, req *http.Request) {
// Get the binary content from url
resp, err := http.Get(bdy.URL)
if err != nil {
http.Error(w, "could not get connect to onlyoffice document server", 400)
http.Error(w, "could not get connect to onlyoffice document server", http.StatusBadRequest)
return
}
defer resp.Body.Close()
......@@ -83,7 +83,7 @@ func HandleSaveCallback(w http.ResponseWriter, req *http.Request) {
client := &http.Client{}
_, err = client.Do(req)
if err != nil {
http.Error(w, err.Error(), 400)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
......
......@@ -72,7 +72,7 @@ func (m manager) StoreData(data interface{}, hostName string, cookieName string,
expiration := now().Add(duration)
value, err := m.CreateToken(data, expiration)
if err != nil {
http.Error(w, err.Error(), 500)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
cookie := http.Cookie{Name: cookieName, Domain: hostName, Value: value, Expires: expiration, Secure: !m.debugMode, HttpOnly: true, SameSite: http.SameSiteLaxMode}
......
......@@ -32,7 +32,7 @@
<div class="navbar-brand">
<div class="navbar-item">
<a class="button is-primary is-rounded is-outlined" href="https://www.github.com/nicolaspernoud/Vestibule" target="_blank" rel="noopener noreferrer">
<span>4.5.1</span>
<span>4.5.2</span>
<span class="icon">
<svg
class="svg-inline--fa fa-github fa-w-16"
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment