Files
cairnobs/alerting/internal/sessioncheck/sessioncheck.go
T
jcoffey-dev 4b5dae5879 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.
2026-08-18 23:53:20 -07:00

74 lines
2.7 KiB
Go

// 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
}