Files
seaweedfs/weed/command/worker_runtime.go
397a156104 security: a fips.mode setting that Go checks against GODEBUG and the Rust binaries apply to TLS (#13029)
* util: refuse to start when fips.mode in security.toml disagrees with GODEBUG

security.toml gains [fips] mode = "off" | "on" | "strict", also settable
as WEED_FIPS_MODE: one setting that states the FIPS 140-3 mode of every
process in a deployment, so the Rust binaries, which do not run on the Go
runtime, can follow it. Go processes keep taking their behaviour from
GODEBUG=fips140 and now check it against the setting:
LoadSecurityConfiguration and `weed worker` exit when "off" runs without
fips140=off, "on" without fips140=on, or "strict" without fips140=only,
naming the setting and the GODEBUG value it needs. An unknown value is
refused; unset or empty changes nothing.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust: fips.mode with FIPS-mode TLS in weed-volume, weed-worker and weed-vector

seaweed-common gains a fips module: FipsMode resolved from fips.mode in
the security.toml a binary uses, with WEED_FIPS_MODE over it. Each binary
resolves it once at startup, logs it and installs the matching rustls
provider as the process default, refusing to start on an unknown value or
when another provider was installed first.

Under "on" and "strict" the provider is aws-lc-rs filtered to the lists
Go's crypto/tls applies in FIPS mode: TLS 1.3 AES-GCM suites and TLS 1.2
ECDHE AES-GCM suites (no ChaCha20-Poly1305), X25519MLKEM768,
SecP256r1MLKEM768, P-256 and P-384 (no plain X25519), Go's ten signature
schemes (no ML-DSA). Configurations SeaweedFS builds require the Extended
Master Secret in that mode, and the volume server refuses a non-FIPS suite
in tls.cipher_suites instead of falling back. sw-client installs the same
provider instead of ring. Unset or "off" keeps aws-lc-rs's default
provider unchanged.

This is behavioural parity only: the provider still runs on the
non-validated aws-lc-rs build.

Refs #12839

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* util: refuse a fips.mode that is not a string

viper's GetString turns an array or a table into "", so mode = ["strict"]
under [fips] skipped the GODEBUG check while the Rust binaries refused the
same file. RequireFipsMode now reads the raw value (ViperProxy.Get, under
its lock) and exits when it is not a string, naming its source; an absent
or empty value still means unset, and WEED_FIPS_MODE still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* rust: read fips.mode with the parser that reads the JWT keys

seaweed_common::fips::resolve parsed security.toml with the toml crate,
while the volume server reads the rest of the file with its own lenient
loader. A file with [fips] mode = "on" beside an unquoted value the loader
accepts resolved to off and logged "fips.mode unset", although the JWT
keys from the same file were applied. Each binary now reads fips.mode
with the loader it uses for everything else and hands the value to
resolve: the volume server through its line parser, the worker and vector
engine through their parsed Security table, which already refuses a file
that is not TOML. A security.toml the volume server finds but cannot read
stops startup. A missing setting is still off, and WEED_FIPS_MODE still
wins. seaweed-common no longer depends on toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* sw-client: offer only FIPS signature schemes with insecure_skip_verify

With https.client.insecure_skip_verify, reqwest installs its own verifier,
which advertises a fixed scheme list including SHA-1 and Ed448 whatever
the process provider allows. In FIPS mode the volume transport now builds
its rustls configuration itself on the process provider: the server
certificate and host name are not checked, as the setting asks, but
handshake signatures are verified with the provider's algorithms, only its
schemes are offered, and TLS 1.2 requires the Extended Master Secret.
Outside FIPS mode the reqwest path is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* seaweed-common: sign only with Go 1.27's FIPS schemes, allow ML-DSA

The FIPS provider kept aws-lc-rs's key provider, so a FIPS-mode listener
signed handshakes with whatever scheme its key and the peer agreed on,
outside the list the provider verifies with. Keys now load through a
provider that limits each key to the FIPS signature schemes and refuses a
key that can sign none of them, such as Ed448; the volume server and the
worker's gRPC TLS name the certificate and key files in that error.

The lists follow Go 1.27.4, which go.mod now requires: its
defaults_fips140.go allows ML-DSA-44, -65 and -87 as signature schemes and
ML-DSA certificate keys (for Go's native module only), so they are allowed
here as well. Go also allows MLKEM1024 but does not enable it by default,
so it stays out of the key exchange list as in Go's defaults. "off" keeps
the default key provider.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* mount: skip the truncate manifest test on freebsd like its fake filer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Chris Lu <chrislusf@users.noreply.github.com>
2026-11-27 12:47:44 -08:00

288 lines
8.6 KiB
Go

package command
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"strconv"
"strings"
"syscall"
"time"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/seaweedfs/seaweedfs/weed/glog"
pluginworker "github.com/seaweedfs/seaweedfs/weed/plugin/worker"
_ "github.com/seaweedfs/seaweedfs/weed/plugin/worker/handlers" // register all handler subpackages
"github.com/seaweedfs/seaweedfs/weed/security"
statsCollect "github.com/seaweedfs/seaweedfs/weed/stats"
"github.com/seaweedfs/seaweedfs/weed/util"
"github.com/seaweedfs/seaweedfs/weed/util/version"
"github.com/seaweedfs/seaweedfs/weed/worker"
"google.golang.org/grpc"
)
const defaultPluginWorkerJobTypes = "all"
type pluginWorkerRunOptions struct {
AdminServer string
WorkerID string
WorkingDir string
JobTypes string
Heartbeat time.Duration
Reconnect time.Duration
MaxDetect int
MaxExecute int
Address string
MetricsPort int
MetricsIP string
}
func runPluginWorkerWithOptions(options pluginWorkerRunOptions) bool {
util.LoadConfiguration("security", false)
util.RequireFipsMode()
options.AdminServer = strings.TrimSpace(options.AdminServer)
if options.AdminServer == "" {
options.AdminServer = fmt.Sprintf("localhost:%d", defaultAdminHTTPPort)
}
options.JobTypes = strings.TrimSpace(options.JobTypes)
if options.JobTypes == "" {
options.JobTypes = defaultPluginWorkerJobTypes
}
if options.Heartbeat <= 0 {
options.Heartbeat = 15 * time.Second
}
if options.Reconnect <= 0 {
options.Reconnect = 5 * time.Second
}
if options.MaxDetect <= 0 {
options.MaxDetect = 1
}
if options.MaxExecute <= 0 {
options.MaxExecute = 4
}
options.MetricsIP = strings.TrimSpace(options.MetricsIP)
if options.MetricsIP == "" {
options.MetricsIP = "0.0.0.0"
}
resolvedAdminServer := resolvePluginWorkerAdminServer(options.AdminServer)
if resolvedAdminServer != options.AdminServer {
fmt.Printf("Resolved admin worker gRPC endpoint: %s -> %s\n", options.AdminServer, resolvedAdminServer)
}
dialOption := security.LoadClientTLS(util.GetViper(), "grpc.worker")
workerID, err := resolvePluginWorkerID(options.WorkerID, options.WorkingDir)
if err != nil {
glog.Errorf("Failed to resolve plugin worker ID: %v", err)
return false
}
handlers, err := buildPluginWorkerHandlers(options.JobTypes, dialOption, options.MaxExecute, options.WorkingDir, options.Address)
if err != nil {
glog.Errorf("Failed to build plugin worker handlers: %v", err)
return false
}
worker, err := pluginworker.NewWorker(pluginworker.WorkerOptions{
AdminServer: resolvedAdminServer,
WorkerID: workerID,
WorkerVersion: version.Version(),
WorkerAddress: options.Address,
HeartbeatInterval: options.Heartbeat,
ReconnectDelay: options.Reconnect,
MaxDetectionConcurrency: options.MaxDetect,
MaxExecutionConcurrency: options.MaxExecute,
GrpcDialOption: dialOption,
Handlers: handlers,
})
if err != nil {
glog.Errorf("Failed to create plugin worker: %v", err)
return false
}
if options.MetricsPort > 0 {
go startPluginWorkerMetricsServer(options.MetricsIP, options.MetricsPort, worker)
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigCh := make(chan os.Signal, 1)
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
defer signal.Stop(sigCh)
go func() {
sig := <-sigCh
fmt.Printf("\nReceived signal %v, stopping plugin worker...\n", sig)
cancel()
}()
fmt.Printf("Starting plugin worker (admin=%s)\n", resolvedAdminServer)
if err := worker.Run(ctx); err != nil {
glog.Errorf("Plugin worker stopped with error: %v", err)
return false
}
fmt.Println("Plugin worker stopped")
return true
}
func resolvePluginWorkerID(explicitID string, workingDir string) (string, error) {
if explicitID != "" {
return explicitID, nil
}
// Use the same ID generation/loading logic as the standard worker
return worker.GenerateOrLoadWorkerID(workingDir)
}
// buildPluginWorkerHandlers resolves the comma-separated jobTypes string
// (which may contain category names like "all", "default", "heavy" and/or
// explicit job type names/aliases) into a deduplicated slice of JobHandlers.
func buildPluginWorkerHandlers(jobTypes string, dialOption grpc.DialOption, maxExecute int, workingDir string, workerAddress ...string) ([]pluginworker.JobHandler, error) {
jobTypes = strings.TrimSpace(jobTypes)
if jobTypes == "" {
jobTypes = defaultPluginWorkerJobTypes
}
factories, err := pluginworker.ResolveHandlerFactories(jobTypes)
if err != nil {
return nil, err
}
addr := ""
if len(workerAddress) > 0 {
addr = strings.TrimSpace(workerAddress[0])
}
opts := pluginworker.HandlerBuildOptions{
GrpcDialOption: dialOption,
MaxExecute: maxExecute,
WorkingDir: workingDir,
WorkerAddress: addr,
}
handlers := make([]pluginworker.JobHandler, 0, len(factories))
for _, f := range factories {
handler, buildErr := f.Build(opts)
if buildErr != nil {
return nil, fmt.Errorf("building handler for %q: %w", f.JobType, buildErr)
}
handlers = append(handlers, handler)
}
return handlers, nil
}
func resolvePluginWorkerAdminServer(adminServer string) string {
adminServer = strings.TrimSpace(adminServer)
host, httpPort, hasExplicitGrpcPort, err := parsePluginWorkerAdminAddress(adminServer)
if err != nil || hasExplicitGrpcPort {
return adminServer
}
workerGrpcPort, err := fetchPluginWorkerGrpcPort(host, httpPort)
if err != nil || workerGrpcPort <= 0 {
return adminServer
}
// Keep canonical host:http form when admin gRPC follows the default +10000 rule.
if workerGrpcPort == httpPort+10000 {
return adminServer
}
return fmt.Sprintf("%s:%d.%d", host, httpPort, workerGrpcPort)
}
func parsePluginWorkerAdminAddress(adminServer string) (host string, httpPort int, hasExplicitGrpcPort bool, err error) {
adminServer = strings.TrimSpace(adminServer)
colonIndex := strings.LastIndex(adminServer, ":")
if colonIndex <= 0 || colonIndex >= len(adminServer)-1 {
return "", 0, false, fmt.Errorf("invalid admin address %q", adminServer)
}
host = adminServer[:colonIndex]
portPart := adminServer[colonIndex+1:]
if dotIndex := strings.LastIndex(portPart, "."); dotIndex > 0 && dotIndex < len(portPart)-1 {
if _, parseErr := strconv.Atoi(portPart[dotIndex+1:]); parseErr == nil {
hasExplicitGrpcPort = true
portPart = portPart[:dotIndex]
}
}
httpPort, err = strconv.Atoi(portPart)
if err != nil || httpPort <= 0 {
return "", 0, false, fmt.Errorf("invalid admin http port in %q", adminServer)
}
return host, httpPort, hasExplicitGrpcPort, nil
}
func fetchPluginWorkerGrpcPort(host string, httpPort int) (int, error) {
client := &http.Client{Timeout: 2 * time.Second}
address := util.JoinHostPort(host, httpPort)
var lastErr error
for _, scheme := range []string{"http", "https"} {
statusURL := fmt.Sprintf("%s://%s/api/plugin/status", scheme, address)
resp, err := client.Get(statusURL)
if err != nil {
lastErr = err
continue
}
var payload struct {
WorkerGrpcPort int `json:"worker_grpc_port"`
}
decodeErr := json.NewDecoder(resp.Body).Decode(&payload)
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
lastErr = fmt.Errorf("status code %d from %s", resp.StatusCode, statusURL)
continue
}
if decodeErr != nil {
lastErr = fmt.Errorf("decode plugin status from %s: %w", statusURL, decodeErr)
continue
}
if payload.WorkerGrpcPort <= 0 {
lastErr = fmt.Errorf("plugin status from %s returned empty worker_grpc_port", statusURL)
continue
}
return payload.WorkerGrpcPort, nil
}
if lastErr == nil {
lastErr = fmt.Errorf("plugin status endpoint unavailable")
}
return 0, lastErr
}
func pluginWorkerHealthHandler(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusOK)
}
func pluginWorkerReadyHandler(pluginRuntime *pluginworker.Worker) http.HandlerFunc {
return func(w http.ResponseWriter, _ *http.Request) {
if pluginRuntime == nil || !pluginRuntime.IsConnected() {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
w.WriteHeader(http.StatusOK)
}
}
func startPluginWorkerMetricsServer(ip string, port int, pluginRuntime *pluginworker.Worker) {
mux := http.NewServeMux()
mux.HandleFunc("/health", pluginWorkerHealthHandler)
mux.HandleFunc("/ready", pluginWorkerReadyHandler(pluginRuntime))
mux.Handle("/metrics", promhttp.HandlerFor(statsCollect.Gather, promhttp.HandlerOpts{}))
glog.V(0).Infof("Starting plugin worker metrics server at %s", statsCollect.JoinHostPort(ip, port))
if err := http.ListenAndServe(statsCollect.JoinHostPort(ip, port), mux); err != nil {
glog.Errorf("Plugin worker metrics server failed to start: %v", err)
}
}