diff --git a/weed/remote_storage/s3/s3_storage_client.go b/weed/remote_storage/s3/s3_storage_client.go index cfc4bea700..2f33176711 100644 --- a/weed/remote_storage/s3/s3_storage_client.go +++ b/weed/remote_storage/s3/s3_storage_client.go @@ -230,8 +230,28 @@ func MakeWithHTTPClient(conf *remote_pb.RemoteConf, httpClient *http.Client) (re if httpClient != nil { config.HTTPClient = httpClient } + workload := false + if conf.Type == "s3" { + var err error + if workload, err = workloadCredentialsMode(); err != nil { + return nil, err + } + } if opt.accessKey != "" && opt.secretKey != "" { config.Credentials = credentials.NewStaticCredentials(opt.accessKey, opt.secretKey, "") + } else if workload { + // the process asks for the workload's identity only + // (WEED_REMOTE_S3_CREDENTIALS=workload): never the environment's keys, + // which may be this server's own S3 identity + if opt.accessKey != "" || opt.secretKey != "" { + return nil, fmt.Errorf("%s remote %q has only one of access key and secret; with %s=workload give both or neither", + opt.name, conf.Name, workloadCredentialsEnv) + } + creds, err := workloadCredentials(opt.region) + if err != nil { + return nil, fmt.Errorf("create %s workload credentials: %w", opt.name, err) + } + config.Credentials = creds } else if opt.anonymousWhenNoCreds && opt.accessKey == "" && opt.secretKey == "" && !awsCredentialSourceConfigured() { // Explicitly disable signing for public buckets. When the environment // names an AWS credential source, leave Credentials nil so the SDK @@ -254,10 +274,14 @@ func MakeWithHTTPClient(conf *remote_pb.RemoteConf, httpClient *http.Client) (re config.Credentials = credSess.Config.Credentials } - sess, err := session.NewSessionWithOptions(session.Options{ + sessOpts := session.Options{ Config: *config, SharedConfigState: session.SharedConfigEnable, - }) + } + if workload { + sessOpts.SharedConfigFiles = []string{} + } + sess, err := session.NewSessionWithOptions(sessOpts) if err != nil { return nil, fmt.Errorf("create %s session: %w", opt.name, err) } diff --git a/weed/remote_storage/s3/workload_credentials.go b/weed/remote_storage/s3/workload_credentials.go new file mode 100644 index 0000000000..8f4673c8a8 --- /dev/null +++ b/weed/remote_storage/s3/workload_credentials.go @@ -0,0 +1,93 @@ +package s3 + +import ( + "fmt" + "net/http" + "os" + "strings" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" + "github.com/aws/aws-sdk-go/aws/credentials/stscreds" + "github.com/aws/aws-sdk-go/aws/defaults" + "github.com/aws/aws-sdk-go/aws/endpoints" + "github.com/aws/aws-sdk-go/aws/session" + "github.com/aws/aws-sdk-go/service/sts" + "github.com/seaweedfs/seaweedfs/weed/util" +) + +// WEED_REMOTE_S3_CREDENTIALS chooses where a remote of type "s3" with no +// access key and no secret in its configuration takes its credentials from: +// +// - unset (the default): as before, the SDK default chain when the +// environment names a credential source, else unsigned requests; +// - "workload": the identity of the AWS workload only (web identity, the +// ECS/EKS container credentials endpoint, the EC2 instance role), never +// AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY or a shared credentials file. +// Every keyless "s3" remote of the process is signed with it, a public +// bucket's too: set it only where the process runs as an AWS workload. +// +// The other S3-compatible types (wasabi, b2, filebase, storj, ...) are not +// affected. A remote with only one of the two keys is refused in workload +// mode: falling back to the default chain would sign with the environment's +// keys, which is what the setting rules out. +// +// "workload" exists because a SeaweedFS process often holds keys of its own in +// those variables: `weed mini` and `weed server -s3` read their initial S3 +// identity from AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY. On EC2, a remote +// mounted on an Amazon S3 bucket with the instance's role (no keys) then signed +// with that local identity and every call answered InvalidAccessKeyId, while a +// filer.remote.sync of the same remote, started without those variables, +// worked. +const workloadCredentialsEnv = "WEED_REMOTE_S3_CREDENTIALS" + +// workloadCredentialsMode reports whether workload mode is on; an unknown +// value is an error, so a misspelling never falls back to the environment's +// keys without a word. +func workloadCredentialsMode() (bool, error) { + switch v := strings.TrimSpace(os.Getenv(workloadCredentialsEnv)); v { + case "": + return false, nil + case "workload": + return true, nil + default: + return false, fmt.Errorf("%s=%q: the only value is \"workload\" (or unset)", workloadCredentialsEnv, v) + } +} + +// workloadCredentials is the workload's identity alone: web identity when the +// environment names a token file and a role (EKS IRSA), else the container +// credentials endpoint or the EC2 instance metadata service. STS is asked at +// the regional endpoint (unless AWS_STS_REGIONAL_ENDPOINTS says otherwise) of +// the workload's own region, the bucket's only when the environment names +// none. The session it builds on carries anonymous credentials so that it +// resolves none of its own (a token file without a role would otherwise fail +// every build), and it fetches on an unguarded HTTP client: the guarded one is +// for the storage endpoint and refuses the link-local credential endpoints. +func workloadCredentials(region string) (*credentials.Credentials, error) { + cfg := aws.Config{Region: aws.String(util.Nvl(os.Getenv("AWS_REGION"), os.Getenv("AWS_DEFAULT_REGION"), region)), HTTPClient: &http.Client{}, + Credentials: credentials.AnonymousCredentials} + if os.Getenv("AWS_STS_REGIONAL_ENDPOINTS") == "" { + cfg.STSRegionalEndpoint = endpoints.RegionalSTSEndpoint + } + sess, err := session.NewSessionWithOptions(session.Options{ + Config: cfg, + SharedConfigState: session.SharedConfigDisable, + SharedConfigFiles: []string{}, + }) + if err != nil { + return nil, err + } + if tokenFile, role := os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"), os.Getenv("AWS_ROLE_ARN"); tokenFile != "" && role != "" { + name := os.Getenv("AWS_ROLE_SESSION_NAME") + if name == "" { + name = "seaweedfs-remote" + } + // no fallback: a failed exchange must not sign with the node's role + return credentials.NewCredentials(stscreds.NewWebIdentityRoleProviderWithOptions( + sts.New(sess), role, name, stscreds.FetchTokenPath(tokenFile), + func(p *stscreds.WebIdentityRoleProvider) { p.ExpiryWindow = 5 * time.Minute })), nil + } + return credentials.NewCredentials(defaults.RemoteCredProvider(*sess.Config, sess.Handlers)), nil +} diff --git a/weed/remote_storage/s3/workload_credentials_test.go b/weed/remote_storage/s3/workload_credentials_test.go new file mode 100644 index 0000000000..36c86c7a2b --- /dev/null +++ b/weed/remote_storage/s3/workload_credentials_test.go @@ -0,0 +1,199 @@ +package s3 + +import ( + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/aws/aws-sdk-go/aws" + "github.com/aws/aws-sdk-go/aws/credentials" + awss3 "github.com/aws/aws-sdk-go/service/s3" + "github.com/seaweedfs/seaweedfs/weed/pb/remote_pb" +) + +// fakeIMDS serves an EC2 instance role over IMDSv2: a token, the role's name, +// then its credentials, refused without the token. +func fakeIMDS(t *testing.T) *httptest.Server { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodPut && r.URL.Path == "/latest/api/token": + w.Header().Set("X-Aws-Ec2-Metadata-Token-Ttl-Seconds", "21600") + w.Write([]byte("tok")) + case r.Header.Get("X-Aws-Ec2-Metadata-Token") != "tok": + w.WriteHeader(http.StatusUnauthorized) + case r.URL.Path == "/latest/meta-data/iam/security-credentials/": + w.Write([]byte("cell-role")) + case r.URL.Path == "/latest/meta-data/iam/security-credentials/cell-role": + w.Write([]byte(`{"Code":"Success","Type":"AWS-HMAC","AccessKeyId":"ROLEKEY","SecretAccessKey":"rolesecret","Token":"roletoken","Expiration":"` + + time.Now().Add(time.Hour).UTC().Format(time.RFC3339) + `"}`)) + default: + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(srv.Close) + return srv +} + +func accessKeyOf(t *testing.T, conf *remote_pb.RemoteConf) string { + t.Helper() + c, err := MakeWithHTTPClient(conf, &http.Client{}) + if err != nil { + t.Fatalf("MakeWithHTTPClient: %v", err) + } + v, err := c.(*s3RemoteStorageClient).conn.(*awss3.S3).Config.Credentials.Get() + if err != nil { + t.Fatalf("credentials: %v", err) + } + return v.AccessKeyID +} + +type stsHostRecorder struct { + next http.RoundTripper + hosts []string +} + +func (r *stsHostRecorder) RoundTrip(req *http.Request) (*http.Response, error) { + if strings.HasPrefix(req.URL.Host, "sts.") { + r.hosts = append(r.hosts, req.URL.Host) + return nil, errors.New("sts not reachable in tests") + } + return r.next.RoundTrip(req) +} + +// IRSA in a pod of one region and a bucket in another: the role exchange goes +// to the pod's regional STS endpoint, and S3 is still signed for the bucket's. +func TestWorkloadWebIdentityAsksTheWorkloadRegion(t *testing.T) { + token := filepath.Join(t.TempDir(), "token") + if err := os.WriteFile(token, []byte("header.payload.signature"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv(workloadCredentialsEnv, "workload") + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", token) + t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/pod") + t.Setenv("AWS_STS_REGIONAL_ENDPOINTS", "") // the SDK's own default is the global endpoint + t.Setenv("AWS_REGION", "us-east-1") + t.Setenv("AWS_DEFAULT_REGION", "") + rec := &stsHostRecorder{next: http.DefaultTransport} + http.DefaultTransport = rec + defer func() { http.DefaultTransport = rec.next }() + + c, err := MakeWithHTTPClient(&remote_pb.RemoteConf{Type: "s3", Name: "r", S3Region: "us-west-2"}, &http.Client{}) + if err != nil { + t.Fatalf("MakeWithHTTPClient: %v", err) + } + conn := c.(*s3RemoteStorageClient).conn.(*awss3.S3) + if _, err := conn.Config.Credentials.Get(); err == nil { + t.Fatalf("credentials: want the recorded STS failure") + } + if len(rec.hosts) == 0 || rec.hosts[0] != "sts.us-east-1.amazonaws.com" { + t.Errorf("STS hosts %v, want sts.us-east-1.amazonaws.com", rec.hosts) + } + if got := aws.StringValue(conn.Config.Region); got != "us-west-2" { + t.Errorf("S3 region %q, want the bucket's us-west-2", got) + } +} + +func makeErr(conf *remote_pb.RemoteConf) error { + _, err := MakeWithHTTPClient(conf, &http.Client{}) + return err +} + +// A server holding its own S3 identity in AWS_ACCESS_KEY_ID (weed mini) and a +// remote with no keys: by default the SDK chain takes the environment's keys; +// with WEED_REMOTE_S3_CREDENTIALS=workload it takes the instance role and never +// those keys. Keys in the configuration win either way; half a key pair and an +// unknown value are refused in workload mode; other S3-compatible types and the +// unsigned public-bucket path are untouched when the setting is off. +func TestWorkloadCredentials(t *testing.T) { + // nothing from the runner's own AWS environment reaches the chain + for _, k := range []string{"AWS_WEB_IDENTITY_TOKEN_FILE", "AWS_ROLE_ARN", "AWS_ROLE_SESSION_NAME", "AWS_PROFILE", + "AWS_DEFAULT_PROFILE", "AWS_SESSION_TOKEN", "AWS_CONTAINER_CREDENTIALS_FULL_URI", + "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_EC2_METADATA_DISABLED", "AWS_CONFIG_FILE"} { + t.Setenv(k, "") + } + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", "/nonexistent") + srv := fakeIMDS(t) + t.Setenv("AWS_EC2_METADATA_SERVICE_ENDPOINT", srv.URL) + t.Setenv("AWS_ACCESS_KEY_ID", "LOCALSERVERKEY") + t.Setenv("AWS_SECRET_ACCESS_KEY", "localserversecret") + ep, region := "https://s3.eu-central-1.amazonaws.com", "eu-central-1" + noKeys := &remote_pb.RemoteConf{Type: "s3", Name: "r", S3Endpoint: ep, S3Region: region} + withKeys := &remote_pb.RemoteConf{Type: "s3", Name: "r", S3Endpoint: ep, S3Region: region, S3AccessKey: "CONFKEY", S3SecretKey: "confsecret"} + halfKeys := &remote_pb.RemoteConf{Type: "s3", Name: "r", S3Endpoint: ep, S3Region: region, S3AccessKey: "CONFKEY"} + wasabi := &remote_pb.RemoteConf{Type: "wasabi", Name: "w", WasabiEndpoint: "https://s3.wasabisys.com", WasabiRegion: "us-east-1", + WasabiAccessKey: "WASABIKEY", WasabiSecretKey: "wasabisecret"} + + t.Setenv(workloadCredentialsEnv, "") + if got := accessKeyOf(t, noKeys); got != "LOCALSERVERKEY" { + t.Errorf("default chain: %q, want the environment's key (the behaviour the setting exists to avoid)", got) + } + t.Setenv(workloadCredentialsEnv, "workload") + if got := accessKeyOf(t, noKeys); got != "ROLEKEY" { + t.Errorf("workload: %q, want the instance role's key", got) + } + if got := accessKeyOf(t, withKeys); got != "CONFKEY" { + t.Errorf("workload with keys configured: %q, want the configuration's", got) + } + if got := accessKeyOf(t, wasabi); got != "WASABIKEY" { + t.Errorf("workload, another S3-compatible type: %q, want its own keys (not affected)", got) + } + if err := makeErr(halfKeys); err == nil { + t.Errorf("workload with half a key pair: built, want a refusal (the default chain would sign with the environment's keys)") + } + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", "/var/run/secrets/token") // a token file with no role: skipped, not fatal + if got := accessKeyOf(t, noKeys); got != "ROLEKEY" { + t.Errorf("workload, token file without a role: %q, want the instance role's key", got) + } + t.Setenv("AWS_ROLE_ARN", "arn:aws:iam::123456789012:role/pod") // web identity named but failing: no fall back to the instance role + c, err := MakeWithHTTPClient(noKeys, &http.Client{}) + if err != nil { + t.Fatalf("MakeWithHTTPClient: %v", err) + } + if v, err := c.(*s3RemoteStorageClient).conn.(*awss3.S3).Config.Credentials.Get(); err == nil { + t.Errorf("workload, web identity failing: got %q, want an error (never the instance role)", v.AccessKeyID) + } + t.Setenv("AWS_ROLE_ARN", "") + t.Setenv("AWS_WEB_IDENTITY_TOKEN_FILE", "") + // a selected profile in the shared credentials file is not read in workload mode + shared := filepath.Join(t.TempDir(), "credentials") + if err := os.WriteFile(shared, []byte("[irsa]\nrole_arn = arn:aws:iam::123456789012:role/pod\nweb_identity_token_file = /var/run/secrets/token\n"), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", shared) + t.Setenv("AWS_PROFILE", "irsa") + if got := accessKeyOf(t, noKeys); got != "ROLEKEY" { + t.Errorf("workload, a profile selected: %q, want the instance role's key", got) + } + // nor a broken one, which the SDK would refuse even with credentials given + if err := os.WriteFile(shared, []byte("[irsa]\nweb_identity_token_file = /var/run/secrets/token\n"), 0o600); err != nil { + t.Fatal(err) + } + if got := accessKeyOf(t, noKeys); got != "ROLEKEY" { + t.Errorf("workload, a broken profile selected: %q, want the instance role's key", got) + } + t.Setenv("AWS_PROFILE", "") + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", "/nonexistent") + t.Setenv(workloadCredentialsEnv, "Workload") + if err := makeErr(noKeys); err == nil { + t.Errorf("unknown value: built, want a refusal (never a silent fall back to the environment's keys)") + } + + // the setting off and no credential source named: a keyless remote is unsigned, as before + t.Setenv(workloadCredentialsEnv, "") + t.Setenv("AWS_ACCESS_KEY_ID", "") + t.Setenv("AWS_SECRET_ACCESS_KEY", "") + t.Setenv("AWS_SHARED_CREDENTIALS_FILE", "") + c, err = MakeWithHTTPClient(noKeys, &http.Client{}) + if err != nil { + t.Fatalf("public bucket: %v", err) + } + if c.(*s3RemoteStorageClient).conn.(*awss3.S3).Config.Credentials != credentials.AnonymousCredentials { + t.Errorf("public bucket, setting off: credentials are not anonymous") + } +} diff --git a/weed/server/volume_grpc_remote.go b/weed/server/volume_grpc_remote.go index b30015866b..73868c8fc1 100644 --- a/weed/server/volume_grpc_remote.go +++ b/weed/server/volume_grpc_remote.go @@ -373,9 +373,9 @@ func guardedMaxConnsPerHost() int { // it is built that its configuration does not hold, so that a change of them // builds a new client: the gcs credentials sources of CredentialsVersion, or, // for an s3-compatible remote, the resolved keys (which a type's environment -// fallback may supply), plus — with a key or secret still missing (the SDK's -// default chain) — the shared credentials and config files and the AWS_* -// variables the chain reads. "" for a remote of another kind. +// fallback may supply) and WEED_REMOTE_S3_CREDENTIALS, plus — with a key or +// secret still missing (the SDK's default chain) — the shared credentials and +// config files and every AWS_* variable. "" for a remote of another kind. func guardedCredentialsVersion(conf *remote_pb.RemoteConf) string { if conf.GetType() == "gcs" { return remote_storage.CredentialsVersion(conf) @@ -388,6 +388,8 @@ func guardedCredentialsVersion(conf *remote_pb.RemoteConf) string { h.Write([]byte(accessKey)) h.Write([]byte{0}) h.Write([]byte(secretKey)) + h.Write([]byte{0}) + h.Write([]byte(os.Getenv("WEED_REMOTE_S3_CREDENTIALS"))) if s3remote.UsesDefaultCredentialChain(conf) { shared := awsSharedFile("AWS_SHARED_CREDENTIALS_FILE", "credentials") config := awsSharedFile("AWS_CONFIG_FILE", "config") @@ -395,9 +397,18 @@ func guardedCredentialsVersion(conf *remote_pb.RemoteConf) string { h.Write([]byte(remote_storage.FileVersion(shared))) h.Write([]byte{0}) h.Write([]byte(remote_storage.FileVersion(config))) - for _, k := range []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE", "AWS_DEFAULT_PROFILE"} { + // the SDK takes its keys, profile, web identity, container, IMDS, STS + // and endpoint settings from AWS_* variables when it builds the session + var vars []string + for _, kv := range os.Environ() { + if strings.HasPrefix(kv, "AWS_") { + vars = append(vars, kv) + } + } + slices.Sort(vars) + for _, kv := range vars { h.Write([]byte{0}) - h.Write([]byte(os.Getenv(k))) + h.Write([]byte(kv)) } } return hex.EncodeToString(h.Sum(nil)[:16]) diff --git a/weed/server/volume_grpc_remote_test.go b/weed/server/volume_grpc_remote_test.go index 72ba24fbcf..38a8dfa752 100644 --- a/weed/server/volume_grpc_remote_test.go +++ b/weed/server/volume_grpc_remote_test.go @@ -1166,3 +1166,35 @@ func TestBuildGuardedRemoteStorageClientS3EnvironmentCredentials(t *testing.T) { t.Fatalf("a changed environment credential must build a new client (err %v)", err) } } + +// A keyed s3 remote reads the credentials mode too, so an unknown value fails its next build instead of returning the cached client. +func TestBuildGuardedRemoteStorageClientS3KeysFollowTheCredentialsMode(t *testing.T) { + guardedCacheTest(t, nil) + t.Setenv("WEED_REMOTE_S3_CREDENTIALS", "") + conf := &remote_pb.RemoteConf{Name: "keyed", Type: "s3", S3AccessKey: "a", S3SecretKey: "b", S3Region: "us-east-1", S3Endpoint: "https://93.184.216.34"} + if _, err := BuildGuardedRemoteStorageClient(context.Background(), conf, false); err != nil { + t.Fatalf("build: %v", err) + } + t.Setenv("WEED_REMOTE_S3_CREDENTIALS", "bogus") + if _, err := BuildGuardedRemoteStorageClient(context.Background(), conf, false); err == nil { + t.Fatal("an unknown credentials mode must fail the build of a cached keyed client") + } +} + +func TestGuardedCredentialsVersionFollowsTheWorkloadSource(t *testing.T) { + conf := &remote_pb.RemoteConf{Type: "s3", Name: "r", S3Region: "us-east-1"} + t.Setenv("AWS_CONTAINER_CREDENTIALS_FULL_URI", "http://169.254.170.23/v1/credentials") + for _, k := range []string{"AWS_CONTAINER_AUTHORIZATION_TOKEN", "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE", + "AWS_ROLE_SESSION_NAME", "AWS_REGION", "AWS_DEFAULT_REGION", "AWS_STS_REGIONAL_ENDPOINTS", + "AWS_EC2_METADATA_SERVICE_ENDPOINT", "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE", + "AWS_EC2_METADATA_DISABLED", "AWS_EC2_METADATA_V1_DISABLED", + "AWS_USE_FIPS_ENDPOINT", "AWS_USE_DUALSTACK_ENDPOINT", "AWS_CA_BUNDLE"} { + t.Setenv(k, "") + before := guardedCredentialsVersion(conf) + t.Setenv(k, "changed") + if guardedCredentialsVersion(conf) == before { + t.Errorf("%s changed, the guarded client's version did not", k) + } + t.Setenv(k, "") + } +}