Skip to content

Add validation to ensure that settings.configs values are dictionaries, in order to prevent misuse #1547

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 23 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
0cdd80d
Add validation to ensure settings.configs values are dictionaries to …
Ryu0118 May 19, 2025
58cdf9b
Add tests for invalid settings.configs value formats
Ryu0118 May 19, 2025
6af2709
Merge branch 'master' into validate_invalid_configs
Ryu0118 May 20, 2025
5c164b2
Replaced with filter and split into a function
Ryu0118 May 20, 2025
d90866f
Rename invalidConfigsFormat to invalidConfigsMappingFormat
Ryu0118 May 20, 2025
eac4831
Add comments to explain invalid fixture
Ryu0118 May 20, 2025
8d90c4a
Rename test fixture
Ryu0118 May 20, 2025
340b8e6
Update CHANGELOG.md
Ryu0118 May 20, 2025
1b32082
Correct grammer
Ryu0118 May 20, 2025
70bf933
Use KeyPath instead of closure
Ryu0118 May 20, 2025
d9ca225
Rename validateMappingStyleInConfig to extractValidConfigs
Ryu0118 May 20, 2025
53968a5
Add a document comment for extractValidConfigs(from:)
Ryu0118 May 20, 2025
c56b072
Use old testing api and remove EquatableErrorBox
Ryu0118 May 20, 2025
d65fc9e
Rename test case to use "mapping" instead of "dictionary"
Ryu0118 May 20, 2025
cb2f605
Add ValidSettingsExtractor to encapsulate the logic for converting a …
Ryu0118 May 20, 2025
54081ce
Add settings validation for both Target and AggregateTarget
Ryu0118 May 20, 2025
24040e7
Add tests for invalid settings.configs in Target and AggregateTarget
Ryu0118 May 20, 2025
9dc8405
Add document comments for ValidSettingsExtractor
Ryu0118 May 20, 2025
ca9ed3e
Rename ValidSettingsExtractor to BuildSettingsExtractor
Ryu0118 May 26, 2025
6b9cc59
Add settings validation for settingGroups
Ryu0118 May 26, 2025
6f7592d
Add tests for settingGroups
Ryu0118 May 26, 2025
79d78ca
Rename extract to parse
Ryu0118 May 26, 2025
03bcec1
Refactor
Ryu0118 May 26, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Next Version

### Fixed
- Added validation to ensure that all values in `settings.configs` are mappings. Previously, passing non-mapping values did not raise an error, making it difficult to detect misconfigurations. Now, `SpecParsingError.invalidConfigsMappingFormat` is thrown if misused. #1547 @Ryu0118

## 2.43.0

### Added
Expand Down
2 changes: 1 addition & 1 deletion Sources/ProjectSpec/AggregateTarget.swift
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ extension AggregateTarget: NamedJSONDictionaryConvertible {
public init(name: String, jsonDictionary: JSONDictionary) throws {
self.name = jsonDictionary.json(atKeyPath: "name") ?? name
targets = jsonDictionary.json(atKeyPath: "targets") ?? []
settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty
settings = try BuildSettingsParser(jsonDictionary: jsonDictionary).parse()
configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:]
buildScripts = jsonDictionary.json(atKeyPath: "buildScripts") ?? []
buildToolPlugins = jsonDictionary.json(atKeyPath: "buildToolPlugins") ?? []
Expand Down
37 changes: 37 additions & 0 deletions Sources/ProjectSpec/BuildSettingsExtractor.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import Foundation
import JSONUtilities

/// A helper for extracting and validating the `Settings` object from a JSON dictionary.
struct BuildSettingsParser {
let jsonDictionary: JSONDictionary

/// Attempts to extract and parse the `Settings` from the dictionary.
///
/// - Returns: A valid `Settings` object
func parse() throws -> Settings {
do {
return try jsonDictionary.json(atKeyPath: "settings")
} catch let specParsingError as SpecParsingError {
// Re-throw `SpecParsingError` to prevent the misuse of settings.configs.
throw specParsingError
} catch {
// Ignore all errors except `SpecParsingError`
return .empty
}
}

/// Attempts to extract and parse setting groups from the dictionary with fallback defaults.
///
/// - Returns: Parsed setting groups or default groups if parsing fails
func parseSettingGroups() throws -> [String: Settings] {
do {
return try jsonDictionary.json(atKeyPath: "settingGroups", invalidItemBehaviour: .fail)
} catch let specParsingError as SpecParsingError {
// Re-throw `SpecParsingError` to prevent the misuse of settingGroups.
throw specParsingError
} catch {
// Ignore all errors except `SpecParsingError`
return jsonDictionary.json(atKeyPath: "settingPresets") ?? [:]
}
}
}
8 changes: 5 additions & 3 deletions Sources/ProjectSpec/Project.swift
Original file line number Diff line number Diff line change
Expand Up @@ -171,11 +171,13 @@ extension Project {
self.basePath = basePath

let jsonDictionary = Project.resolveProject(jsonDictionary: jsonDictionary)
let buildSettingsParser = BuildSettingsParser(jsonDictionary: jsonDictionary)

name = try jsonDictionary.json(atKeyPath: "name")
settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty
settingGroups = jsonDictionary.json(atKeyPath: "settingGroups")
?? jsonDictionary.json(atKeyPath: "settingPresets") ?? [:]

settings = try buildSettingsParser.parse()
settingGroups = try buildSettingsParser.parseSettingGroups()

let configs: [String: String] = jsonDictionary.json(atKeyPath: "configs") ?? [:]
self.configs = configs.isEmpty ? Config.defaultConfigs :
configs.map { Config(name: $0, type: ConfigType(rawValue: $1)) }.sorted { $0.name < $1.name }
Expand Down
23 changes: 22 additions & 1 deletion Sources/ProjectSpec/Settings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,14 +28,35 @@ public struct Settings: Equatable, JSONObjectConvertible, CustomStringConvertibl
groups = jsonDictionary.json(atKeyPath: "groups") ?? jsonDictionary.json(atKeyPath: "presets") ?? []
let buildSettingsDictionary: JSONDictionary = jsonDictionary.json(atKeyPath: "base") ?? [:]
buildSettings = buildSettingsDictionary
configSettings = jsonDictionary.json(atKeyPath: "configs") ?? [:]

self.configSettings = try Self.extractValidConfigs(from: jsonDictionary)
} else {
buildSettings = jsonDictionary
configSettings = [:]
groups = []
}
}

/// Extracts and validates the `configs` mapping from the given JSON dictionary.
/// - Parameter jsonDictionary: The JSON dictionary to extract `configs` from.
/// - Returns: A dictionary mapping configuration names to `Settings` objects.
private static func extractValidConfigs(from jsonDictionary: JSONDictionary) throws -> [String: Settings] {
guard let configSettings = jsonDictionary["configs"] as? JSONDictionary else {
return [:]
}

let invalidConfigKeys = Set(
configSettings.filter { !($0.value is JSONDictionary) }
.map(\.key)
)

guard invalidConfigKeys.isEmpty else {
throw SpecParsingError.invalidConfigsMappingFormat(keys: invalidConfigKeys)
}

return try jsonDictionary.json(atKeyPath: "configs")
}

public static func == (lhs: Settings, rhs: Settings) -> Bool {
NSDictionary(dictionary: lhs.buildSettings).isEqual(to: rhs.buildSettings) &&
lhs.configSettings == rhs.configSettings &&
Expand Down
3 changes: 3 additions & 0 deletions Sources/ProjectSpec/SpecParsingError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public enum SpecParsingError: Error, CustomStringConvertible {
case unknownBreakpointActionType(String)
case unknownBreakpointActionConveyanceType(String)
case unknownBreakpointActionSoundName(String)
case invalidConfigsMappingFormat(keys: Set<String>)

public var description: String {
switch self {
Expand Down Expand Up @@ -46,6 +47,8 @@ public enum SpecParsingError: Error, CustomStringConvertible {
return "Unknown Breakpoint Action conveyance type: \(type)"
case let .unknownBreakpointActionSoundName(name):
return "Unknown Breakpoint Action sound name: \(name)"
case let .invalidConfigsMappingFormat(keys):
return "Invalid format: The value for \"\(keys.sorted().joined(separator: ", "))\" in `configs` must be mapping format"
}
}
}
2 changes: 1 addition & 1 deletion Sources/ProjectSpec/Target.swift
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ extension Target: NamedJSONDictionaryConvertible {
deploymentTarget = nil
}

settings = jsonDictionary.json(atKeyPath: "settings") ?? .empty
settings = try BuildSettingsParser(jsonDictionary: jsonDictionary).parse()
configFiles = jsonDictionary.json(atKeyPath: "configFiles") ?? [:]
if let source: String = jsonDictionary.json(atKeyPath: "sources") {
sources = [TargetSource(path: source)]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
name: InvalidConfigsValueNonMappingAggregateTargets

# This fixture tests validation of `settings.configs` under an aggregate target.
# Here, `invalid_key0` and `invalid_key1` are scalar values (not mappings),
# so parsing should throw SpecParsingError.invalidConfigsMappingFormat.
targets:
valid_target1:
type: application
platform: iOS
valid_target2:
type: application
platform: iOS

aggregateTargets:
invalid_target:
targets:
- valid_target1
- valid_target2
settings:
configs:
invalid_key0: value0
debug:
valid_key: value1
invalid_key1: value2
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: InvalidConfigsValueNonMappingSettingGroups

# This fixture tests validation of `settings.configs` under an aggregate target.
# Here, `invalid_key0` and `invalid_key1` are scalar values (not mappings),
# so parsing should throw SpecParsingError.invalidConfigsMappingFormat.
settingGroups:
invalid_preset:
configs:
invalid_key0: value0
debug:
valid_key: value1
invalid_key1: value2
targets:
invalid_target:
type: application
platform: iOS
settings:
groups:
- invalid_preset
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: InvalidConfigsValueNonMappingSettings

# This fixture tests validation of `settings.configs` at the top level.
# Here, `invalid_key0` and `invalid_key1` are scalar values (not mappings),
# so parsing should throw SpecParsingError.invalidConfigsMappingFormat.
settings:
configs:
invalid_key0: value0
debug:
valid_key: value1
invalid_key1: value2
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
name: InvalidConfigsValueNonMappingTargets

# This fixture tests nested validation of `settings.configs` under a target.
# Here, `invalid_key0` and `invalid_key1` are scalar values (not mappings),
# so parsing should throw SpecParsingError.invalidConfigsMappingFormat.
targets:
invalid_target:
type: application
platform: iOS
settings:
configs:
invalid_key0: value0
debug:
valid_key: value1
invalid_key1: value2
43 changes: 43 additions & 0 deletions Tests/ProjectSpecTests/InvalidConfigsFormatTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import ProjectSpec
import Testing
import TestSupport
import PathKit

struct invalidConfigsMappingFormatTests {
struct InvalidConfigsTestArguments {
var fixturePath: Path
var expectedError: SpecParsingError
}

private static var testArguments: [InvalidConfigsTestArguments] {
let invalidConfigsFixturePath: Path = fixturePath + "invalid_configs"
return [
InvalidConfigsTestArguments(
fixturePath: invalidConfigsFixturePath + "invalid_configs_value_non_mapping_settings.yml",
expectedError: SpecParsingError.invalidConfigsMappingFormat(keys: ["invalid_key0", "invalid_key1"])
),
InvalidConfigsTestArguments(
fixturePath: invalidConfigsFixturePath + "invalid_configs_value_non_mapping_targets.yml",
expectedError: SpecParsingError.invalidConfigsMappingFormat(keys: ["invalid_key0", "invalid_key1"])
),
InvalidConfigsTestArguments(
fixturePath: invalidConfigsFixturePath + "invalid_configs_value_non_mapping_aggregate_targets.yml",
expectedError: SpecParsingError.invalidConfigsMappingFormat(keys: ["invalid_key0", "invalid_key1"])
),
InvalidConfigsTestArguments(
fixturePath: invalidConfigsFixturePath + "invalid_configs_value_non_mapping_setting_groups.yml",
expectedError: SpecParsingError.invalidConfigsMappingFormat(keys: ["invalid_key0", "invalid_key1"])
)
]
}

@Test("throws invalidConfigsMappingFormat for non-mapping configs entries", arguments: testArguments)
func testInvalidConfigsMappingFormat(_ arguments: InvalidConfigsTestArguments) throws {
#expect {
try Project(path: arguments.fixturePath)
} throws: { actualError in
(actualError as any CustomStringConvertible).description
== arguments.expectedError.description
}
}
}