Add local login, agent extra log paths, IPv4/IPv6 metrics; remediate security audit findings
This is a large squashed commit covering two batches of prior uncommitted work plus a full security-audit remediation pass, kept together because go.mod/go.sum and several shared files (main.go, handler.go) were touched by both and splitting risked non-building intermediate commits. Features (built earlier, previously uncommitted): - Local username/password login for single-tenant deployments with no SSO configured (api/localauth, alerting/internal/sessioncheck, sentryctl users, web/src/routes/login, metadata migrations 0040/0041). - Remotely-editable additional log file paths for agents, on top of their existing primary source (api/agents, agent/sentry-agent extra-file-path diffing, web agent config UI). - IPv4/IPv6 addresses reported alongside other host system metrics. Security audit remediation (this pass, all live-verified in production): - Critical: block ClickHouse SSRF table functions (url/remote/file/s3/...) in the raw-SQL query escape hatch. - High: deny sensitive paths and require Admin to add agent extra_file_paths (Editor could previously point an agent at /etc/shadow or an SSH key); alerting webhook targets now validate against internal/metadata/loopback addresses, both at creation and send time; alerting's session middleware now enforces an Editor+ floor on mutating requests instead of "any authenticated session"; bumped goxmldsig to close a SAML signature-verification bypass (GO-2026-4753). - Medium: per-IP login rate limiting; security response headers (HSTS/CSP/nosniff/X-Frame-Options/Referrer-Policy/Permissions-Policy) on web/nginx.conf; a DevCredentialWarnings check in every Go service's config loader, logging loudly at startup if a deployment is still on docker-compose.yml's literal dev-only credentials; dependency bumps (golang.org/x/text, grpc, x/net, quick-xml, h2) across every affected Go module and both Rust crates, including a previously-uncovered x/net vulnerability in deploy/operator; a new security-scan.yml CI workflow running cargo-deny/govulncheck/npm-audit, mirroring the existing license-compliance.yml matrix shape. - Low: removed sentryctl's plaintext --password flag (shell history/`ps` exposure) in favor of stdin and a --password-stdin flag for reset-password's optional specific-password path; a dummy bcrypt comparison closes a login response-time username-enumeration side-channel.
This commit is contained in:
@@ -29,6 +29,7 @@ import (
|
||||
"github.com/sentry/sentry/alerting/internal/notifystore"
|
||||
"github.com/sentry/sentry/alerting/internal/queryclient"
|
||||
"github.com/sentry/sentry/alerting/internal/rulestore"
|
||||
"github.com/sentry/sentry/alerting/internal/sessioncheck"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -39,6 +40,9 @@ func main() {
|
||||
logger.Error("loading config", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
for _, w := range cfg.DevCredentialWarnings() {
|
||||
logger.Warn(w)
|
||||
}
|
||||
|
||||
// -healthcheck: self-check mode for Docker's HEALTHCHECK, mirrors
|
||||
// api/cmd/api/main.go's runHealthcheck -- this image is distroless too
|
||||
@@ -71,9 +75,23 @@ func main() {
|
||||
handler := httpapi.NewHandler(logger, rules, targets, rules)
|
||||
mux := http.NewServeMux()
|
||||
handler.RegisterRoutes(mux)
|
||||
|
||||
// Local login (see /docs -- deployment runbook, and
|
||||
// api/localauth's package doc comment for the full feature):
|
||||
// alerting has no per-route role plumbing of its own, so this is one
|
||||
// blanket "must have a valid session" gate in front of the whole
|
||||
// mux, same shape CORS already wraps it in below. /healthz stays
|
||||
// reachable regardless -- see sessioncheck.RequireSession's doc
|
||||
// comment.
|
||||
var gatedMux http.Handler = mux
|
||||
corsFn := httpserver.WithCORS
|
||||
if cfg.LocalAuthEnabled {
|
||||
gatedMux = sessioncheck.RequireSession(sessioncheck.NewChecker(pgPool), mux)
|
||||
corsFn = httpserver.WithCredentialedCORS
|
||||
}
|
||||
srv := &http.Server{
|
||||
Addr: cfg.HTTPListenAddr,
|
||||
Handler: httpserver.WithCORS(mux, cfg.CORSAllowedOrigin),
|
||||
Handler: corsFn(gatedMux, cfg.CORSAllowedOrigin),
|
||||
}
|
||||
|
||||
eval := evaluator.New(rules, targets, qc, cfg.Evaluator.QueryTimeout, cfg.Evaluator.ClaimBatchSize, cfg.Evaluator.WorkerPoolSize, logger)
|
||||
|
||||
+1
-1
@@ -12,5 +12,5 @@ require (
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
golang.org/x/text v0.29.0 // indirect
|
||||
golang.org/x/text v0.39.0 // indirect
|
||||
)
|
||||
|
||||
+2
-2
@@ -20,8 +20,8 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
|
||||
golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
|
||||
golang.org/x/text v0.29.0 h1:1neNs90w9YzJ9BocxfsQNHKuAT4pkghyXc4nhZ6sJvk=
|
||||
golang.org/x/text v0.29.0/go.mod h1:7MhJOA9CD2qZyOKYazxdYMF85OwPdEr9jTtBpO7ydH4=
|
||||
golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
|
||||
golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
|
||||
@@ -16,6 +16,11 @@ type Config struct {
|
||||
APIServiceToken string // RoleService credential presented to /api's POST /query -- see queryclient.New's doc comment
|
||||
CORSAllowedOrigin string
|
||||
Evaluator EvaluatorConfig
|
||||
// LocalAuthEnabled gates alerting's own session-required middleware
|
||||
// (see internal/sessioncheck) -- same env var name as api's
|
||||
// LOCAL_AUTH_ENABLED, one consistent on/off switch across both
|
||||
// services for a single-tenant deployment turning local login on.
|
||||
LocalAuthEnabled bool
|
||||
}
|
||||
|
||||
type PostgresConfig struct {
|
||||
@@ -43,6 +48,25 @@ type EvaluatorConfig struct {
|
||||
QueryTimeout time.Duration // per-evaluation POST /query timeout
|
||||
}
|
||||
|
||||
// devOnlyCredential is docker-compose.yml's zero-config default for
|
||||
// every Postgres/ClickHouse password in this repo -- see
|
||||
// api/internal/config.Config.DevCredentialWarnings for the full
|
||||
// reasoning (duplicated here per this repo's no-shared-code-between-
|
||||
// services convention).
|
||||
const devOnlyCredential = "sentry-dev-only"
|
||||
|
||||
// DevCredentialWarnings reports whether the configured Postgres
|
||||
// credential still equals the literal dev-only default --
|
||||
// cmd/alerting/main.go logs it loudly at startup. A warning, not a
|
||||
// startup-refusing error: local dev's zero-config docker-compose.yml
|
||||
// path legitimately leaves it at this value.
|
||||
func (c Config) DevCredentialWarnings() []string {
|
||||
if c.Postgres.Password == devOnlyCredential {
|
||||
return []string{"POSTGRES_PASSWORD is still the default dev-only value -- set a real password before this is reachable outside local dev"}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
cfg := Config{
|
||||
HTTPListenAddr: getenv("HTTP_LISTEN_ADDR", ":8081"),
|
||||
@@ -90,6 +114,12 @@ func Load() (Config, error) {
|
||||
}
|
||||
cfg.Evaluator.QueryTimeout = time.Duration(queryTimeoutSec) * time.Second
|
||||
|
||||
localAuthEnabled, err := strconv.ParseBool(getenv("LOCAL_AUTH_ENABLED", "false"))
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("LOCAL_AUTH_ENABLED: %w", err)
|
||||
}
|
||||
cfg.LocalAuthEnabled = localAuthEnabled
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -162,6 +162,17 @@ func (w *Worker) attempt(ctx context.Context, c claimedDelivery) {
|
||||
return
|
||||
}
|
||||
|
||||
// Re-validated here, not just at target-creation time
|
||||
// (httpapi.handleCreateTarget already checks this too): a hostname
|
||||
// that resolved to a public IP when the target was created can be
|
||||
// repointed at an internal/metadata address later via DNS rebinding,
|
||||
// and this is the point that actually issues the outbound request --
|
||||
// see notifystore.ValidateWebhookURL's doc comment.
|
||||
if err := notifystore.ValidateWebhookURL(target.WebhookURL); err != nil {
|
||||
w.fail(ctx, c, 0, fmt.Sprintf("webhook_url no longer valid: %v", err))
|
||||
return
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target.WebhookURL, bytes.NewReader(c.payload))
|
||||
if err != nil {
|
||||
w.fail(ctx, c, 0, fmt.Sprintf("building request: %v", err))
|
||||
|
||||
@@ -151,6 +151,10 @@ func (h *Handler) handleCreateTarget(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, http.StatusBadRequest, "webhook_url must not be empty")
|
||||
return
|
||||
}
|
||||
if err := notifystore.ValidateWebhookURL(target.WebhookURL); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "webhook_url: "+err.Error())
|
||||
return
|
||||
}
|
||||
if err := h.targets.Create(r.Context(), &target); err != nil {
|
||||
h.logger.Error("creating notification target", "error", err)
|
||||
writeError(w, http.StatusInternalServerError, "creating notification target failed")
|
||||
|
||||
@@ -231,12 +231,29 @@ func TestCreateTargetRejectsInvalidKind(t *testing.T) {
|
||||
|
||||
func TestCreateSlackTarget(t *testing.T) {
|
||||
mux := newTestMux(newFakeRuleStore(), newFakeTargetStore(), &fakeDeliveryReader{})
|
||||
rec := doRequest(t, mux, http.MethodPost, "/targets", `{"name": "oncall", "kind": "slack", "webhook_url": "https://hooks.slack.com/services/x"}`)
|
||||
// A literal public IP, not a real hostname like hooks.slack.com --
|
||||
// ValidateWebhookURL (see notifystore/ssrf.go) now resolves the
|
||||
// target host and rejects internal/metadata addresses, so this test
|
||||
// stays deterministic without depending on live DNS; ssrf_test.go
|
||||
// covers the validation logic itself in depth.
|
||||
rec := doRequest(t, mux, http.MethodPost, "/targets", `{"name": "oncall", "kind": "slack", "webhook_url": "https://8.8.8.8/services/x"}`)
|
||||
if rec.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateTargetRejectsSSRFWebhookURL is the regression test for the
|
||||
// security-audit finding that target creation performed no URL
|
||||
// validation at all -- any authenticated user could point a webhook at
|
||||
// an internal or cloud-metadata address.
|
||||
func TestCreateTargetRejectsSSRFWebhookURL(t *testing.T) {
|
||||
mux := newTestMux(newFakeRuleStore(), newFakeTargetStore(), &fakeDeliveryReader{})
|
||||
rec := doRequest(t, mux, http.MethodPost, "/targets", `{"name": "x", "kind": "webhook", "webhook_url": "http://169.254.169.254/latest/meta-data/"}`)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400; body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestListDeliveriesForRule(t *testing.T) {
|
||||
deliveries := &fakeDeliveryReader{entries: []rulestore.DeliveryLogEntry{
|
||||
{ID: 1, RuleID: "rule-1", EventType: "firing", Status: "sent"},
|
||||
|
||||
@@ -22,3 +22,27 @@ func WithCORS(next http.Handler, allowedOrigin string) http.Handler {
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
// WithCredentialedCORS is WithCORS's sibling for local login (see
|
||||
// /docs -- deployment runbook): once alerting requires a session
|
||||
// cookie/bearer token (sessioncheck.RequireSession), a browser calling
|
||||
// it cross-origin must send credentials, and browsers categorically
|
||||
// refuse to combine a credentialed request with
|
||||
// Access-Control-Allow-Origin: "*" -- allowedOrigin must be a real,
|
||||
// literal origin, not the wildcard WithCORS's own zero-config default
|
||||
// relies on. Deliberately duplicated from api/httpserver's identical
|
||||
// function rather than shared, same convention as WithCORS's own doc
|
||||
// comment above.
|
||||
func WithCredentialedCORS(next http.Handler, allowedOrigin string) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", allowedOrigin)
|
||||
w.Header().Set("Access-Control-Allow-Credentials", "true")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
package notifystore
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
// ValidateWebhookURL rejects a notification target URL that resolves to
|
||||
// an internal, loopback, link-local, or cloud-metadata address --
|
||||
// closes an SSRF path a security audit found: without this, any user
|
||||
// who could create a notification target could point
|
||||
// delivery.Worker.attempt's outbound POST at
|
||||
// http://169.254.169.254/... or an internal service address, and read
|
||||
// back what happened via delivery_log's recorded status code -- a
|
||||
// semi-blind SSRF oracle. Applies to all three Kind values (webhook,
|
||||
// slack, pagerduty), since all three deliver through the same
|
||||
// WebhookURL-addressed POST -- see webhook.go's package doc comment.
|
||||
//
|
||||
// Callers should invoke this both at target-creation time
|
||||
// (httpapi.handleCreateTarget) and again immediately before every
|
||||
// delivery attempt (delivery.Worker.attempt): a hostname that resolved
|
||||
// to a public IP at creation time can be repointed at an internal one
|
||||
// later (DNS rebinding), so checking only once would leave that gap
|
||||
// open.
|
||||
func ValidateWebhookURL(raw string) error {
|
||||
u, err := url.Parse(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid URL: %w", err)
|
||||
}
|
||||
if u.Scheme != "http" && u.Scheme != "https" {
|
||||
return fmt.Errorf("URL scheme must be http or https, got %q", u.Scheme)
|
||||
}
|
||||
host := u.Hostname()
|
||||
if host == "" {
|
||||
return fmt.Errorf("URL must have a host")
|
||||
}
|
||||
|
||||
ips, err := net.LookupIP(host)
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolving host %q: %w", host, err)
|
||||
}
|
||||
if len(ips) == 0 {
|
||||
return fmt.Errorf("host %q did not resolve to any address", host)
|
||||
}
|
||||
for _, ip := range ips {
|
||||
if isDisallowedWebhookTarget(ip) {
|
||||
return fmt.Errorf("host %q resolves to %s, a disallowed address -- internal, loopback, link-local, and cloud-metadata addresses are not allowed as notification target URLs", host, ip)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isDisallowedWebhookTarget covers RFC1918/RFC4193 private ranges,
|
||||
// loopback, link-local (which also covers 169.254.169.254, the AWS/GCP/
|
||||
// Azure instance-metadata address), unspecified, and multicast.
|
||||
func isDisallowedWebhookTarget(ip net.IP) bool {
|
||||
return ip.IsLoopback() ||
|
||||
ip.IsLinkLocalUnicast() ||
|
||||
ip.IsLinkLocalMulticast() ||
|
||||
ip.IsPrivate() ||
|
||||
ip.IsUnspecified() ||
|
||||
ip.IsMulticast()
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package notifystore
|
||||
|
||||
import "testing"
|
||||
|
||||
// Uses literal IP addresses throughout, not real hostnames -- net.LookupIP
|
||||
// resolves a literal IP without a network round trip, so these tests stay
|
||||
// deterministic and fast in any environment, including one with no DNS/
|
||||
// network access.
|
||||
func TestValidateWebhookURLRejectsInternalAndMetadataAddresses(t *testing.T) {
|
||||
disallowed := []string{
|
||||
"http://169.254.169.254/latest/meta-data/", // cloud instance metadata
|
||||
"http://127.0.0.1:8123/", // loopback -- e.g. ClickHouse
|
||||
"http://10.0.0.5:5432/", // RFC1918
|
||||
"http://172.17.0.2:9092/", // RFC1918 (default docker bridge range)
|
||||
"http://192.168.1.1/", // RFC1918
|
||||
"http://[::1]/", // IPv6 loopback
|
||||
"http://[fe80::1]/", // IPv6 link-local
|
||||
"http://[fc00::1]/", // IPv6 unique local (RFC4193)
|
||||
"http://0.0.0.0/", // unspecified
|
||||
}
|
||||
for _, u := range disallowed {
|
||||
if err := ValidateWebhookURL(u); err == nil {
|
||||
t.Errorf("ValidateWebhookURL(%q): want error, got nil", u)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWebhookURLAllowsPublicAddress(t *testing.T) {
|
||||
// A real-looking public IP literal, not a hostname needing DNS.
|
||||
if err := ValidateWebhookURL("https://8.8.8.8/webhook"); err != nil {
|
||||
t.Errorf("ValidateWebhookURL on a public IP: err = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWebhookURLRejectsBadScheme(t *testing.T) {
|
||||
cases := []string{"ftp://8.8.8.8/", "file:///etc/passwd", "not-a-url"}
|
||||
for _, u := range cases {
|
||||
if err := ValidateWebhookURL(u); err == nil {
|
||||
t.Errorf("ValidateWebhookURL(%q): want error, got nil", u)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateWebhookURLRejectsEmptyHost(t *testing.T) {
|
||||
if err := ValidateWebhookURL("http:///path"); err == nil {
|
||||
t.Error("ValidateWebhookURL with no host: want error, got nil")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package sessioncheck
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// sessionCookieName must match api/localauth's sessionCookieName
|
||||
// exactly (unexported there too, deliberately duplicated rather than
|
||||
// imported -- see this package's doc comment) -- the same cookie
|
||||
// api/localauth.Handler.setCookie writes, scoped (via SESSION_COOKIE_
|
||||
// DOMAIN) to cover both api's and alerting's subdomains in production.
|
||||
const sessionCookieName = "sentry_local_session"
|
||||
|
||||
type errorResponse struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
_ = json.NewEncoder(w).Encode(errorResponse{Error: "unauthorized"})
|
||||
}
|
||||
|
||||
func writeForbidden(w http.ResponseWriter) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
_ = json.NewEncoder(w).Encode(errorResponse{Error: "forbidden"})
|
||||
}
|
||||
|
||||
// mutatingRoleFloor is the minimum role RequireSession enforces for any
|
||||
// non-read request -- closes a real gap the security audit found: this
|
||||
// package used to be a pure "logged in or not" gate with no role check
|
||||
// at all, meaning a Viewer-role session could create/delete alert rules
|
||||
// and notification targets exactly like an Editor. GET/HEAD (read-only)
|
||||
// stay at "any valid session," matching every role floor in this
|
||||
// codebase's other RBAC-gated resources (queries, dashboards) using
|
||||
// Viewer as their read bar.
|
||||
const mutatingRoleFloor = "editor"
|
||||
|
||||
func isReadOnly(method string) bool {
|
||||
return method == http.MethodGet || method == http.MethodHead
|
||||
}
|
||||
|
||||
func credentialFromRequest(r *http.Request) string {
|
||||
if auth := r.Header.Get("Authorization"); auth != "" {
|
||||
const prefix = "Bearer "
|
||||
if len(auth) > len(prefix) && auth[:len(prefix)] == prefix {
|
||||
return auth[len(prefix):]
|
||||
}
|
||||
}
|
||||
if cookie, err := r.Cookie(sessionCookieName); err == nil {
|
||||
return cookie.Value
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// RequireSession wraps next so every request needs a valid local-login
|
||||
// session -- a blanket gate, not per-route roles: alerting has no
|
||||
// role-check plumbing at all today (unlike api/authz's per-route
|
||||
// RequireRole), and building a full parallel system just for this
|
||||
// feature is out of scope (see /docs/agent-management-design.md-style
|
||||
// "resist scope creep" discipline this codebase applies everywhere).
|
||||
// GET /healthz is deliberately exempt -- Docker's HEALTHCHECK execs
|
||||
// this same binary against itself over loopback (cmd/alerting/main.go's
|
||||
// runHealthcheck), pre-auth, and must keep working regardless of
|
||||
// whether local auth is enabled.
|
||||
func RequireSession(checker *Checker, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/healthz" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
raw := credentialFromRequest(r)
|
||||
if raw == "" {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
role, err := checker.Validate(r.Context(), raw)
|
||||
if err != nil {
|
||||
writeUnauthorized(w)
|
||||
return
|
||||
}
|
||||
if !isReadOnly(r.Method) && !roleSatisfies(role, mutatingRoleFloor) {
|
||||
writeForbidden(w)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Package sessioncheck is alerting's half of local login (see
|
||||
// api/localauth's package doc comment for the full feature). It only
|
||||
// ever validates an already-issued session against the shared
|
||||
// local_sessions table api/localauth writes to (same Postgres, no Go
|
||||
// import) -- it never handles a raw password, never creates a session,
|
||||
// and has no user-management surface at all; that stays exclusively in
|
||||
// api. Deliberately its own small package rather than an import of
|
||||
// api/localauth: this repo's hard, documented convention is no shared
|
||||
// Go store/HTTP code between api and alerting, only /proto (see
|
||||
// alerting/internal/httpserver/cors.go's WithCORS doc comment) --
|
||||
// duplicating this one hash-and-look-up check is a small, low-risk
|
||||
// price for keeping that boundary real.
|
||||
package sessioncheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrInvalidSession = errors.New("sessioncheck: invalid or expired session")
|
||||
|
||||
type Checker struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewChecker(pool *pgxpool.Pool) *Checker {
|
||||
return &Checker{pool: pool}
|
||||
}
|
||||
|
||||
// roleRank duplicates api/authz.Role's rank table -- same "no shared Go
|
||||
// code between api and alerting" boundary this package's doc comment
|
||||
// already explains for hashToken, applied to the one extra column
|
||||
// (role) middleware.go now needs to enforce a floor on mutating
|
||||
// requests (see RequireSession).
|
||||
var roleRank = map[string]int{"viewer": 1, "editor": 2, "admin": 3, "owner": 4}
|
||||
|
||||
// roleSatisfies reports whether role meets minRole on the same
|
||||
// Viewer<Editor<Admin<Owner scale api/authz.Role.Satisfies uses.
|
||||
func roleSatisfies(role, minRole string) bool {
|
||||
return roleRank[role] >= roleRank[minRole]
|
||||
}
|
||||
|
||||
// Validate hashes raw (plain SHA-256, no bcrypt -- see
|
||||
// api/localauth/token.go's hashToken doc comment for why a session
|
||||
// token doesn't need bcrypt's deliberate slowness) and checks it
|
||||
// against local_sessions, returning the session's role snapshot
|
||||
// alongside. Returns ErrInvalidSession for both "no such session" and
|
||||
// "expired" -- middleware.go's caller doesn't distinguish them either,
|
||||
// same posture api/localauth.Store.GetSession already takes for the
|
||||
// same two cases.
|
||||
func (c *Checker) Validate(ctx context.Context, raw string) (role string, err error) {
|
||||
sum := sha256.Sum256([]byte(raw))
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
|
||||
var expiresAt time.Time
|
||||
err = c.pool.QueryRow(ctx, `SELECT role, expires_at FROM local_sessions WHERE token_hash = $1`, hash).Scan(&role, &expiresAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return "", ErrInvalidSession
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
if expiresAt.Before(time.Now()) {
|
||||
return "", ErrInvalidSession
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// Exercises Checker.Validate against a real local_sessions row --
|
||||
// unlike a fake, this confirms alerting can actually read the rows
|
||||
// api/localauth (a separate Go module/service) writes into the shared
|
||||
// Postgres, including the exact hash function agreeing on both sides.
|
||||
// Same "skip unless a live-Postgres env var is set" convention as
|
||||
// api/dashboards/store_integration_test.go.
|
||||
//
|
||||
// Skipped unless SESSIONCHECK_TEST_POSTGRES_ADDR is set; run via:
|
||||
//
|
||||
// docker run --rm --network sentry_default -v $(pwd)/../../..:/src -w /src/alerting \
|
||||
// -e SESSIONCHECK_TEST_POSTGRES_ADDR=metadata-postgres:5432 \
|
||||
// -e SESSIONCHECK_TEST_POSTGRES_PASSWORD=sentry-dev-only \
|
||||
// golang:1.25-alpine go test ./internal/sessioncheck/... -run Integration -v
|
||||
package sessioncheck
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
func integrationPool(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
addr := os.Getenv("SESSIONCHECK_TEST_POSTGRES_ADDR")
|
||||
if addr == "" {
|
||||
t.Skip("SESSIONCHECK_TEST_POSTGRES_ADDR not set -- skipping live-Postgres integration test")
|
||||
}
|
||||
password := os.Getenv("SESSIONCHECK_TEST_POSTGRES_PASSWORD")
|
||||
dsn := fmt.Sprintf("postgres://sentry:%s@%s/sentry_metadata", password, addr)
|
||||
pool, err := pgxpool.New(context.Background(), dsn)
|
||||
if err != nil {
|
||||
t.Fatalf("opening pool: %v", err)
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
return pool
|
||||
}
|
||||
|
||||
// insertTestSession writes directly into local_sessions and users --
|
||||
// this package has no Store type of its own (see package doc comment:
|
||||
// creating a session is api/localauth's job, this only ever validates
|
||||
// one), so a real row has to come from somewhere for the test to check
|
||||
// against.
|
||||
func insertTestSession(t *testing.T, pool *pgxpool.Pool, ttl time.Duration) (raw string) {
|
||||
t.Helper()
|
||||
return insertTestSessionWithRole(t, pool, ttl, "viewer")
|
||||
}
|
||||
|
||||
func insertTestSessionWithRole(t *testing.T, pool *pgxpool.Pool, ttl time.Duration, role string) (raw string) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
|
||||
userID := uuid.NewString()
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO users (id, username, password_hash, display_name, created_at, updated_at)
|
||||
VALUES ($1, $2, 'unused', $2, now(), now())`,
|
||||
userID, "test-"+userID[:8]); err != nil {
|
||||
t.Fatalf("inserting test user: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _, _ = pool.Exec(context.Background(), `DELETE FROM users WHERE id = $1`, userID) })
|
||||
|
||||
buf := make([]byte, 32)
|
||||
sum := sha256.Sum256([]byte(userID + role)) // deterministic-enough per-test randomness without crypto/rand here
|
||||
copy(buf, sum[:])
|
||||
raw = base64.RawURLEncoding.EncodeToString(buf)
|
||||
hashSum := sha256.Sum256([]byte(raw))
|
||||
hash := hex.EncodeToString(hashSum[:])
|
||||
|
||||
if _, err := pool.Exec(ctx, `
|
||||
INSERT INTO local_sessions (id, user_id, tenant_id, role, token_hash, expires_at)
|
||||
VALUES ($1, $2, 'default', $3, $4, $5)`,
|
||||
uuid.NewString(), userID, role, hash, time.Now().Add(ttl)); err != nil {
|
||||
t.Fatalf("inserting test session: %v", err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestIntegrationValidateAcceptsRealSession(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
raw := insertTestSession(t, pool, time.Hour)
|
||||
|
||||
role, err := NewChecker(pool).Validate(context.Background(), raw)
|
||||
if err != nil {
|
||||
t.Errorf("Validate on a real, unexpired session: err = %v, want nil", err)
|
||||
}
|
||||
if role != "viewer" {
|
||||
t.Errorf("role = %q, want %q (matches insertTestSession's role column)", role, "viewer")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationValidateRejectsExpiredSession(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
raw := insertTestSession(t, pool, -time.Hour)
|
||||
|
||||
if _, err := NewChecker(pool).Validate(context.Background(), raw); !errors.Is(err, ErrInvalidSession) {
|
||||
t.Errorf("Validate on an expired session: err = %v, want ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationValidateRejectsUnknownToken(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
|
||||
if _, err := NewChecker(pool).Validate(context.Background(), "not-a-real-token"); !errors.Is(err, ErrInvalidSession) {
|
||||
t.Errorf("Validate on an unknown token: err = %v, want ErrInvalidSession", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegrationRequireSessionForbidsMutatingRequestFromViewer is the
|
||||
// regression test for the security-audit finding that this middleware
|
||||
// used to be a pure "logged in or not" gate: a Viewer-role session
|
||||
// could create/delete alert rules and notification targets exactly like
|
||||
// an Editor. A POST from a Viewer session must now be 403, not passed
|
||||
// through to the handler.
|
||||
func TestIntegrationRequireSessionForbidsMutatingRequestFromViewer(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
raw := insertTestSessionWithRole(t, pool, time.Hour, "viewer")
|
||||
|
||||
called := false
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { called = true; w.WriteHeader(http.StatusOK) })
|
||||
handler := RequireSession(NewChecker(pool), next)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/targets", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Errorf("status = %d, want 403", rec.Code)
|
||||
}
|
||||
if called {
|
||||
t.Error("handler must not run for a Viewer's mutating request")
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegrationRequireSessionAllowsMutatingRequestFromEditor is the
|
||||
// positive counterpart: an Editor-role session (the new floor) must
|
||||
// still be able to reach mutating routes.
|
||||
func TestIntegrationRequireSessionAllowsMutatingRequestFromEditor(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
raw := insertTestSessionWithRole(t, pool, time.Hour, "editor")
|
||||
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
handler := RequireSession(NewChecker(pool), next)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/targets", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegrationRequireSessionAllowsReadFromViewer confirms the read
|
||||
// path is untouched: GET still only needs a valid session, any role.
|
||||
func TestIntegrationRequireSessionAllowsReadFromViewer(t *testing.T) {
|
||||
pool := integrationPool(t)
|
||||
raw := insertTestSessionWithRole(t, pool, time.Hour, "viewer")
|
||||
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) })
|
||||
handler := RequireSession(NewChecker(pool), next)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/targets", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+raw)
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Errorf("status = %d, want 200", rec.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package sessioncheck
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRoleSatisfies(t *testing.T) {
|
||||
cases := []struct {
|
||||
role, min string
|
||||
want bool
|
||||
}{
|
||||
{"viewer", "editor", false},
|
||||
{"editor", "editor", true},
|
||||
{"admin", "editor", true},
|
||||
{"owner", "editor", true},
|
||||
{"", "editor", false}, // unknown/empty role never satisfies a real floor
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := roleSatisfies(c.role, c.min); got != c.want {
|
||||
t.Errorf("roleSatisfies(%q, %q) = %v, want %v", c.role, c.min, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsReadOnly(t *testing.T) {
|
||||
if !isReadOnly("GET") || !isReadOnly("HEAD") {
|
||||
t.Error("GET/HEAD should be read-only")
|
||||
}
|
||||
for _, m := range []string{"POST", "PUT", "DELETE", "PATCH"} {
|
||||
if isReadOnly(m) {
|
||||
t.Errorf("%s should not be read-only", m)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user