diff --git a/README.md b/README.md index a271041..d0c7d17 100644 --- a/README.md +++ b/README.md @@ -205,7 +205,9 @@ Operations are synchronous, `throws` (typed ``Libgit2Error``), and return never authorized or accessed. Git's nonfatal relative-gitdir diagnostic is returned by the live API or delivered after the scoped body through `onDiagnostic`; GitKit prints nothing. Failure is atomic and writes stay - local. See [the contract and Git oracle results](docs/conditional-config.md). + local. An include chain deeper than git's ten levels throws + `ConfigIncludeDepthError` (`limit`, `includedPath`, `includingPath`), from + which a host can print git's `exceeded maximum include depth` message. See [the contract and Git oracle results](docs/conditional-config.md). - **Operation configuration** — `Repository.withOperationConfiguration(_:_:)` gives the same levels (`OperationConfiguration.Level.file` / `.entries`) and command-line layers (`OperationConfiguration.layers`, diff --git a/Sources/CGitKit/include/gitkit_libgit2.h b/Sources/CGitKit/include/gitkit_libgit2.h index c55d055..9aef345 100644 --- a/Sources/CGitKit/include/gitkit_libgit2.h +++ b/Sources/CGitKit/include/gitkit_libgit2.h @@ -290,8 +290,25 @@ GIT_EXTERN(void) gitkit_config_scope_free(gitkit_config_scope *scope); GIT_EXTERN(int) gitkit_config_scope_has_level(git_config_level_t level); GIT_EXTERN(int) gitkit_config_scope_first_failure( const gitkit_config_scope *scope, int *code, int *klass, const char **message); +/* For the failure _first_failure returns: 1 and its paths when it is an + * include-depth failure (see gitkit_config_include_depth_last), else 0. */ +GIT_EXTERN(int) gitkit_config_scope_first_failure_include_depth( + const gitkit_config_scope *scope, int *limit, const char **included, const char **including); GIT_EXTERN(void) gitkit_config_scope_mark_reported(int klass, const char *message); +/* + * GitKit addition, implemented in Sources/Clibgit2Patches/config_condition.c: + * the calling thread's newest "exceeded maximum include depth" failure (a + * GIT_ERROR_CONFIG error). Returns 1 and the depth limit, the resolved path + * of the file being included, the path of the file including it ("the + * command line" for a command-line include) and the libgit2 message it set, + * or 0 when there is none. The strings live until the next such failure on + * the thread or _clear. Used by GitKit's Swift layer; not a stable API. + */ +GIT_EXTERN(int) gitkit_config_include_depth_last(int *limit, const char **included, + const char **including, const char **message); +GIT_EXTERN(void) gitkit_config_include_depth_clear(void); + /* * GitKit addition, implemented in Sources/Clibgit2Patches/worktree_patched.c: * git_worktree_add(), which, when it fails after making the worktree's git diff --git a/Sources/Clibgit2Patches/config_condition.c b/Sources/Clibgit2Patches/config_condition.c index 1752b47..edeb12d 100644 --- a/Sources/Clibgit2Patches/config_condition.c +++ b/Sources/Clibgit2Patches/config_condition.c @@ -309,6 +309,52 @@ int gitkit_condition_unexpanded(const char *path) return -1; } +/* The calling thread's newest include-depth failure, for the Swift layer to + * raise as a typed error when the libgit2 error it returns is this one. */ +typedef struct { + char *included, *including, *message; +} gitkit_include_depth_record; +static GITKIT_TLS gitkit_include_depth_record depth_record; + +void gitkit_config_include_depth_clear(void) +{ + git__free(depth_record.included); + git__free(depth_record.including); + git__free(depth_record.message); + memset(&depth_record, 0, sizeof(depth_record)); +} + +int gitkit_condition_depth_exceeded(const char *included, const char *including) +{ + const git_error *last; + /* Git names a command-line includer "the command line". */ + if (!including) + including = "the command line"; + git_error_set(GIT_ERROR_CONFIG, "exceeded maximum include depth (%d) while including '%s' from '%s'", + GITKIT_MAX_INCLUDE_DEPTH, included, including); + gitkit_config_include_depth_clear(); + if ((last = git_error_last()) != NULL && last->message) { + depth_record.included = git__strdup(included); + depth_record.including = git__strdup(including); + depth_record.message = git__strdup(last->message); + if (!depth_record.included || !depth_record.including || !depth_record.message) + gitkit_config_include_depth_clear(); + } + return -1; +} + +int gitkit_config_include_depth_last(int *limit, const char **included, + const char **including, const char **message) +{ + if (!depth_record.message) + return 0; + *limit = GITKIT_MAX_INCLUDE_DEPTH; + *included = depth_record.included; + *including = depth_record.including; + *message = depth_record.message; + return 1; +} + static int match_gitdir(int *matches, gitkit_condition_context *ctx, const char *condition, const char *file, const char *value, int insensitive) { @@ -471,10 +517,9 @@ static int scan_file(url_scan *parent, const char *target, int conditional) error = condition_read(&scan, parent->path, &content); if (error == GIT_ENOTFOUND) { git_error_clear(); error = 0; } else if (!error) { - if (scan.depth > 10) { - git_error_set(GIT_ERROR_CONFIG, "maximum config include depth reached"); - error = -1; - } else error = scan_text(&scan, content.ptr, content.size); + if (scan.depth > GITKIT_MAX_INCLUDE_DEPTH) + error = gitkit_condition_depth_exceeded(path.ptr, parent->path); + else error = scan_text(&scan, content.ptr, content.size); } done: git_str_dispose(&path); diff --git a/Sources/Clibgit2Patches/config_file_patched.c b/Sources/Clibgit2Patches/config_file_patched.c index 17223ef..e85c674 100644 --- a/Sources/Clibgit2Patches/config_file_patched.c +++ b/Sources/Clibgit2Patches/config_file_patched.c @@ -341,9 +341,8 @@ static int gitkit_read_include(config_file_parse_data *data, const char *target) error = git_fs_path_set_error(errno, file->path, "stat"); goto done; } - if (child.depth > 10) { - git_error_set(GIT_ERROR_CONFIG, "maximum config include depth reached"); - error = -1; + if (child.depth > GITKIT_MAX_INCLUDE_DEPTH) { + error = gitkit_condition_depth_exceeded(file->path, data->file->path); goto done; } if ((error = git_futils_readbuffer(&content, file->path)) < 0) diff --git a/Sources/Clibgit2Patches/gitkit_config_condition.h b/Sources/Clibgit2Patches/gitkit_config_condition.h index eb6367f..1cb807f 100644 --- a/Sources/Clibgit2Patches/gitkit_config_condition.h +++ b/Sources/Clibgit2Patches/gitkit_config_condition.h @@ -45,6 +45,11 @@ int gitkit_condition_path(git_str *out, const char *path, const char *from); * fails as Git's expansion does. GitKit's Swift layer writes the same name. */ #define GITKIT_UNEXPANDED_PATH "gitkit-unexpanded-path" int gitkit_condition_unexpanded(const char *path); +/* Git's MAX_INCLUDE_DEPTH. Raises the failure for an include past it, with + * the resolved target and the including file (NULL: the command line), and + * records both for gitkit_config_include_depth_last. Returns -1. */ +#define GITKIT_MAX_INCLUDE_DEPTH 10 +int gitkit_condition_depth_exceeded(const char *included, const char *including); int gitkit_config_authorize(const git_repository *repo, const char *path, const char *from, int depth); int gitkit_condition_build_begin(git_config *cfg, gitkit_condition_context *ctx); void gitkit_condition_build_end(git_config *cfg); diff --git a/Sources/Clibgit2Patches/repository_patched.c b/Sources/Clibgit2Patches/repository_patched.c index 1ac55d7..be5c574 100644 --- a/Sources/Clibgit2Patches/repository_patched.c +++ b/Sources/Clibgit2Patches/repository_patched.c @@ -131,6 +131,7 @@ typedef struct { int klass; char *message; int reported; /* handed back by the call that failed */ + char *included, *including; /* an include-depth failure's paths */ } gitkit_config_scope_failure; typedef struct { @@ -234,8 +235,11 @@ void gitkit_config_scope__release(gitkit_config_scope *scope) for (i = 0; i < scope->levels_len; i++) gitkit_scope_level_dispose(&scope->levels[i]); - for (i = 0; i < scope->failures_len; i++) + for (i = 0; i < scope->failures_len; i++) { git__free(scope->failures[i].message); + git__free(scope->failures[i].included); + git__free(scope->failures[i].including); + } git__free(scope->failures); for (i = 0; i < scope->diagnostics_len; i++) { git__free(scope->diagnostics[i].condition); @@ -533,6 +537,28 @@ int gitkit_config_scope_first_failure( return 0; } +int gitkit_config_scope_first_failure_include_depth( + const gitkit_config_scope *scope, int *limit, const char **included, const char **including) +{ + size_t i; + + GIT_ASSERT_ARG(scope); + + for (i = 0; i < scope->failures_len; i++) { + const gitkit_config_scope_failure *failure = &scope->failures[i]; + + if (failure->reported) + continue; + if (!failure->included || !failure->including) + return 0; + *limit = GITKIT_MAX_INCLUDE_DEPTH; + *included = failure->included; + *including = failure->including; + return 1; + } + return 0; +} + void gitkit_config_scope_mark_reported(int klass, const char *message) { gitkit_config_scope *scope = gitkit_current_scope; @@ -570,6 +596,8 @@ void gitkit_config_scope__record(int code) gitkit_config_scope *scope = gitkit_current_scope; gitkit_config_scope_failure *grown; const git_error *last; + const char *depth_message, *included, *including; + int limit; if (!scope) return; @@ -590,11 +618,26 @@ void gitkit_config_scope__record(int code) grown->klass = last ? last->klass : 0; grown->message = git__strdup(last && last->message ? last->message : "unknown error"); grown->reported = 0; + grown->included = grown->including = NULL; if (!grown->message) { scope->failure_lost = 1; return; } + /* A later depth failure replaces the thread's record: keep its paths. */ + if (last && last->klass == GIT_ERROR_CONFIG && + gitkit_config_include_depth_last(&limit, &included, &including, &depth_message) && + strcmp(depth_message, grown->message) == 0) { + grown->included = git__strdup(included); + grown->including = git__strdup(including); + if (!grown->included || !grown->including) { + git__free(grown->included); + git__free(grown->including); + git__free(grown->message); + scope->failure_lost = 1; + return; + } + } scope->failures_len++; } diff --git a/Sources/GitKit/ConfigIncludeDepthError.swift b/Sources/GitKit/ConfigIncludeDepthError.swift new file mode 100644 index 0000000..9e39eae --- /dev/null +++ b/Sources/GitKit/ConfigIncludeDepthError.swift @@ -0,0 +1,61 @@ +import Foundation +import CGitKit + +/// A config include chain went deeper than git allows: following an +/// `[include]` or `[includeIf]` would read an eleventh nested file. +/// +/// Thrown in place of the ``Libgit2Error`` libgit2 returns for it, whether +/// the config was being read or `hasconfig:remote.*.url:` was collecting +/// URLs. Git 2.54 reports the same case as +/// +/// ``` +/// fatal: exceeded maximum include depth (10) while including +/// +/// from +/// +/// This might be due to circular includes. +/// ``` +/// +/// and exits 128. Git checks that a target exists before it counts depth, +/// and so does GitKit: a missing target is empty, never this error. +public struct ConfigIncludeDepthError: Error, LocalizedError, Sendable, Equatable { + /// The deepest include git follows: 10. + public let limit: Int + /// The file whose include went past ``limit``, resolved as git prints + /// it (a relative target joined to its includer's directory). + public let includedPath: String + /// The file that names ``includedPath``. Git calls a command-line + /// includer `the command line`; with ``limit`` at 10 the includer is + /// always a file, so in practice this is a path. + public let includingPath: String + + /// Memberwise init. + public init(limit: Int, includedPath: String, includingPath: String) { + self.limit = limit + self.includedPath = includedPath + self.includingPath = includingPath + } + + /// Git's message without its `fatal: ` prefix. + public var errorDescription: String? { + "exceeded maximum include depth (\(limit)) while including\n\t\(includedPath)\nfrom\n\t\(includingPath)\n" + + "This might be due to circular includes." + } + + /// The typed error for `error` when it is the calling thread's newest + /// include-depth failure, which is then forgotten. + static func take(matching error: Libgit2Error) -> ConfigIncludeDepthError? { + guard error.klass == Int32(GIT_ERROR_CONFIG.rawValue) else { return nil } + var limit: Int32 = 0 + var included: UnsafePointer? + var including: UnsafePointer? + var message: UnsafePointer? + guard gitkit_config_include_depth_last(&limit, &included, &including, &message) == 1, + let included, let including, let message, + String(cString: message) == error.message else { return nil } + let typed = ConfigIncludeDepthError(limit: Int(limit), includedPath: String(cString: included), + includingPath: String(cString: including)) + gitkit_config_include_depth_clear() + return typed + } +} diff --git a/Sources/GitKit/Libgit2Error.swift b/Sources/GitKit/Libgit2Error.swift index d1cade0..7352212 100644 --- a/Sources/GitKit/Libgit2Error.swift +++ b/Sources/GitKit/Libgit2Error.swift @@ -40,7 +40,8 @@ public struct Libgit2Error: Error, LocalizedError, Sendable { } } -/// Throws ``Libgit2Error`` (or a pending ``GitFilterError``) if `rc < 0`. Returns `rc` otherwise so the +/// Throws ``Libgit2Error`` (or a pending ``GitFilterError`` or the +/// ``ConfigIncludeDepthError`` it reports) if `rc < 0`. Returns `rc` otherwise so the /// caller can use it (some libgit2 APIs return the count on success). @discardableResult func check(_ rc: Int32) throws -> Int32 { @@ -48,6 +49,7 @@ func check(_ rc: Int32) throws -> Int32 { let error = Libgit2Error.last(code: rc) OperationConfigurationScope.markReported(error) if let filterError = PendingFilterError.take(matching: error) { throw filterError } + if let depthError = ConfigIncludeDepthError.take(matching: error) { throw depthError } throw error } return rc diff --git a/Sources/GitKit/OperationConfiguration.swift b/Sources/GitKit/OperationConfiguration.swift index 22113b6..dfa0dad 100644 --- a/Sources/GitKit/OperationConfiguration.swift +++ b/Sources/GitKit/OperationConfiguration.swift @@ -267,11 +267,22 @@ final class OperationConfigurationScope { precondition(rc == 0, "operation configuration scope popped out of order") } - func firstFailure() -> Libgit2Error? { + /// The first failure not handed back, typed when it is an include-depth + /// failure: the scope keeps each one's paths, as later ones replace the + /// thread's record. + func firstFailure() -> Error? { var code: Int32 = 0 var klass: Int32 = 0 var message: UnsafePointer? guard gitkit_config_scope_first_failure(pointer, &code, &klass, &message) == 1 else { return nil } + var limit: Int32 = 0 + var included: UnsafePointer? + var including: UnsafePointer? + if gitkit_config_scope_first_failure_include_depth(pointer, &limit, &included, &including) == 1, + let included, let including { + return ConfigIncludeDepthError(limit: Int(limit), includedPath: String(cString: included), + includingPath: String(cString: including)) + } return Libgit2Error(code: code, klass: klass, message: message.map { String(cString: $0) } ?? "unknown error") } diff --git a/Tests/GitKitPublicAPITests/ConditionalConfigConsumerTests.swift b/Tests/GitKitPublicAPITests/ConditionalConfigConsumerTests.swift index 37fc37d..281ed03 100644 --- a/Tests/GitKitPublicAPITests/ConditionalConfigConsumerTests.swift +++ b/Tests/GitKitPublicAPITests/ConditionalConfigConsumerTests.swift @@ -360,17 +360,31 @@ struct ConditionalConfigConsumerTests { func includeDepth() throws { defer { cleanUp() } let repository = try Repository.initialize(at: root.appendingPathComponent("repo"), initialBranch: "main") - var included = try write("[test]\nvalue = deepest\n", "depth-10") + let deepest = try write("[test]\nvalue = deepest\n", "depth-10") + var included = deepest for depth in (1...9).reversed() { included = try write("[include]\npath = \(included.path)\n", "depth-\(depth)") } try repository.setCommandLineConfig(CommandLineConfig([.include(path: included.path)])) #expect(try repository.configGet("test.value") == "deepest") let extra = try write("[include]\npath = \(included.path)\n", "depth-0") - #expect(throws: Libgit2Error.self) { + // Git names the eleventh file and the tenth, which includes it. + let expected = ConfigIncludeDepthError( + limit: 10, includedPath: deepest.path, + includingPath: root.appendingPathComponent("depth-9").path) + #expect(throws: expected) { try repository.setCommandLineConfig(CommandLineConfig([.include(path: extra.path)])) } #expect(try repository.configGet("test.value") == "deepest") + // The hasconfig URL pre-scan reads even a nonmatching target's chain. + #expect(throws: expected) { + try repository.setCommandLineConfig(CommandLineConfig([ + .includeIf(condition: "hasconfig:remote.*.url:never", path: extra.path)])) + } + #expect(try repository.configGet("test.value") == "deepest") + #expect(expected.localizedDescription == "exceeded maximum include depth (10) while including\n\t" + + "\(deepest.path)\nfrom\n\t\(root.appendingPathComponent("depth-9").path)\n" + + "This might be due to circular includes.") // Git checks existence before counting depth: a missing eleventh // target is empty, not a depth failure, also during URL collection. try Data("[test]\nvalue = deepest\n[include]\npath = absent\n".utf8) diff --git a/Tests/GitKitTests/GitFiltersTests.swift b/Tests/GitKitTests/GitFiltersTests.swift index 9047051..eb5a9f5 100644 --- a/Tests/GitKitTests/GitFiltersTests.swift +++ b/Tests/GitKitTests/GitFiltersTests.swift @@ -47,6 +47,10 @@ struct GitFiltersTests { return (dir, try Repository.open(at: dir)) } + private static func real(_ url: URL) -> String { + url.resolvingSymlinksInPath().standardizedFileURL.path + } + private func requireDriver(in dir: URL) throws { try git(["config", "filter.\(name).required", "true"], in: dir) } @@ -292,8 +296,14 @@ struct GitFiltersTests { try git(["rm", ".gitattributes"], in: dir) let driver = name let registeredName = name + "-registration" + let gitDirectory = Self.real(dir.appendingPathComponent(".git")) + let observations = Observations() + // `filter=*` matches every filtered file in the process, so a concurrent + // suite's checkout can reach this callback; pass its files through. try GitFilters.register(name: registeredName, attributes: "filter=*", smudge: { source, input in + guard Self.real(source.gitDirectory) == gitDirectory else { return nil } #expect(source.driver == driver) + observations.record(input.count) return input }) defer { try? GitFilters.unregister(name: registeredName) } @@ -306,6 +316,7 @@ struct GitFiltersTests { defer { git_buf_dispose(&result) } try check(git_filter_list_apply_to_buffer(&result, filters, "hello\n", 6)) #expect(result.size == 6) + #expect(observations.chunks == [6]) } @Test("The guard rejects missing required drivers, but permits optional ones") diff --git a/Tests/GitKitTests/OperationConfigurationTests.swift b/Tests/GitKitTests/OperationConfigurationTests.swift index 8632b86..bb29c99 100644 --- a/Tests/GitKitTests/OperationConfigurationTests.swift +++ b/Tests/GitKitTests/OperationConfigurationTests.swift @@ -526,6 +526,43 @@ struct OperationConfigurationTests { } /// Collects what callbacks on other threads saw. +extension OperationConfigurationTests { + @Test("a swallowed include-depth failure keeps its paths after later depth failures") + func hiddenIncludeDepthFailureIsTyped() throws { + defer { fixtures.removeAll() } + let fixture = try makeFixture() + /// Eleven nested files; returns the first, the tenth and the eleventh. + func chain(_ tag: String) throws -> (first: URL, tenth: URL, eleventh: URL) { + var file = try write("[t]\n\tdeepest = yes\n", to: "\(tag)-11") + let eleventh = file + for depth in (1...10).reversed() { + file = try write("[include]\n\tpath = \(file.path)\n", to: "\(tag)-\(depth)") + } + return (file, fixtures.url("\(tag)-10"), eleventh) + } + let hidden = try chain("hidden") + let later = try chain("later") + try git(["config", "include.path", hidden.first.path], in: fixture.middle) + try git(["config", "include.path", later.first.path], in: fixture.inner) + let outer = try Repository.open(at: fixture.outer) + + let error = #expect(throws: ConfigIncludeDepthError.self) { + try Repository.withOperationConfiguration(OperationConfiguration(levels: [Self.autocrlf])) { + // libgit2 swallows middle-sub's failed open: status returns. + _ = try outer.status() + // A later depth failure, thrown to the body, replaces the + // thread's newest record. + #expect(throws: ConfigIncludeDepthError( + limit: 10, includedPath: later.eleventh.path, includingPath: later.tenth.path)) { + try Repository.open(at: fixture.inner) + } + } + } + #expect(error == ConfigIncludeDepthError( + limit: 10, includedPath: hidden.eleventh.path, includingPath: hidden.tenth.path)) + } +} + private final class Recorded: @unchecked Sendable { private let lock = NSLock() private var _includes: [ConfigInclude] = [] diff --git a/Tests/GitKitTests/RepositoryPreparationTests.swift b/Tests/GitKitTests/RepositoryPreparationTests.swift index 91771e0..f5c434f 100644 --- a/Tests/GitKitTests/RepositoryPreparationTests.swift +++ b/Tests/GitKitTests/RepositoryPreparationTests.swift @@ -21,13 +21,16 @@ struct RepositoryPreparationTests { let id = UUID() } - /// Counts smudges per path, from any thread. + /// Counts its own driver's smudges per path, from any thread. Filter + /// registration is process-wide, so sources for other drivers are ignored. final class SmudgeProbe: @unchecked Sendable { + let driver = "probe-\(UUID().uuidString)" private let lock = NSLock() private var paths: [String: Int] = [:] private var workdirs: Set = [] func record(_ source: GitFilterSource) { + guard source.driver == driver else { return } lock.lock(); defer { lock.unlock() } paths[source.path, default: 0] += 1 if let workdir = source.workingDirectory { workdirs.insert(Self.real(workdir)) } @@ -130,8 +133,8 @@ struct RepositoryPreparationTests { @Test("a prepared clone smudges each file once, in the prepared repository") func preparedCloneSmudgesOnce() throws { defer { fixtures.removeAll() } - let driver = "probe-\(UUID().uuidString)" let probe = SmudgeProbe() + let driver = probe.driver try GitFilters.register(name: driver, smudge: { source, _ in probe.record(source) return nil @@ -317,8 +320,8 @@ extension RepositoryPreparationTests { @Test("a prepared worktree smudges each file once, in the worktree") func preparedWorktreeSmudgesOnce() throws { defer { fixtures.removeAll() } - let driver = "probe-\(UUID().uuidString)" let probe = SmudgeProbe() + let driver = probe.driver try GitFilters.register(name: driver, smudge: { source, _ in probe.record(source) return nil diff --git a/docs/conditional-config.md b/docs/conditional-config.md index 822bcab..4886894 100644 --- a/docs/conditional-config.md +++ b/docs/conditional-config.md @@ -125,7 +125,11 @@ platform launcher warnings were absent in these runs. Primary references: [Git 2.54 config.c](https://github.com/git/git/blob/v2.54.0/config.c#L186-L418) and [t1305-config-include.sh](https://github.com/git/git/blob/v2.54.0/t/t1305-config-include.sh). GitKit returns values, diagnostics and errors; the host owns CLI exit-code -mapping. Public-consumer tests reproduce the old hasconfig failures and cover +mapping. An eleventh include level, read for the config or during the +hasconfig URL pre-scan, throws `ConfigIncludeDepthError` with the limit (10), +the resolved path of the file being included and the path of the file that +includes it, so a host can print Git's `exceeded maximum include depth (10) +while including … from …` message. Public-consumer tests reproduce the old hasconfig failures and cover the corrected no-repository behavior, policy, metadata, ordering and atomicity. Native integration tests exercise internal submodule status/diff and linked worktrees, alongside the existing scope, write and creation-rollback suites.