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:
2026-08-18 23:53:20 -07:00
parent d2bb9de245
commit 4b5dae5879
87 changed files with 5095 additions and 164 deletions
+205
View File
@@ -0,0 +1,205 @@
// Command surface for api/localauth -- single-tenant mode's local
// username/password login and user manager (see /docs -- deployment
// runbook, and api/localauth's package doc comment for the full
// feature). Same list/create/delete shape as agents/dashboards, plus a
// "login" subcommand: unlike every other resource this CLI manages,
// there's no way to get a first SENTRYCTL_TOKEN without one.
package main
import (
"bufio"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func cmdUsers(args []string, stdin io.Reader, stdout, stderr io.Writer) int {
if len(args) == 0 {
fmt.Fprintln(stderr, "sentryctl users: expected a subcommand (login, list, create, delete, reset-password)")
return 1
}
apiURL, rest := extractAPIFlag(args[1:], os.Getenv)
token := resolveToken(os.Getenv)
switch args[0] {
case "login":
if len(rest) == 0 {
fmt.Fprintln(stderr, "sentryctl users login: missing username")
return 1
}
return cmdUsersLogin(rest[0], rest[1:], apiURL, stdin, stdout, stderr)
case "list":
return httpGetJSON(apiURL, "/auth/users", token, stdout, stderr)
case "create":
if len(rest) == 0 {
fmt.Fprintln(stderr, "sentryctl users create: missing username")
return 1
}
return cmdUsersCreate(rest[0], rest[1:], apiURL, token, stdin, stdout, stderr)
case "delete":
if len(rest) == 0 {
fmt.Fprintln(stderr, "sentryctl users delete: missing user id")
return 1
}
return httpMutateNoBody(http.MethodDelete, apiURL, "/auth/users/"+rest[0], token, "", "user deleted", stdout, stderr)
case "reset-password":
if len(rest) == 0 {
fmt.Fprintln(stderr, "sentryctl users reset-password: missing user id")
return 1
}
return cmdUsersResetPassword(rest[0], rest[1:], apiURL, token, stdin, stdout, stderr)
default:
fmt.Fprintf(stderr, "sentryctl users: unknown subcommand %q (want login, list, create, delete, reset-password)\n", args[0])
return 1
}
}
// extractPasswordStdinFlag pulls the boolean --password-stdin flag out
// of args if present -- same "walk args, splice out the one flag this
// caller cares about" shape extractAPIFlag already uses at the
// top-level dispatch layer. Unlike the --password <value> flag this
// replaced (security-audit finding L-4), this flag never carries the
// secret itself -- only readPasswordFromStdin's caller decides to
// actually read one, same "docker login --password-stdin" convention,
// chosen over inventing a new one: a plaintext password passed as a CLI
// argument is visible to any other local user via `ps`/
// `/proc/<pid>/cmdline` and typically lands in shell history too.
func extractPasswordStdinFlag(args []string) (useStdin bool, rest []string) {
for _, a := range args {
if a == "--password-stdin" {
useStdin = true
continue
}
rest = append(rest, a)
}
return useStdin, rest
}
// readPasswordFromStdin reads a single line from stdin. Not masked
// (this codebase has no terminal/raw-mode dependency to draw on -- see
// resolveToken's doc comment for the same tradeoff already accepted for
// SENTRYCTL_TOKEN); pipe the value in (`echo "$PW" | sentryctl users
// login admin`) rather than typing it at an interactive terminal where
// that matters.
func readPasswordFromStdin(stdin io.Reader) (string, error) {
line, err := bufio.NewReader(stdin).ReadString('\n')
if err != nil && line == "" {
return "", err
}
return strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r"), nil
}
type loginRequestBody struct {
Username string `json:"username"`
Password string `json:"password"`
}
type loginResponseBody struct {
Token string `json:"token"`
Error string `json:"error"`
}
// cmdUsersLogin prints only the raw token to stdout on success (nothing
// else) -- deliberately pipeable: `export SENTRYCTL_TOKEN=$(sentryctl
// users login admin)`.
func cmdUsersLogin(username string, _ []string, apiURL string, stdin io.Reader, stdout, stderr io.Writer) int {
password, err := readPasswordFromStdin(stdin)
if err != nil {
fmt.Fprintf(stderr, "reading password: %v\n", err)
return 1
}
body, err := json.Marshal(loginRequestBody{Username: username, Password: password})
if err != nil {
fmt.Fprintf(stderr, "encoding request: %v\n", err)
return 1
}
req, err := http.NewRequest(http.MethodPost, apiURL+"/auth/login", strings.NewReader(string(body)))
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
}
req.Header.Set("Content-Type", "application/json")
resp, err := httpClient.Do(req)
if err != nil {
fmt.Fprintf(stderr, "request failed: %v\n", err)
return 1
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(stderr, "reading response: %v\n", err)
return 1
}
var login loginResponseBody
_ = json.Unmarshal(respBody, &login)
if resp.StatusCode != http.StatusOK {
if login.Error != "" {
fmt.Fprintf(stderr, "login failed: %s\n", login.Error)
} else {
fmt.Fprintf(stderr, "login failed: status %d\n", resp.StatusCode)
}
return 1
}
fmt.Fprintln(stdout, login.Token)
return 0
}
func cmdUsersCreate(username string, flagArgs []string, apiURL, token string, stdin io.Reader, stdout, stderr io.Writer) int {
role := "editor"
for i := 0; i < len(flagArgs); i++ {
if flagArgs[i] == "--role" && i+1 < len(flagArgs) {
role = flagArgs[i+1]
i++
continue
}
}
password, err := readPasswordFromStdin(stdin)
if err != nil {
fmt.Fprintf(stderr, "reading password: %v\n", err)
return 1
}
body, err := json.Marshal(struct {
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}{Username: username, Password: password, Role: role})
if err != nil {
fmt.Fprintf(stderr, "encoding request: %v\n", err)
return 1
}
return httpPostJSON(apiURL, "/auth/users", token, string(body), stdout, stderr)
}
// cmdUsersResetPassword defaults to requesting a server-generated
// random password (empty body -- see api/localauth's handleResetPassword
// doc comment): pass --password-stdin to instead set a specific password
// read from stdin. There is deliberately no --password <value> flag (see
// extractPasswordStdinFlag's doc comment) -- a specific password chosen
// this way must be piped in, never typed as a bare CLI argument.
func cmdUsersResetPassword(id string, flagArgs []string, apiURL, token string, stdin io.Reader, stdout, stderr io.Writer) int {
useStdin, _ := extractPasswordStdinFlag(flagArgs)
body := "{}"
if useStdin {
password, err := readPasswordFromStdin(stdin)
if err != nil {
fmt.Fprintf(stderr, "reading password: %v\n", err)
return 1
}
encoded, err := json.Marshal(struct {
Password string `json:"password"`
}{Password: password})
if err != nil {
fmt.Fprintf(stderr, "encoding request: %v\n", err)
return 1
}
body = string(encoded)
}
return httpPostJSON(apiURL, "/auth/users/"+id+"/reset-password", token, body, stdout, stderr)
}
+190
View File
@@ -0,0 +1,190 @@
package main
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestCmdUsersMissingSubcommand(t *testing.T) {
var stdout, stderr bytes.Buffer
code := cmdUsers(nil, strings.NewReader(""), &stdout, &stderr)
if code != 1 {
t.Fatalf("code = %d, want 1", code)
}
}
func TestCmdUsersLoginPrintsOnlyTheToken(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/auth/login" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
var body loginRequestBody
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Username != "admin" || body.Password != "s3cret!!" {
t.Errorf("unexpected credentials: %+v", body)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"token":"abc123","user_id":"u1","username":"admin","role":"owner"}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"login", "admin", "--api", srv.URL}, strings.NewReader("s3cret!!\n"), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
if got := strings.TrimSpace(stdout.String()); got != "abc123" {
t.Fatalf("stdout = %q, want exactly the raw token (pipeable into SENTRYCTL_TOKEN)", got)
}
}
func TestCmdUsersLoginFailure(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"invalid username or password"}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"login", "admin", "--api", srv.URL}, strings.NewReader("wrong\n"), &stdout, &stderr)
if code != 1 {
t.Fatalf("code = %d, want 1", code)
}
if !strings.Contains(stderr.String(), "invalid username or password") {
t.Fatalf("stderr = %q, want it to surface the server's error message", stderr.String())
}
if stdout.String() != "" {
t.Fatalf("stdout = %q, want empty on failure (nothing pipeable into SENTRYCTL_TOKEN)", stdout.String())
}
}
func TestCmdUsersCreateSuccess(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost || r.URL.Path != "/auth/users" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
var body struct {
Username string `json:"username"`
Password string `json:"password"`
Role string `json:"role"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Role != "viewer" {
t.Errorf("role = %q, want viewer (from --role)", body.Role)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":"u2","username":"bob","role":"viewer"}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"create", "bob", "--role", "viewer", "--api", srv.URL}, strings.NewReader("bobspassword\n"), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
if !strings.Contains(stdout.String(), "bob") {
t.Fatalf("stdout = %q, want it to contain the created user", stdout.String())
}
}
func TestCmdUsersCreateDefaultsRoleToEditor(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Role string `json:"role"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Role != "editor" {
t.Errorf("role = %q, want editor (the default when --role is omitted)", body.Role)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"id":"u2","username":"bob","role":"editor"}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"create", "bob", "--api", srv.URL}, strings.NewReader("bobspassword\n"), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
}
func TestCmdUsersDeleteMissingID(t *testing.T) {
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"delete"}, strings.NewReader(""), &stdout, &stderr)
if code != 1 {
t.Fatalf("code = %d, want 1", code)
}
}
func TestCmdUsersDeleteSuccess(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodDelete || r.URL.Path != "/auth/users/u2" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)
}
w.WriteHeader(http.StatusNoContent)
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"delete", "u2", "--api", srv.URL}, strings.NewReader(""), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
}
func TestCmdUsersResetPasswordWithGeneratedPassword(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/auth/users/u2/reset-password" {
t.Errorf("unexpected path: %s", r.URL.Path)
}
body, _ := io.ReadAll(r.Body)
if strings.TrimSpace(string(body)) != "{}" {
t.Errorf("body = %q, want {} (no --password-stdin supplied)", body)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{"password":"generated-abc"}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"reset-password", "u2", "--api", srv.URL}, strings.NewReader(""), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
if !strings.Contains(stdout.String(), "generated-abc") {
t.Fatalf("stdout = %q, want it to contain the generated password", stdout.String())
}
}
// TestCmdUsersResetPasswordWithStdinPassword is the regression test for
// the security-audit finding that this CLI accepted a plaintext
// --password <value> flag (visible via `ps`/shell history). Setting a
// specific password must go through --password-stdin plus piped input
// instead, never a bare argument.
func TestCmdUsersResetPasswordWithStdinPassword(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body struct {
Password string `json:"password"`
}
_ = json.NewDecoder(r.Body).Decode(&body)
if body.Password != "a-specific-password" {
t.Errorf("password = %q, want the value piped via stdin", body.Password)
}
w.Header().Set("Content-Type", "application/json")
w.Write([]byte(`{}`))
}))
defer srv.Close()
var stdout, stderr bytes.Buffer
code := cmdUsers([]string{"reset-password", "u2", "--password-stdin", "--api", srv.URL}, strings.NewReader("a-specific-password\n"), &stdout, &stderr)
if code != 0 {
t.Fatalf("code = %d, want 0; stderr=%s", code, stderr.String())
}
}
+12 -1
View File
@@ -115,7 +115,18 @@ func httpMutateNoBody(method, baseURL, path, token, body, successMsg string, std
// for callers that construct the body themselves rather than reading it
// from a file (agents config set, agents restart).
func httpPutJSON(baseURL, path, token, body string, stdout, stderr io.Writer) int {
req, err := http.NewRequest(http.MethodPut, baseURL+path, strings.NewReader(body))
return httpSendJSON(http.MethodPut, baseURL, path, token, body, stdout, stderr)
}
// httpPostJSON is httpPutJSON's POST sibling -- for callers creating a
// resource from a body they built themselves rather than reading it
// from a file (users create, users reset-password).
func httpPostJSON(baseURL, path, token, body string, stdout, stderr io.Writer) int {
return httpSendJSON(http.MethodPost, baseURL, path, token, body, stdout, stderr)
}
func httpSendJSON(method, baseURL, path, token, body string, stdout, stderr io.Writer) int {
req, err := http.NewRequest(method, baseURL+path, strings.NewReader(body))
if err != nil {
fmt.Fprintf(stderr, "building request: %v\n", err)
return 1
+18
View File
@@ -40,6 +40,8 @@ func run(args []string, stdout, stderr io.Writer) int {
return cmdAlerts(args[1:], stdout, stderr)
case "agents":
return cmdAgents(args[1:], stdout, stderr)
case "users":
return cmdUsers(args[1:], os.Stdin, stdout, stderr)
case "-h", "--help", "help":
usage(stdout)
return 0
@@ -67,6 +69,11 @@ Usage:
[--heartbeat-enabled true|false] [--heartbeat-interval-ms N]
[--journald-unit UNIT] [--api <url>]
sentryctl agents restart <host> [--yes] [--api <url>]
sentryctl users login <username> [--password <pw>] [--api <url>]
sentryctl users list [--api <url>]
sentryctl users create <username> [--password <pw>] [--role viewer|editor|admin|owner] [--api <url>]
sentryctl users delete <id> [--api <url>]
sentryctl users reset-password <id> [--password <pw>] [--api <url>]
Commands:
ping Checks that the api service is reachable via GET /healthz.
@@ -95,6 +102,17 @@ Commands:
as the web UI's edit form. "restart" briefly interrupts
log collection on that host and prompts for confirmation
unless --yes is given.
users Local username/password login and user management (see
api/localauth -- only meaningful on a deployment with
LOCAL_AUTH_ENABLED set; a 404 on any of these means it
isn't). "login" is the only command that works with no
$SENTRYCTL_TOKEN set yet -- it prints just the raw token
to stdout: `+"`export SENTRYCTL_TOKEN=$(sentryctl users login admin)`"+`.
--password (on any users subcommand) is read from stdin
if omitted -- same shell-history/ps caveat as typing a
credential in any flag, prefer piping it in.
"create"/"list"/"delete"/"reset-password" require an
owner-role token (see RegisterRoutes in api/localauth).
--api defaults to $SENTRYCTL_API_URL, or `+defaultAPIURL+` if unset.
--alerting-api defaults to $SENTRYCTL_ALERTING_API_URL, or `+defaultAlertingURL+` if unset.