Merge pull request #483 from Leechuihui/security/response-headers

security(server): send security headers on every response
This commit is contained in:
BaaRai
2026-11-22 23:01:48 +01:00
committed by GitHub
5 changed files with 164 additions and 17 deletions
+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project are documented in this file. The format is b
### Added
- **Security response headers on every response**: `X-Content-Type-Options: nosniff`, a same-origin referrer policy, `X-Frame-Options: SAMEORIGIN` and a `frame-ancestors 'self'` CSP are now set by one wrapper around the whole handler tree, so the JSON API carries them too; previously only the console route did. Console documents additionally get `Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a peer in `ARTEX_TRUSTED_PROXIES`, so a direct client cannot claim HTTPS on its own. The README reverse-proxy recipe now starts with an 80 to 443 redirect.
- **Global company switcher**: the sidebar header carries a company picker (search, an explicit "all companies", the asset count). It persists per browser and narrows these views on the server: the findings list, grouped view, asset tree and stat cards (`GET /api/exploration/findings`, `/groups`, `/asset-tree`, `/stats` take `company`), the dashboard findings panels (same list endpoint), the task list (`GET /api/tasks?company=`), the traffic list (`GET /api/traffic?company=`, the hosts the company owns) and the asset tabs (`GET /api/assets?company_id=`, plain and DSL path; the company clause is ANDed outside the compiled DSL). A finding belongs to a company through its live assets. A finding with no live asset belongs to a company only when its task is scoped to that company (`task_scope` kind `company`); otherwise it shows under "all companies" only. An unknown or non-numeric company id returns nothing (#425).
### Fixed
+20 -1
View File
@@ -635,7 +635,19 @@ default; the Docker container publishes on `127.0.0.1`), and the activity stream
default, so **no `NEXT_PUBLIC_SSE_BASE` is needed**: expose 443 and keep 8787 internal.
SSE keeps a long-lived connection with continuous pushes, so the proxy **must disable buffering**;
otherwise the browser connects but never receives events. Nginx example:
otherwise the browser connects but never receives events.
Redirect plain HTTP first, so a bookmarked `http://` URL never reaches the app unencrypted:
```nginx
server {
listen 80;
server_name your.domain.com;
return 301 https://$host$request_uri;
}
```
Then the TLS server:
```nginx
server {
@@ -681,6 +693,13 @@ For a peer in that list, ARTEX reads `X-Forwarded-For` from the right and takes
that is not a trusted proxy; from any other peer the header is ignored. Trust only proxies you run:
a trusted peer can claim any client address.
**Security headers**: every response carries `X-Content-Type-Options: nosniff`, a same-origin
referrer policy and a `frame-ancestors 'self'` CSP; console documents additionally get a
`Permissions-Policy` and COOP/CORP. `Strict-Transport-Security` is sent only when the request is
known to be HTTPS: directly over TLS, or via `X-Forwarded-Proto: https` from a trusted proxy. The
same list above enables it, so with nginx in front, the 443 server answers with HSTS after you set
`ARTEX_TRUSTED_PROXIES`.
> Only when SSE needs a different origin from the page (e.g. a dedicated subdomain) should you set
> `NEXT_PUBLIC_SSE_BASE` **at build time** (it is baked into the static bundle during `next build`;
> setting it at container runtime has no effect).
+59
View File
@@ -0,0 +1,59 @@
package server
import (
"net/http"
"net/netip"
)
// Security headers are split in two layers so the API and the operator console
// each get what applies to them.
// securityHeaders applies the response headers that are safe for every response,
// including the JSON API. It wraps the whole handler tree so no route can forget
// them: a missing nosniff on a JSON reply is exactly the kind of gap that only
// shows up on the one route nobody remembered.
func (s *Server) securityHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
// Do not leak workspace paths and task ids to third parties.
h.Set("Referrer-Policy", "same-origin")
// The API is JSON, but a proxied error page must still not be framed.
h.Set("X-Frame-Options", "SAMEORIGIN")
h.Set("Content-Security-Policy", "frame-ancestors 'self'")
if s.isHTTPS(r) {
// Ignored by browsers over plain HTTP, so it only takes effect behind
// the TLS-terminating proxy this deployment is documented to use.
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
next.ServeHTTP(w, r)
})
}
// consoleHeaders applies the headers that only make sense on documents, on top of
// the ones securityHeaders already set. Called from the console route.
func consoleHeaders(h http.Header) {
// The console needs no device APIs; keep them from being promptable.
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=(), payment=(), usb=()")
// Separate the console's browsing context from the tabs it opens.
h.Set("Cross-Origin-Opener-Policy", "same-origin")
h.Set("Cross-Origin-Resource-Policy", "same-origin")
}
// isHTTPS reports whether the request reached us over TLS, either directly or
// through a trusted proxy that says so. X-Forwarded-Proto is only believed when
// the peer is in ARTEX_TRUSTED_PROXIES, the same rule clientIP uses: a direct
// client could otherwise claim HTTPS and get a header it cannot back up.
func (s *Server) isHTTPS(r *http.Request) bool {
if r.TLS != nil {
return true
}
if r.Header.Get("X-Forwarded-Proto") != "https" {
return false
}
peer, err := netip.ParseAddr(peerIP(r))
if err != nil {
return false
}
return isTrusted(peer, s.trustedProxies)
}
+3 -5
View File
@@ -1082,13 +1082,11 @@ func (s *Server) Handler() http.Handler {
root.Handle("/api/", api)
webui := s.webuiHandler()
root.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Keep the operator console out of cross-origin frames and referrers.
w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("Referrer-Policy", "same-origin")
// Document-only headers; the shared ones come from securityHeaders.
consoleHeaders(w.Header())
webui.ServeHTTP(w, r)
})
return limitRequestBody(root)
return s.securityHeaders(limitRequestBody(root))
}
// --- handlers ---
+81 -11
View File
@@ -1,24 +1,50 @@
package server
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
)
func TestConsoleBrowserProtections(t *testing.T) {
// sharedHeaders apply to every response, API included.
var sharedHeaders = map[string]string{
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "same-origin",
"X-Frame-Options": "SAMEORIGIN",
"Content-Security-Policy": "frame-ancestors 'self'",
}
// consoleOnlyHeaders must stay off the API: they are document headers.
var consoleOnlyHeaders = map[string]string{
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=(), usb=()",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
}
func TestSharedHeadersEverywhere(t *testing.T) {
handler := (&Server{}).Handler()
headers := map[string]string{
"Content-Security-Policy": "frame-ancestors 'self'",
"X-Frame-Options": "SAMEORIGIN",
"Referrer-Policy": "same-origin",
for _, path := range []string{"/", "/settings/", "/api/health", "/api/stats"} {
res := httptest.NewRecorder()
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))
sent := res.Result().Header
for name, want := range sharedHeaders {
if got := sent.Get(name); got != want {
t.Errorf("%s: %s = %q, want %q", path, name, got, want)
}
}
}
}
func TestConsoleOnlyHeaders(t *testing.T) {
handler := (&Server{}).Handler()
for _, path := range []string{"/", "/settings/"} {
res := httptest.NewRecorder()
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, path, nil))
sent := res.Result().Header
for name, want := range headers {
for name, want := range consoleOnlyHeaders {
if got := sent.Get(name); got != want {
t.Errorf("%s: %s = %q, want %q", path, name, got, want)
}
@@ -27,13 +53,57 @@ func TestConsoleBrowserProtections(t *testing.T) {
res := httptest.NewRecorder()
handler.ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/api/health", nil))
if res.Code != http.StatusOK {
t.Fatalf("health: status = %d, want %d", res.Code, http.StatusOK)
}
sent := res.Result().Header
for name := range headers {
for name := range consoleOnlyHeaders {
if got := sent.Get(name); got != "" {
t.Errorf("health: unexpected %s = %q", name, got)
t.Errorf("api: unexpected %s = %q", name, got)
}
}
}
// HSTS is only sent when the request is known to be HTTPS; over plain HTTP it is
// inert and would only add noise. X-Forwarded-Proto is believed only from a
// trusted proxy, so a direct client cannot claim HTTPS on its own.
func TestHSTSOnlyOverHTTPS(t *testing.T) {
handler := (&Server{}).Handler()
plain := httptest.NewRecorder()
handler.ServeHTTP(plain, httptest.NewRequest(http.MethodGet, "/", nil))
if got := plain.Result().Header.Get("Strict-Transport-Security"); got != "" {
t.Errorf("http: HSTS = %q, want none", got)
}
tlsReq := httptest.NewRequest(http.MethodGet, "/", nil)
tlsReq.TLS = &tls.ConnectionState{}
res := httptest.NewRecorder()
handler.ServeHTTP(res, tlsReq)
if got := res.Result().Header.Get("Strict-Transport-Security"); got == "" {
t.Error("direct TLS: no HSTS header")
}
}
// A trusted proxy saying HTTPS earns the header; an untrusted peer saying the
// same must not.
func TestHSTSFromTrustedProxy(t *testing.T) {
trusted := &Server{trustedProxies: mustTrusted(t, "127.0.0.1/32")}
handler := trusted.Handler()
proxied := httptest.NewRequest(http.MethodGet, "/", nil)
proxied.RemoteAddr = "127.0.0.1:5555"
proxied.Header.Set("X-Forwarded-Proto", "https")
res := httptest.NewRecorder()
handler.ServeHTTP(res, proxied)
if got := res.Result().Header.Get("Strict-Transport-Security"); got == "" {
t.Error("trusted proxy: no HSTS header")
}
untrusted := (&Server{}).Handler()
spoof := httptest.NewRequest(http.MethodGet, "/", nil)
spoof.RemoteAddr = "127.0.0.1:5555"
spoof.Header.Set("X-Forwarded-Proto", "https")
res = httptest.NewRecorder()
untrusted.ServeHTTP(res, spoof)
if got := res.Result().Header.Get("Strict-Transport-Security"); got != "" {
t.Errorf("untrusted peer: HSTS = %q, want none", got)
}
}