ARTEX/server/csrf_test.go

207 lines
9.3 KiB
Go

package server
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/Autumn-27/artex/db"
)
// csrfRequest builds a request to http://example.com (the httptest default
// host) with the given headers. A "Cookie" value is the artex_token cookie.
func csrfRequest(method, path, body string, headers map[string]string) *http.Request {
r := httptest.NewRequest(method, path, strings.NewReader(body))
for k, v := range headers {
if k == "Cookie" {
r.AddCookie(&http.Cookie{Name: "artex_token", Value: v})
continue
}
r.Header.Set(k, v)
}
return r
}
// The browser attaches the artex_token cookie on its own, to requests a
// foreign page makes as well, so the cookie is never a session: whatever the
// method or origin, a request with only the cookie is refused. A bearer token
// is put there by the caller and is the only session. requireAuth is
// exercised directly, without a database.
func TestCookieIsNeverASession(t *testing.T) {
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
tok, err := signJWT(s.jwtKey)
if err != nil {
t.Fatal(err)
}
reached := false
h := s.requireAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reached = true
w.WriteHeader(204)
}))
for _, tc := range []struct {
name string
method string
path string
headers map[string]string
want int
}{
{"cookie, matching Origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "http://example.com"}, 401},
{"cookie, Sec-Fetch-Site same-origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Sec-Fetch-Site": "same-origin"}, 401},
{"cookie, foreign Origin", "POST", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401},
{"cookie, neither header, DELETE", "DELETE", "/api/mcp", map[string]string{"Cookie": tok}, 401},
{"cookie, foreign Origin, GET", "GET", "/api/mcp", map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401},
{"cookie, neither header, GET", "GET", "/api/mcp", map[string]string{"Cookie": tok}, 401},
{"cookie, neither header, HEAD", "HEAD", "/api/mcp", map[string]string{"Cookie": tok}, 401},
{"cookie and query token, foreign Origin", "POST", "/api/mcp?token=" + tok, map[string]string{"Cookie": tok, "Origin": "https://evil.example"}, 401},
{"query token alone", "GET", "/api/mcp?token=" + tok, nil, 401},
{"bearer, foreign Origin", "POST", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok, "Origin": "https://evil.example"}, 204},
{"bearer, neither header", "DELETE", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok}, 204},
{"bearer, GET", "GET", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok}, 204},
{"bearer and cookie, foreign Origin", "DELETE", "/api/mcp", map[string]string{"Authorization": "Bearer " + tok, "Cookie": tok, "Origin": "https://evil.example"}, 204},
// A bad bearer token does not fall back to the cookie.
{"bad bearer and cookie", "POST", "/api/mcp", map[string]string{"Authorization": "Bearer nope", "Cookie": tok, "Origin": "http://example.com"}, 401},
{"no token", "POST", "/api/mcp", map[string]string{"Origin": "http://example.com"}, 401},
} {
reached = false
rec := httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest(tc.method, tc.path, "", tc.headers))
if rec.Code != tc.want || reached != (tc.want == 204) {
t.Errorf("%s: status=%d handler reached=%v, want %d", tc.name, rec.Code, reached, tc.want)
}
}
// The handlers that validate the session themselves (event streams,
// change-password, approver) read it through extractToken too.
r := csrfRequest("GET", "/api/logs/stream", "", map[string]string{"Cookie": tok})
if got := extractToken(r); got != "" {
t.Errorf("extractToken took the session from the cookie: %q", got)
}
r = csrfRequest("GET", "/api/logs/stream", "", map[string]string{"Cookie": tok, "Authorization": "Bearer " + tok})
if got := extractToken(r); got != tok {
t.Errorf("extractToken ignored the bearer token")
}
}
// The same rule through the real mux: a foreign page must not be able to add
// an MCP server (POST /api/mcp) or change the admin password
// (POST /api/auth/change-password, which validates the session itself) with
// the operator's cookie. Setup and login need no session and keep working.
// Needs PostgreSQL (ARTEX_PG_DSN); skipped without it.
func TestCookieCSRFThroughRealMux(t *testing.T) {
m, err := NewManager(t.TempDir(), "")
if err != nil {
db.SkipPGUnavailable(t, err)
}
if m.pg == nil {
db.SkipNoPG(t)
}
defer m.Close()
td := t.TempDir()
ctx, cancel := context.WithCancel(context.Background())
s := New(ctx, m, td, td, td)
defer stopTestServer(t, s, cancel)
stamp := time.Now().UnixNano()
s.authHashKey = fmt.Sprintf("test.password_hash.%d", stamp)
s.authVersionKey = fmt.Sprintf("test.password_version.%d", stamp)
prefix := fmt.Sprintf("csrf-%d-", stamp)
defer func() { // deferred, not t.Cleanup: it must run before m.Close
_, _ = m.pg.Exec(`DELETE FROM settings WHERE key=$1 OR key=$2`, s.authHashKey, s.authVersionKey)
_, _ = m.pg.Exec(`DELETE FROM mcp_servers WHERE name LIKE $1`, prefix+"%")
}()
s.setupMu.Lock()
s.setupToken = "setup-ok"
s.setupMu.Unlock()
h := s.Handler()
token := func(rec *httptest.ResponseRecorder) string {
t.Helper()
var out struct {
Token string `json:"token"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &out) != nil || out.Token == "" {
t.Fatalf("status=%d body=%s, want a token", rec.Code, rec.Body.String())
}
return out.Token
}
// Setup from a client that sends neither Origin nor Sec-Fetch-Site (curl).
rec := httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/init", `{"password":"correct-horse-1","setup_token":"setup-ok"}`, nil))
stale := token(rec)
// Login the same way, then from the browser: the login page posts from the
// console's own origin and may still hold the cookie of an earlier session.
login := `{"username":"ARTEX","password":"correct-horse-1"}`
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, nil))
token(rec)
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, map[string]string{"Cookie": stale, "Origin": "http://example.com", "Sec-Fetch-Site": "same-origin"}))
tok := token(rec)
for _, tc := range []struct {
name string
headers map[string]string
want int
}{
{"cookie-same-origin", map[string]string{"Cookie": tok, "Origin": "http://example.com", "Content-Type": "application/json"}, 401},
// What a foreign page can send without a preflight: a text/plain body.
{"cookie-cross-origin", map[string]string{"Cookie": tok, "Origin": "https://evil.example", "Content-Type": "text/plain"}, 401},
{"cookie-no-headers", map[string]string{"Cookie": tok}, 401},
{"bearer-cross-origin", map[string]string{"Authorization": "Bearer " + tok, "Origin": "https://evil.example"}, 200},
} {
name := prefix + tc.name
body := fmt.Sprintf(`{"name":%q,"transport":"stdio","command":"sh","args":["-c","id"],"enabled":false}`, name)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/mcp", body, tc.headers))
rows, err := m.pg.ListMCP()
if err != nil {
t.Fatal(err)
}
stored := false
for _, row := range rows {
stored = stored || row.Name == name
}
if rec.Code != tc.want || stored != (tc.want == 200) {
t.Errorf("%s: status=%d MCP server stored=%v, want %d (body %s)", tc.name, rec.Code, stored, tc.want, strings.TrimSpace(rec.Body.String()))
}
}
// change-password is under /api/auth/*, which requireAuth exempts; the
// handler validates the session itself. A cross-origin form post that
// carries only the cookie (and knows the old password) must not rotate it.
change := `{"old_password":"correct-horse-1","new_password":"attacker-chosen-9"}`
for _, headers := range []map[string]string{
{"Cookie": tok, "Origin": "https://evil.example", "Content-Type": "text/plain"},
{"Cookie": tok, "Origin": "http://example.com", "Sec-Fetch-Site": "same-origin", "Content-Type": "application/json"},
} {
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/change-password", change, headers))
if rec.Code != 401 {
t.Errorf("change-password with the cookie only (%v): status=%d, want 401", headers["Origin"], rec.Code)
}
}
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/login", login, nil))
if rec.Code != 200 {
t.Fatalf("the cookie-only change-password request changed the password: login status=%d", rec.Code)
}
// Reads with the cookie alone are refused too: the log page and the event
// streams send the bearer token.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("GET", "/api/mcp", "", map[string]string{"Cookie": tok}))
if rec.Code != 401 {
t.Errorf("GET /api/mcp with the cookie: status=%d, want 401", rec.Code)
}
// The console's own request carries the bearer token and still works.
rec = httptest.NewRecorder()
h.ServeHTTP(rec, csrfRequest("POST", "/api/auth/change-password", `{"old_password":"correct-horse-1","new_password":"correct-horse-2"}`,
map[string]string{"Authorization": "Bearer " + tok, "Content-Type": "application/json"}))
if rec.Code != 200 {
t.Errorf("change-password with the bearer token: status=%d body=%s, want 200", rec.Code, rec.Body.String())
}
}