Page Menu
Home
Musing Studio
Search
Configure Global Search
Log In
Files
F15045717
No One
Temporary
Actions
View File
Edit File
Delete File
View Transforms
Subscribe
Mute Notifications
Award Token
Flag For Later
Size
27 KB
Subscribers
None
View Options
diff --git a/csrf.go b/csrf.go
new file mode 100644
index 0000000..ab2b64b
--- /dev/null
+++ b/csrf.go
@@ -0,0 +1,95 @@
+/*
+ * Copyright © 2026 Musing Studio LLC.
+ *
+ * This file is part of WriteFreely.
+ *
+ * WriteFreely is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, included
+ * in the LICENSE file in this source code package.
+ */
+
+package writefreely
+
+import (
+ "net/http"
+ "net/url"
+ "strings"
+
+ "github.com/gorilla/csrf"
+ "github.com/writefreely/writefreely/config"
+)
+
+// newCSRFProtector returns CSRF middleware configured for this instance. All
+// CSRF-protected routes should use it rather than calling csrf.Protect
+// directly.
+//
+// Since v1.7.3, gorilla/csrf assumes every request is served over HTTPS: it
+// rejects http:// Origin and Referer headers unless the request has been
+// marked with csrf.PlaintextHTTPRequest. We mark requests from the configured
+// host rather than from how the request reached us, because TLS is often
+// terminated at a reverse proxy, so WriteFreely sees plain HTTP even when the
+// browser is on https://. Requests to a plain-HTTP instance (app.host is
+// http://) or to a plain-HTTP Tor hidden service (server.hidden_host) are
+// marked as plaintext. HTTPS instances get gorilla/csrf's defaults unchanged.
+func newCSRFProtector(cfg *config.Config, key []byte) func(http.Handler) http.Handler {
+ secureHost := strings.HasPrefix(cfg.App.Host, "https://")
+ hiddenHost := plaintextHiddenHost(cfg.Server.HiddenHost)
+
+ opts := []csrf.Option{
+ csrf.Path("/"),
+ // Match the session cookie (see InitSession). Browsers drop Secure
+ // cookies set over plain HTTP everywhere except localhost, so
+ // otherwise no form would work on a LAN or no-TLS instance.
+ csrf.Secure(secureHost),
+ }
+ if !secureHost {
+ // An http:// instance may still be reached over HTTPS through a
+ // proxy, or with a rewritten Host header, so trust an Origin header
+ // naming the configured host with either scheme.
+ if u, err := url.Parse(cfg.App.Host); err == nil && u.Host != "" {
+ opts = append(opts, csrf.TrustedOrigins([]string{u.Host}))
+ }
+ }
+ protect := csrf.Protect(key, opts...)
+
+ return func(next http.Handler) http.Handler {
+ protected := protect(next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.TLS == nil && (!secureHost || (hiddenHost != "" && strings.EqualFold(r.Host, hiddenHost))) {
+ r = csrf.PlaintextHTTPRequest(r)
+ }
+ protected.ServeHTTP(w, r)
+ })
+ }
+}
+
+// plaintextHiddenHost returns the host of the configured Tor hidden service if
+// it's served over plain HTTP, or "" if there isn't one or it uses HTTPS. A
+// value without a scheme is assumed to be plain HTTP.
+func plaintextHiddenHost(hiddenHost string) string {
+ if hiddenHost == "" || strings.HasPrefix(hiddenHost, "https://") {
+ return ""
+ }
+ if !strings.Contains(hiddenHost, "://") {
+ hiddenHost = "http://" + hiddenHost
+ }
+ u, err := url.Parse(hiddenHost)
+ if err != nil {
+ return ""
+ }
+ return u.Host
+}
+
+// csrfProtectForm wraps a handler with CSRF protection but exempts JSON
+// requests, which authenticate via Authorization header rather than
+// session cookies and are therefore not CSRF-exploitable.
+func csrfProtectForm(protect func(http.Handler) http.Handler, next http.Handler) http.Handler {
+ protected := protect(next)
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if IsJSON(r) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ protected.ServeHTTP(w, r)
+ })
+}
diff --git a/csrf_test.go b/csrf_test.go
new file mode 100644
index 0000000..52a264f
--- /dev/null
+++ b/csrf_test.go
@@ -0,0 +1,162 @@
+/*
+ * Copyright © 2026 Musing Studio LLC.
+ *
+ * This file is part of WriteFreely.
+ *
+ * WriteFreely is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License, included
+ * in the LICENSE file in this source code package.
+ */
+
+package writefreely
+
+import (
+ "bytes"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gorilla/csrf"
+ "github.com/writefreely/writefreely/config"
+)
+
+var testCSRFKey = bytes.Repeat([]byte("k"), 32)
+
+// csrfTestHandler echoes the request's CSRF token so tests can obtain a valid
+// token/cookie pair from a GET, then replay it on a POST.
+var csrfTestHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Write([]byte(csrf.Token(r)))
+})
+
+// getCSRFToken performs a GET through h and returns the masked token from the
+// response body along with the CSRF cookie that was set.
+func getCSRFToken(t *testing.T, h http.Handler, target string) (string, *http.Cookie) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, httptest.NewRequest("GET", target, nil))
+ res := rec.Result()
+ if res.StatusCode != http.StatusOK {
+ t.Fatalf("GET %s: status %d", target, res.StatusCode)
+ }
+ body, _ := io.ReadAll(res.Body)
+ for _, c := range res.Cookies() {
+ if c.Name == "_gorilla_csrf" {
+ return string(body), c
+ }
+ }
+ t.Fatalf("GET %s: no CSRF cookie set", target)
+ return "", nil
+}
+
+func TestCSRFProtector(t *testing.T) {
+ tests := []struct {
+ name string
+ appHost string
+ hiddenHost string
+ // target is the URL WriteFreely itself sees. An http:// target with
+ // an https:// Origin simulates TLS terminated at a reverse proxy.
+ target string
+ origin string
+ referer string
+ noToken bool
+ want int
+ }{
+ // Plain HTTP instances (local dev, LAN, no TLS)
+ {name: "http same origin", appHost: "http://localhost:8080", target: "http://localhost:8080/api/me/self", origin: "http://localhost:8080", want: http.StatusOK},
+ {name: "http same-origin referer, no origin", appHost: "http://localhost:8080", target: "http://localhost:8080/api/me/self", referer: "http://localhost:8080/me/settings", want: http.StatusOK},
+ {name: "http reached via LAN address", appHost: "http://localhost:8080", target: "http://192.168.1.5:8080/api/me/self", origin: "http://192.168.1.5:8080", want: http.StatusOK},
+ {name: "http host behind TLS proxy", appHost: "http://blog.example.com", target: "http://blog.example.com/api/me/self", origin: "https://blog.example.com", want: http.StatusOK},
+ {name: "http cross origin", appHost: "http://localhost:8080", target: "http://localhost:8080/api/me/self", origin: "http://evil.example", want: http.StatusForbidden},
+ {name: "http missing token", appHost: "http://localhost:8080", target: "http://localhost:8080/api/me/self", origin: "http://localhost:8080", noToken: true, want: http.StatusForbidden},
+
+ // HTTPS instances: behavior must match gorilla/csrf defaults
+ {name: "https via TLS proxy", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", origin: "https://blog.example.com", want: http.StatusOK},
+ {name: "https direct TLS", appHost: "https://blog.example.com", target: "https://blog.example.com/api/me/self", origin: "https://blog.example.com", want: http.StatusOK},
+ {name: "https referer, no origin", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", referer: "https://blog.example.com/me/settings", want: http.StatusOK},
+ {name: "https rejects plaintext origin", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", origin: "http://blog.example.com", want: http.StatusForbidden},
+ {name: "https rejects plaintext referer", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", referer: "http://blog.example.com/me/settings", want: http.StatusForbidden},
+ {name: "https requires referer", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", want: http.StatusForbidden},
+ {name: "https cross origin", appHost: "https://blog.example.com", target: "http://blog.example.com/api/me/self", origin: "https://evil.example", want: http.StatusForbidden},
+
+ // Tor hidden service alongside an HTTPS clearnet host
+ {name: "onion same origin", appHost: "https://blog.example.com", hiddenHost: "http://abcdefgh.onion", target: "http://abcdefgh.onion/api/me/self", origin: "http://abcdefgh.onion", want: http.StatusOK},
+ {name: "onion referer, no origin", appHost: "https://blog.example.com", hiddenHost: "http://abcdefgh.onion", target: "http://abcdefgh.onion/api/me/self", referer: "http://abcdefgh.onion/me/settings", want: http.StatusOK},
+ {name: "onion doesn't relax clearnet", appHost: "https://blog.example.com", hiddenHost: "http://abcdefgh.onion", target: "http://blog.example.com/api/me/self", origin: "http://blog.example.com", want: http.StatusForbidden},
+ {name: "onion cross origin", appHost: "https://blog.example.com", hiddenHost: "http://abcdefgh.onion", target: "http://abcdefgh.onion/api/me/self", origin: "http://evil.onion", want: http.StatusForbidden},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cfg := config.New()
+ cfg.App.Host = tt.appHost
+ cfg.Server.HiddenHost = tt.hiddenHost
+ h := newCSRFProtector(cfg, testCSRFKey)(csrfTestHandler)
+
+ token, cookie := getCSRFToken(t, h, tt.target)
+
+ req := httptest.NewRequest("POST", tt.target, nil)
+ req.AddCookie(cookie)
+ if !tt.noToken {
+ req.Header.Set("X-CSRF-Token", token)
+ }
+ if tt.origin != "" {
+ req.Header.Set("Origin", tt.origin)
+ }
+ if tt.referer != "" {
+ req.Header.Set("Referer", tt.referer)
+ }
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+
+ if got := rec.Result().StatusCode; got != tt.want {
+ t.Errorf("POST %s (Origin %q, Referer %q): got %d, want %d; body: %s",
+ tt.target, tt.origin, tt.referer, got, tt.want, rec.Body.String())
+ }
+ })
+ }
+}
+
+// The CSRF cookie must follow the same Secure rule as the session cookie:
+// browsers drop Secure cookies set over plain HTTP (except on localhost), which
+// would make every form on a LAN or no-TLS instance fail with "CSRF token
+// invalid".
+func TestCSRFCookieSecure(t *testing.T) {
+ for host, wantSecure := range map[string]bool{
+ "http://192.168.1.5:8080": false,
+ "https://blog.example.com": true,
+ } {
+ cfg := config.New()
+ cfg.App.Host = host
+ _, cookie := getCSRFToken(t, newCSRFProtector(cfg, testCSRFKey)(csrfTestHandler), host+"/me/settings")
+ if cookie.Secure != wantSecure {
+ t.Errorf("host %s: CSRF cookie Secure = %v, want %v", host, cookie.Secure, wantSecure)
+ }
+ }
+}
+
+func TestCSRFProtectFormSkipsJSON(t *testing.T) {
+ cfg := config.New()
+ cfg.App.Host = "https://blog.example.com"
+ h := csrfProtectForm(newCSRFProtector(cfg, testCSRFKey), csrfTestHandler)
+
+ // No token or cookie: JSON clients authenticate with an Authorization
+ // header, so CSRF doesn't apply.
+ req := httptest.NewRequest("POST", "/api/me/self", nil)
+ req.Header.Set("Content-Type", "application/json")
+ rec := httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if got := rec.Result().StatusCode; got != http.StatusOK {
+ t.Errorf("JSON POST: got %d, want %d", got, http.StatusOK)
+ }
+
+ // Form posts without a token are still rejected.
+ req = httptest.NewRequest("POST", "/api/me/self", nil)
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", "https://blog.example.com")
+ rec = httptest.NewRecorder()
+ h.ServeHTTP(rec, req)
+ if got := rec.Result().StatusCode; got != http.StatusForbidden {
+ t.Errorf("form POST without token: got %d, want %d", got, http.StatusForbidden)
+ }
+}
diff --git a/routes.go b/routes.go
index 93bc118..9735c58 100644
--- a/routes.go
+++ b/routes.go
@@ -1,264 +1,252 @@
/*
* Copyright © 2018-2021 Musing Studio LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"net/http"
"net/url"
"path/filepath"
"strings"
- "github.com/gorilla/csrf"
"github.com/gorilla/mux"
"github.com/writeas/go-webfinger"
"github.com/writeas/web-core/log"
"github.com/writefreely/go-nodeinfo"
)
// InitStaticRoutes adds routes for serving static files.
// TODO: this should just be a func, not method
func (app *App) InitStaticRoutes(r *mux.Router) {
// Handle static files
fs := http.FileServer(http.Dir(filepath.Join(app.cfg.Server.StaticParentDir, staticDir)))
fs = cacheControl(fs)
app.shttp = http.NewServeMux()
app.shttp.Handle("/", fs)
r.PathPrefix("/").Handler(fs)
}
// InitRoutes adds dynamic routes for the given mux.Router.
func InitRoutes(apper Apper, r *mux.Router) *mux.Router {
// Create handler
handler := NewWFHandler(apper)
// Set up routes
hostSubroute := apper.App().cfg.App.Host[strings.Index(apper.App().cfg.App.Host, "://")+3:]
if apper.App().cfg.App.SingleUser {
hostSubroute = "{domain}"
} else {
if strings.HasPrefix(hostSubroute, "localhost") {
hostSubroute = "localhost"
}
}
if apper.App().cfg.App.SingleUser {
log.Info("Adding %s routes (single user)...", hostSubroute)
} else {
log.Info("Adding %s routes (multi-user)...", hostSubroute)
}
+ // CSRF protection for cookie-authenticated form posts
+ csrfProtect := newCSRFProtector(apper.App().cfg, apper.App().keys.CSRFKey)
+
// Primary app routes
write := r.PathPrefix("/").Subrouter()
// Federation endpoint configurations
wf := webfinger.Default(wfResolver{apper.App().db, apper.App().cfg})
wf.NoTLSHandler = nil
// Federation endpoints
// host-meta
write.HandleFunc("/.well-known/host-meta", handler.Web(handleViewHostMeta, UserLevelReader))
// webfinger
write.HandleFunc(webfinger.WebFingerPath, handler.LogHandlerFunc(http.HandlerFunc(wf.Webfinger)))
// nodeinfo
niCfg := nodeInfoConfig(apper.App().db, apper.App().cfg)
ni := nodeinfo.NewService(*niCfg, nodeInfoResolver{apper.App().cfg, apper.App().db})
write.HandleFunc(nodeinfo.NodeInfoPath, handler.LogHandlerFunc(http.HandlerFunc(ni.NodeInfoDiscover)))
write.HandleFunc(niCfg.InfoURL, handler.LogHandlerFunc(http.HandlerFunc(ni.NodeInfo)))
// handle mentions
write.HandleFunc("/@/{handle}", handler.Web(handleViewMention, UserLevelReader))
configureSlackOauth(handler, write, apper.App())
configureWriteAsOauth(handler, write, apper.App())
configureGitlabOauth(handler, write, apper.App())
configureGenericOauth(handler, write, apper.App())
configureGiteaOauth(handler, write, apper.App())
// Set up dynamic page handlers
// Handle auth
auth := write.PathPrefix("/api/auth/").Subrouter()
auth.HandleFunc("/signup", handler.All(apiSignup)).Methods("POST")
auth.HandleFunc("/login", handler.All(login)).Methods("POST")
auth.HandleFunc("/read", handler.WebErrors(handleWebCollectionUnlock, UserLevelNone)).Methods("POST")
auth.HandleFunc("/me", handler.All(handleAPILogout)).Methods("DELETE")
// Handle logged in user sections
me := write.PathPrefix("/me").Subrouter()
me.HandleFunc("/", handler.Redirect("/me", UserLevelUser))
me.HandleFunc("/c", handler.Redirect("/me/c/", UserLevelUser)).Methods("GET")
me.HandleFunc("/c/", handler.User(viewCollections)).Methods("GET")
me.HandleFunc("/c/{collection}", handler.User(viewEditCollection)).Methods("GET")
me.HandleFunc("/c/{collection}/stats", handler.User(viewStats)).Methods("GET")
me.HandleFunc("/c/{collection}/subscribers", handler.User(handleViewSubscribers)).Methods("GET")
- me.Path("/delete").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(handleUserDelete))).Methods("POST")
+ me.Path("/delete").Handler(csrfProtect(handler.User(handleUserDelete))).Methods("POST")
me.HandleFunc("/posts", handler.Redirect("/me/posts/", UserLevelUser)).Methods("GET")
me.HandleFunc("/posts/", handler.User(viewArticles)).Methods("GET")
me.HandleFunc("/posts/export.csv", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET")
me.HandleFunc("/posts/export.zip", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET")
me.HandleFunc("/posts/export.json", handler.Download(viewExportPosts, UserLevelUser)).Methods("GET")
me.HandleFunc("/export", handler.User(viewExportOptions)).Methods("GET")
me.HandleFunc("/export.json", handler.Download(viewExportFull, UserLevelUser)).Methods("GET")
- me.Path("/import").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(viewImport))).Methods("GET")
- me.Path("/settings").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(viewSettings))).Methods("GET")
- me.Path("/invites").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(handleViewUserInvites))).Methods("GET")
+ me.Path("/import").Handler(csrfProtect(handler.User(viewImport))).Methods("GET")
+ me.Path("/settings").Handler(csrfProtect(handler.User(viewSettings))).Methods("GET")
+ me.Path("/invites").Handler(csrfProtect(handler.User(handleViewUserInvites))).Methods("GET")
me.HandleFunc("/logout", handler.Web(viewLogout, UserLevelNone)).Methods("GET")
write.HandleFunc("/api/me", handler.All(viewMeAPI)).Methods("GET")
apiMe := write.PathPrefix("/api/me/").Subrouter()
apiMe.HandleFunc("/", handler.All(viewMeAPI)).Methods("GET")
apiMe.HandleFunc("/posts", handler.UserWebAPI(viewMyPostsAPI)).Methods("GET")
apiMe.HandleFunc("/collections", handler.UserAPI(viewMyCollectionsAPI)).Methods("GET")
apiMe.HandleFunc("/password", handler.All(updatePassphrase)).Methods("POST")
- apiMe.Path("/self").Handler(csrfProtectForm(apper.App().keys.CSRFKey, handler.All(updateSettings))).Methods("POST")
- apiMe.Path("/invites").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(handleCreateUserInvite))).Methods("POST")
- apiMe.Path("/import").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(handleImport))).Methods("POST")
- apiMe.Path("/oauth/remove").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.User(removeOauth))).Methods("POST")
+ apiMe.Path("/self").Handler(csrfProtectForm(csrfProtect, handler.All(updateSettings))).Methods("POST")
+ apiMe.Path("/invites").Handler(csrfProtect(handler.User(handleCreateUserInvite))).Methods("POST")
+ apiMe.Path("/import").Handler(csrfProtect(handler.User(handleImport))).Methods("POST")
+ apiMe.Path("/oauth/remove").Handler(csrfProtect(handler.User(removeOauth))).Methods("POST")
// Sign up validation
write.HandleFunc("/api/alias", handler.All(handleUsernameCheck)).Methods("POST")
write.HandleFunc("/api/markdown", handler.All(handleRenderMarkdown)).Methods("POST")
instanceURL, _ := url.Parse(apper.App().Config().App.Host)
host := instanceURL.Host
// Handle collections
write.HandleFunc("/api/collections", handler.All(newCollection)).Methods("POST")
apiColls := write.PathPrefix("/api/collections/").Subrouter()
apiColls.HandleFunc("/monetization-pointer", handler.PlainTextAPI(handleSPSPEndpoint)).Methods("GET")
apiColls.HandleFunc("/"+host, handler.AllReader(fetchCollection)).Methods("GET")
apiColls.HandleFunc("/{alias:[0-9a-zA-Z\\-]+}", handler.AllReader(fetchCollection)).Methods("GET")
apiColls.HandleFunc("/{alias:[0-9a-zA-Z\\-]+}", handler.All(existingCollection)).Methods("POST", "DELETE")
apiColls.HandleFunc("/{alias}/posts", handler.AllReader(fetchCollectionPosts)).Methods("GET")
apiColls.HandleFunc("/{alias}/posts", handler.All(newPost)).Methods("POST")
apiColls.HandleFunc("/{alias}/posts/{post}", handler.AllReader(fetchPost)).Methods("GET")
apiColls.HandleFunc("/{alias}/posts/{post:[a-zA-Z0-9]{10}}", handler.All(existingPost)).Methods("POST")
apiColls.HandleFunc("/{alias}/posts/{post}/splitcontent", handler.AllReader(handleGetSplitContent)).Methods("GET", "POST")
apiColls.HandleFunc("/{alias}/posts/{post}/{property}", handler.AllReader(fetchPostProperty)).Methods("GET")
apiColls.HandleFunc("/{alias}/collect", handler.All(addPost)).Methods("POST")
apiColls.HandleFunc("/{alias}/pin", handler.All(pinPost)).Methods("POST")
apiColls.HandleFunc("/{alias}/unpin", handler.All(pinPost)).Methods("POST")
apiColls.HandleFunc("/{alias}/email/subscribers/export.csv", handler.Download(handleExportEmailSubscriptions, UserLevelUser)).Methods("GET")
apiColls.HandleFunc("/{alias}/email/subscribe", handler.All(handleCreateEmailSubscription)).Methods("POST")
apiColls.HandleFunc("/{alias}/email/subscribe", handler.All(handleDeleteEmailSubscription)).Methods("DELETE")
apiColls.HandleFunc("/{collection}/email/unsubscribe", handler.All(handleDeleteEmailSubscription)).Methods("GET")
apiColls.HandleFunc("/{alias}/inbox", handler.All(handleFetchCollectionInbox)).Methods("POST")
apiColls.HandleFunc("/{alias}/outbox", handler.AllReader(handleFetchCollectionOutbox)).Methods("GET")
apiColls.HandleFunc("/{alias}/following", handler.AllReader(handleFetchCollectionFollowing)).Methods("GET")
apiColls.HandleFunc("/{alias}/followers", handler.AllReader(handleFetchCollectionFollowers)).Methods("GET")
// Handle posts
write.HandleFunc("/api/posts", handler.All(newPost)).Methods("POST")
posts := write.PathPrefix("/api/posts/").Subrouter()
posts.HandleFunc("/claim", handler.All(addPost)).Methods("POST")
posts.HandleFunc("/disperse", handler.All(dispersePost)).Methods("POST")
posts.HandleFunc("/{post:[a-zA-Z0-9]+}", handler.AllReader(fetchPost)).Methods("GET")
posts.HandleFunc("/{post:[a-zA-Z0-9]+}", handler.All(existingPost)).Methods("POST", "PUT")
posts.HandleFunc("/{post:[a-zA-Z0-9]+}", handler.All(deletePost)).Methods("DELETE")
posts.HandleFunc("/{post:[a-zA-Z0-9]+}/{property}", handler.AllReader(fetchPostProperty)).Methods("GET")
write.HandleFunc("/auth/signup", handler.Web(handleWebSignup, UserLevelNoneRequired)).Methods("POST")
write.HandleFunc("/auth/login", handler.Web(webLogin, UserLevelNoneRequired)).Methods("POST")
write.HandleFunc("/admin", handler.Admin(handleViewAdminDash)).Methods("GET")
write.HandleFunc("/admin/monitor", handler.Admin(handleViewAdminMonitor)).Methods("GET")
write.HandleFunc("/admin/settings", handler.Admin(handleViewAdminSettings)).Methods("GET")
write.HandleFunc("/admin/users", handler.Admin(handleViewAdminUsers)).Methods("GET")
write.HandleFunc("/admin/user/{username}", handler.Admin(handleViewAdminUser)).Methods("GET")
write.HandleFunc("/admin/user/{username}/delete", handler.Admin(handleAdminDeleteUser)).Methods("POST")
write.HandleFunc("/admin/user/{username}/status", handler.Admin(handleAdminToggleUserStatus)).Methods("POST")
write.HandleFunc("/admin/user/{username}/passphrase", handler.Admin(handleAdminResetUserPass)).Methods("POST")
write.HandleFunc("/admin/pages", handler.Admin(handleViewAdminPages)).Methods("GET")
write.HandleFunc("/admin/page/{slug}", handler.Admin(handleViewAdminPage)).Methods("GET")
write.HandleFunc("/admin/update/config", handler.AdminApper(handleAdminUpdateConfig)).Methods("POST")
write.HandleFunc("/admin/update/{page}", handler.Admin(handleAdminUpdateSite)).Methods("POST")
write.HandleFunc("/admin/updates", handler.Admin(handleViewAdminUpdates)).Methods("GET")
// Handle special pages first
- write.Path("/reset").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.Web(viewResetPassword, UserLevelNoneRequired)))
- write.Path("/forgot-username").Handler(csrf.Protect(apper.App().keys.CSRFKey, csrf.Path("/"))(handler.Web(viewForgotUsername, UserLevelNoneRequired)))
+ write.Path("/reset").Handler(csrfProtect(handler.Web(viewResetPassword, UserLevelNoneRequired)))
+ write.Path("/forgot-username").Handler(csrfProtect(handler.Web(viewForgotUsername, UserLevelNoneRequired)))
write.HandleFunc("/login", handler.Web(viewLogin, UserLevelNoneRequired))
write.HandleFunc("/signup", handler.Web(handleViewLanding, UserLevelNoneRequired))
write.HandleFunc("/invite/{code:[a-zA-Z0-9]+}", handler.Web(handleViewInvite, UserLevelOptional)).Methods("GET")
// TODO: show a reader-specific 404 page if the function is disabled
write.HandleFunc("/read", handler.Web(viewLocalTimeline, UserLevelReader))
RouteRead(handler, UserLevelReader, write.PathPrefix("/read").Subrouter())
draftEditPrefix := ""
if apper.App().cfg.App.SingleUser {
draftEditPrefix = "/d"
write.HandleFunc("/me/new", handler.Web(handleViewPad, UserLevelUser)).Methods("GET")
} else {
write.HandleFunc("/new", handler.Web(handleViewPad, UserLevelUser)).Methods("GET")
}
// All the existing stuff
write.HandleFunc(draftEditPrefix+"/{action}/edit", handler.Web(handleViewPad, UserLevelUser)).Methods("GET")
write.HandleFunc(draftEditPrefix+"/{action}/meta", handler.Web(handleViewMeta, UserLevelUser)).Methods("GET")
// Collections
if apper.App().cfg.App.SingleUser {
RouteCollections(handler, write.PathPrefix("/").Subrouter())
} else {
write.HandleFunc("/{prefix:[@~$!\\-+]}{collection}", handler.Web(handleViewCollection, UserLevelReader))
write.HandleFunc("/{collection}/", handler.Web(handleViewCollection, UserLevelReader))
RouteCollections(handler, write.PathPrefix("/{prefix:[@~$!\\-+]?}{collection}").Subrouter())
// Posts
}
write.HandleFunc(draftEditPrefix+"/{post}", handler.Web(handleViewPost, UserLevelOptional))
write.HandleFunc("/", handler.Web(handleViewHome, UserLevelOptional))
return r
}
-// csrfProtectForm wraps a handler with CSRF protection but exempts JSON
-// requests, which authenticate via Authorization header rather than
-// session cookies and are therefore not CSRF-exploitable.
-func csrfProtectForm(key []byte, next http.Handler) http.Handler {
- protected := csrf.Protect(key, csrf.Path("/"))(next)
- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if IsJSON(r) {
- next.ServeHTTP(w, r)
- return
- }
- protected.ServeHTTP(w, r)
- })
-}
-
func RouteCollections(handler *Handler, r *mux.Router) {
r.HandleFunc("/logout", handler.Web(handleLogOutCollection, UserLevelOptional))
r.HandleFunc("/page/{page:[0-9]+}", handler.Web(handleViewCollection, UserLevelReader))
r.HandleFunc("/archive/", handler.Web(handleViewCollection, UserLevelReader))
r.HandleFunc("/{archive:archive}/page/{page:[0-9]+}", handler.Web(handleViewCollection, UserLevelReader))
r.HandleFunc("/lang:{lang:[a-z]{2}}", handler.Web(handleViewCollectionLang, UserLevelOptional))
r.HandleFunc("/lang:{lang:[a-z]{2}}/page/{page:[0-9]+}", handler.Web(handleViewCollectionLang, UserLevelOptional))
r.HandleFunc("/tag:{tag}", handler.Web(handleViewCollectionTag, UserLevelReader))
r.HandleFunc("/tag:{tag}/page/{page:[0-9]+}", handler.Web(handleViewCollectionTag, UserLevelReader))
r.HandleFunc("/tag:{tag}/feed/", handler.Web(ViewFeed, UserLevelReader))
r.HandleFunc("/sitemap.xml", handler.AllReader(handleViewSitemap))
r.HandleFunc("/feed/", handler.AllReader(ViewFeed))
r.HandleFunc("/email/confirm/{subscriber}", handler.All(handleConfirmEmailSubscription)).Methods("GET")
r.HandleFunc("/email/unsubscribe/{subscriber}", handler.All(handleDeleteEmailSubscription)).Methods("GET")
r.HandleFunc("/{slug}", handler.CollectionPostOrStatic)
r.HandleFunc("/{slug}/edit", handler.Web(handleViewPad, UserLevelUser))
r.HandleFunc("/{slug}/edit/meta", handler.Web(handleViewMeta, UserLevelUser))
r.HandleFunc("/{slug}/", handler.Web(handleCollectionPostRedirect, UserLevelReader)).Methods("GET")
}
func RouteRead(handler *Handler, readPerm UserLevelFunc, r *mux.Router) {
r.HandleFunc("/api/posts", handler.Web(viewLocalTimelineAPI, readPerm))
r.HandleFunc("/p/{page}", handler.Web(viewLocalTimeline, readPerm))
r.HandleFunc("/feed", handler.Web(viewLocalTimelineFeed, readPerm))
r.HandleFunc("/feed/", handler.Web(viewLocalTimelineFeed, readPerm))
r.HandleFunc("/t/{tag}", handler.Web(viewLocalTimeline, readPerm))
r.HandleFunc("/a/{post}", handler.Web(handlePostIDRedirect, readPerm))
r.HandleFunc("/{author}", handler.Web(viewLocalTimeline, readPerm))
r.HandleFunc("/", handler.Web(viewLocalTimeline, readPerm))
}
File Metadata
Details
Attached
Mime Type
text/x-diff
Expires
Mon, Nov 30, 9:49 AM (5 h, 2 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3830677
Attached To
rWF WriteFreely
Event Timeline
Log In to Comment