From a2a7a589bb520fc33fe3cb018d66e9935789df8b Mon Sep 17 00:00:00 2001 From: Tiago Posse Date: Tue, 1 Dec 2026 19:56:25 +0100 Subject: [PATCH] filer: keep the content out of S3 config parse errors (#13202) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * filer: keep the content out of S3 config parse errors protojson's errors quote the token they reject, and in these files that can be a secret key or KMS key material, so a config that didn't parse could log part of a key. The error now gives the line and column, the field's type and name for a value of the wrong type, or says the file ends early. Syntax errors come from encoding/json, which gives an offset instead of a quote, so protojson's text is only read for valid JSON. Co-Authored-By: Claude Opus 5.5 * filer: keep codespell from flagging a parse error test case Codespell reads `tru` in `{"é": tru#` as a misspelling. `nul#` fails at the same column. Co-Authored-By: Claude Opus 5.5 * credential: run the store interface tests on the memory store The tests took the first registered store, which depends on package init order: once filer_etc registered first they ran against a filer that is not there. Co-Authored-By: Claude Opus 5.5 * credential: keep the content out of static S3 config file parse errors LoadS3ConfigFile parsed the -s3.config file with protojson directly, so the filer logged a rejected token such as a secret key. It now uses ParseS3ConfigurationFromBytes like the other readers of that file. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: Chris Lu --- weed/credential/credential_manager.go | 5 +- .../credential_manager_config_file_test.go | 26 +++++++++ weed/credential/credential_test.go | 27 +++------ weed/filer/s3iam_conf.go | 55 ++++++++++++++++++- weed/filer/s3iam_conf_test.go | 30 ++++++++++ 5 files changed, 117 insertions(+), 26 deletions(-) create mode 100644 weed/credential/credential_manager_config_file_test.go diff --git a/weed/credential/credential_manager.go b/weed/credential/credential_manager.go index 7bf84c9670..75da755e96 100644 --- a/weed/credential/credential_manager.go +++ b/weed/credential/credential_manager.go @@ -7,6 +7,7 @@ import ( "strings" "sync" + "github.com/seaweedfs/seaweedfs/weed/filer" "github.com/seaweedfs/seaweedfs/weed/glog" "github.com/seaweedfs/seaweedfs/weed/pb" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" @@ -14,7 +15,6 @@ import ( "github.com/seaweedfs/seaweedfs/weed/util" "github.com/seaweedfs/seaweedfs/weed/wdclient" "google.golang.org/grpc" - "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) @@ -383,8 +383,7 @@ func (cm *CredentialManager) LoadS3ConfigFile(path string) error { return fmt.Errorf("read %s: %w", path, err) } config := &iam_pb.S3ApiConfiguration{} - opts := protojson.UnmarshalOptions{DiscardUnknown: true, AllowPartial: true} - if err := opts.Unmarshal(content, config); err != nil { + if err := filer.ParseS3ConfigurationFromBytes(content, config); err != nil { return fmt.Errorf("parse %s: %w", path, err) } for _, ident := range config.Identities { diff --git a/weed/credential/credential_manager_config_file_test.go b/weed/credential/credential_manager_config_file_test.go new file mode 100644 index 0000000000..e75c77c2dc --- /dev/null +++ b/weed/credential/credential_manager_config_file_test.go @@ -0,0 +1,26 @@ +package credential + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestLoadS3ConfigFileKeepsTheContentOutOfParseErrors(t *testing.T) { + path := filepath.Join(t.TempDir(), "s3.json") + content := `{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}` + if err := os.WriteFile(path, []byte(content), 0600); err != nil { + t.Fatal(err) + } + err := (&CredentialManager{}).LoadS3ConfigFile(path) + if err == nil { + t.Fatal("expected a parse error") + } + if strings.Contains(err.Error(), "102030405060708090") { + t.Fatalf("parse error quotes the secret key: %v", err) + } + if want := "invalid configuration at line 1, column 80: invalid value for string field secretKey"; !strings.HasSuffix(err.Error(), want) { + t.Fatalf("got %v, want it to end with %s", err, want) + } +} diff --git a/weed/credential/credential_test.go b/weed/credential/credential_test.go index dd1449fa5d..8a682ac95f 100644 --- a/weed/credential/credential_test.go +++ b/weed/credential/credential_test.go @@ -2,6 +2,7 @@ package credential import ( "context" + "slices" "testing" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" @@ -90,18 +91,11 @@ func TestCredentialManagerCreation(t *testing.T) { } func TestCredentialInterface(t *testing.T) { - // Skip if no stores are registered - if len(Stores) == 0 { - t.Skip("No credential stores registered - for full testing see test/ package") + if !slices.Contains(GetAvailableStores(), StoreTypeMemory) { + t.Skip("memory store not registered - for full testing see test/ package") } - // Test the interface with the first available store - availableStores := GetAvailableStores() - if len(availableStores) == 0 { - t.Skip("No stores available for testing") - } - - testCredentialInterfaceWithStore(t, availableStores[0]) + testCredentialInterfaceWithStore(t, StoreTypeMemory) } func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTypeName) { @@ -173,18 +167,11 @@ func testCredentialInterfaceWithStore(t *testing.T, storeName CredentialStoreTyp } func TestCredentialManagerIntegration(t *testing.T) { - // Skip if no stores are registered - if len(Stores) == 0 { - t.Skip("No credential stores registered - for full testing see test/ package") + if !slices.Contains(GetAvailableStores(), StoreTypeMemory) { + t.Skip("memory store not registered - for full testing see test/ package") } - // Test with the first available store - availableStores := GetAvailableStores() - if len(availableStores) == 0 { - t.Skip("No stores available for testing") - } - - storeName := availableStores[0] + storeName := StoreTypeMemory config := util.GetViper() cm, err := NewCredentialManager(storeName, config, "test.") if err != nil { diff --git a/weed/filer/s3iam_conf.go b/weed/filer/s3iam_conf.go index 3d0a092140..6f32c79dc3 100644 --- a/weed/filer/s3iam_conf.go +++ b/weed/filer/s3iam_conf.go @@ -1,23 +1,72 @@ package filer import ( + "bytes" + "encoding/json" + "errors" "fmt" "io" + "regexp" + "strings" + "unicode/utf8" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" jsonpb "google.golang.org/protobuf/encoding/protojson" "google.golang.org/protobuf/proto" ) +var protojsonError = regexp.MustCompile(`\(line (\d+):(\d+)\): (invalid value for \w+ field \w+)?`) + func ParseS3ConfigurationFromBytes[T proto.Message](content []byte, config T) error { options := &jsonpb.UnmarshalOptions{ DiscardUnknown: true, AllowPartial: true, } - if err := options.Unmarshal(content, config); err != nil { - return err + err := options.Unmarshal(content, config) + if err == nil { + return nil } - return nil + // protojson's errors quote the token they reject, which in these files can be a secret + // key or KMS key material, so an error only says where it is and, for a value of the + // wrong type, which field it's for. encoding/json finds syntax errors and gives an offset + // instead of a quote, so protojson's text is only read for a file that is valid JSON. + decoder := json.NewDecoder(bytes.NewReader(content)) + var syntaxErr *json.SyntaxError + switch jsonErr := decoder.Decode(new(json.RawMessage)); { + case jsonErr == io.EOF || jsonErr == io.ErrUnexpectedEOF: + return errors.New("invalid configuration: unexpected end of input") + case errors.As(jsonErr, &syntaxErr): + return fmt.Errorf("invalid configuration at %s", position(content, int(syntaxErr.Offset)-1)) + case jsonErr == nil: + if rest := bytes.TrimLeft(content[decoder.InputOffset():], " \t\r\n"); len(rest) > 0 { + return fmt.Errorf("invalid configuration at %s", position(content, len(content)-len(rest))) + } + } + if strings.HasSuffix(err.Error(), io.ErrUnexpectedEOF.Error()) { + // protojson reads six bytes past a \u escape of a surrogate, so on one near the end of + // the file it runs out of input. With room after it, it says where the escape is. + if padded := options.Unmarshal(append(bytes.Clone(content), " "...), config.ProtoReflect().New().Interface()); padded != nil { + err = padded + } + } + found := protojsonError.FindStringSubmatch(err.Error()) + switch { + case found != nil && found[3] != "": + return fmt.Errorf("invalid configuration at line %s, column %s: %s", found[1], found[2], found[3]) + case found != nil: + return fmt.Errorf("invalid configuration at line %s, column %s", found[1], found[2]) + } + return errors.New("invalid configuration") +} + +// position gives offset as protojson's errors do, with the column in runes. +func position(content []byte, offset int) string { + before := content[:offset] + line := bytes.Count(before, []byte("\n")) + 1 + if i := bytes.LastIndexByte(before, '\n'); i >= 0 { + before = before[i+1:] + } + return fmt.Sprintf("line %d, column %d", line, utf8.RuneCount(before)+1) } func ProtoToText(writer io.Writer, config proto.Message) error { diff --git a/weed/filer/s3iam_conf_test.go b/weed/filer/s3iam_conf_test.go index ab1af4bc1e..2a8ed79d70 100644 --- a/weed/filer/s3iam_conf_test.go +++ b/weed/filer/s3iam_conf_test.go @@ -7,6 +7,7 @@ import ( . "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants" "github.com/seaweedfs/seaweedfs/weed/pb/iam_pb" + "github.com/seaweedfs/seaweedfs/weed/pb/s3_pb" "github.com/stretchr/testify/assert" ) @@ -181,3 +182,32 @@ func TestCheckDuplicateAccessKey(t *testing.T) { } } } + +func TestParseErrorKeepsTheContentOut(t *testing.T) { + for content, want := range map[string]string{ + `{"kms": {"providers": {"local": {"keys": [{"key_material": fa0102030405060708090a0b0c0d0e0f}]}}}}`: "invalid configuration at line 1, column 62", + `{"kms": {"providers": {"local": {"keys": [{"key_material": "\ud800fa0102030405"}]}}}}`: "invalid configuration at line 1, column 60", + `{"identities": [{"name": "a", "credentials": [{"accessKey": "AK", "secretKey": 102030405060708090}]}]}`: "invalid configuration at line 1, column 80: invalid value for string field secretKey", + `{"identities": [{"name": "a", "credentials": [{"secretKey": 102030405060708090`: "invalid configuration: unexpected end of input", + `{"identities": [{"name": "a", "credentials": [{"secretKey": "c2VjcmV0`: "invalid configuration: unexpected end of input", + `{"identities": "c2VjcmV0"}`: "invalid configuration at line 1, column 16", + `"c2VjcmV0"`: "invalid configuration at line 1, column 1", + `{"identities": [{"name": "\ud800"}]}`: "invalid configuration at line 1, column 26", + `{"identities": [{"name": 5, "actions": [`: "invalid configuration: unexpected end of input", + `{"identities": [{"name": "a"}]}"`: "invalid configuration at line 1, column 32", + `{"é": nul#`: "invalid configuration at line 1, column 10", + "{}\n \"x": "invalid configuration at line 2, column 3", + "{\"a\": 1} \t\r\n\"x": "invalid configuration at line 2, column 1", + " \n": "invalid configuration: unexpected end of input", + } { + err := ParseS3ConfigurationFromBytes([]byte(content), &iam_pb.S3ApiConfiguration{}) + if err == nil || err.Error() != want { + t.Errorf("%q: got %v, want %s", content, err, want) + } + } + + err := ParseS3ConfigurationFromBytes([]byte(`{"global": {"enabled": "yes"}}`), &s3_pb.S3CircuitBreakerConfig{}) + if want := "invalid configuration at line 1, column 24: invalid value for bool field enabled"; err == nil || err.Error() != want { + t.Errorf("circuit breaker: got %v, want %s", err, want) + } +}