Przeglądaj źródła

fix(lang): reject non-integer schemaVersion values

Decoding schemaVersion straight into an int let yaml.v3 truncate values
such as 1.5 to 1. Check the raw YAML scalar instead, and accept only the
plain integer 1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jamesread 21 godzin temu
rodzic
commit
df3bace545
2 zmienionych plików z 30 dodań i 3 usunięć
  1. 14 3
      lang/main.go
  2. 16 0
      lang/main_test.go

+ 14 - 3
lang/main.go

@@ -16,7 +16,7 @@ import (
 )
 
 type LanguageFilev1 struct {
-	SchemaVersion int               `json:"schemaVersion" yaml:"schemaVersion"`
+	SchemaVersion yaml.Node         `json:"schemaVersion" yaml:"schemaVersion"`
 	Translations  map[string]string `json:"translations" yaml:"translations"`
 }
 
@@ -163,8 +163,9 @@ func loadLanguageFile(fullPath string) (map[string]string, error) {
 		return nil, fmt.Errorf("parsing language file %s: %w", fullPath, err)
 	}
 
-	if yamlData.SchemaVersion != 1 {
-		return nil, fmt.Errorf("language file %s has schemaVersion %d, expected 1", fullPath, yamlData.SchemaVersion)
+	err = validateSchemaVersion(&yamlData.SchemaVersion)
+	if err != nil {
+		return nil, fmt.Errorf("language file %s: %w", fullPath, err)
 	}
 
 	if len(yamlData.Translations) == 0 {
@@ -174,6 +175,16 @@ func loadLanguageFile(fullPath string) (map[string]string, error) {
 	return yamlData.Translations, nil
 }
 
+// validateSchemaVersion checks the raw YAML scalar, because decoding straight
+// into an int silently truncates values such as 1.5 to 1.
+func validateSchemaVersion(node *yaml.Node) error {
+	if node.Kind != yaml.ScalarNode || node.ShortTag() != "!!int" || node.Value != "1" {
+		return fmt.Errorf("schemaVersion is %q, expected 1", node.Value)
+	}
+
+	return nil
+}
+
 // getReferenceKeys returns the keys from the "en" translation as the reference set.
 func getReferenceKeys(messages map[string]map[string]string) map[string]bool {
 	enTranslations, exists := messages["en"]

+ 16 - 0
lang/main_test.go

@@ -29,6 +29,22 @@ func TestLoadLanguageFileRejectsWrongSchemaVersion(t *testing.T) {
 	}
 }
 
+func TestLoadLanguageFileRejectsNonIntegerSchemaVersion(t *testing.T) {
+	for _, schemaVersion := range []string{"1.5", "1.0", "\"1\"", "0x1", "[1]"} {
+		content := "schemaVersion: " + schemaVersion + "\ntranslations:\n  welcome: Hi\n"
+
+		if _, err := loadLanguageFile(writeLanguageFile(t, content)); err == nil {
+			t.Errorf("expected an error for schemaVersion %s", schemaVersion)
+		}
+	}
+}
+
+func TestLoadLanguageFileRejectsMissingSchemaVersion(t *testing.T) {
+	if _, err := loadLanguageFile(writeLanguageFile(t, "translations:\n  welcome: Hi\n")); err == nil {
+		t.Error("expected an error for a missing schemaVersion")
+	}
+}
+
 func TestLoadLanguageFileRejectsInvalidYaml(t *testing.T) {
 	if _, err := loadLanguageFile(writeLanguageFile(t, "schemaVersion: 1\ntranslations: [\n")); err == nil {
 		t.Error("expected an error for invalid YAML")