Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix: parse remote URLs with gix-url so IPv6 hosts and SSH ports get distinct project identifiers (#4421)

Worktrunk Bot59501986af72
diff --git a/Cargo.lock b/Cargo.lock
index 16ff086e3..922753d61 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1182,9 +1182,9 @@ checksum = "dd2e7510819d6fbf51a5545c8f922716ecfb14df168a3242f7d33e0239efe6a1"
[[package]]
name = "fastrand"
-version = "2.3.0"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
[[package]]
name = "filedescriptor"
@@ -1429,6 +1429,68 @@ dependencies = [
"r-efi 6.0.0",
]
+[[package]]
+name = "gix-error"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aef6406003c4117d640329fe2c35386f4e137a628bb28d3f50209db159b48bc4"
+dependencies = [
+ "bstr",
+]
+
+[[package]]
+name = "gix-path"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6d563d4d0c975ed0df4e853f9ec962a2ba46633b1d324e1a5582541fcae0c6b"
+dependencies = [
+ "bstr",
+ "gix-error",
+ "gix-trace",
+ "gix-validate",
+]
+
+[[package]]
+name = "gix-trace"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "133f2de116104d637541831b6acb157898556d5eeec363ab2eb1c583adc6bb56"
+
+[[package]]
+name = "gix-url"
+version = "0.40.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04317dea7a5dd5253bbcab060c230f3de6a57d17cc9600c6cd7030bf4795b414"
+dependencies = [
+ "bstr",
+ "gix-error",
+ "gix-path",
+ "gix-utils",
+ "percent-encoding",
+]
+
+[[package]]
+name = "gix-utils"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "830639b49e83df93de7803ff0031a6c82d2a395dec7c4a068e37e97b0ce61bca"
+dependencies = [
+ "bstr",
+ "fastrand",
+ "getrandom 0.4.3",
+ "unicode-normalization",
+]
+
+[[package]]
+name = "gix-validate"
+version = "0.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbcd59cc52742468bc5c8a0e7123390d154f45e6cbd37461b0dcecdc681f2179"
+dependencies = [
+ "bstr",
+ "gix-error",
+]
+
[[package]]
name = "glob"
version = "0.3.3"
@@ -4678,6 +4740,7 @@ dependencies = [
"dunce",
"etcetera",
"fs2",
+ "gix-url",
"home",
"humantime",
"ignore",
diff --git a/Cargo.toml b/Cargo.toml
index 950227a66..9ce234f03 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -239,6 +239,9 @@ which = "8.0.2"
dunce = "1.0"
termimad = { version = "0.35.1", optional = true }
urlencoding = "2.1"
+# Git transport URL syntax (scheme, SCP, userinfo, IPv6, ports) for
+# `GitRemoteUrl`; Worktrunk keeps only the namespace/repo and forge policy.
+gix-url = "0.40"
regex = "1.12.3"
ignore = "0.4"
reflink-copy = "0.1"
diff --git a/dev/config.example.toml b/dev/config.example.toml
index 87ce8049b..95e37f3ce 100644
--- a/dev/config.example.toml
+++ b/dev/config.example.toml
@@ -235,7 +235,7 @@
#
# User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the project config (https://worktrunk.dev/config/#project-configuration) shared with teammates.
#
-# Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+# Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
#
# Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See how the layers rank (https://worktrunk.dev/config/#precedence).
#
@@ -260,7 +260,7 @@
# [projects."git.company.example/platform/*"]
# worktree-path = ".worktrees/{{ branch | sanitize }}"
#
-# Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.
+# Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
#
# Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
#
diff --git a/docs/src/content/docs/config.md b/docs/src/content/docs/config.md
index 01a413f68..85f133ee5 100644
--- a/docs/src/content/docs/config.md
+++ b/docs/src/content/docs/config.md
@@ -346,7 +346,7 @@ Aliases defined here apply to all projects. For project-specific aliases, use th
User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the [project config](/config/#project-configuration) shared with teammates.
-Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See [how the layers rank](/config/#precedence).
@@ -375,7 +375,7 @@ forge.platform = "gitlab"
worktree-path = ".worktrees/{{ branch | sanitize }}"
```
-Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.
+Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.md
index cebe4960a..8501e4d7d 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/config.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md
@@ -338,7 +338,7 @@ Aliases defined here apply to all projects. For project-specific aliases, use th
User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the [project config](https://worktrunk.dev/config/#project-configuration) shared with teammates.
-Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See [how the layers rank](https://worktrunk.dev/config/#precedence).
@@ -367,7 +367,7 @@ forge.platform = "gitlab"
worktree-path = ".worktrees/{{ branch | sanitize }}"
```
-Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.
+Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.md
index cebe4960a..8501e4d7d 100644
--- a/skills/worktrunk/reference/config.md
+++ b/skills/worktrunk/reference/config.md
@@ -338,7 +338,7 @@ Aliases defined here apply to all projects. For project-specific aliases, use th
User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the [project config](https://worktrunk.dev/config/#project-configuration) shared with teammates.
-Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See [how the layers rank](https://worktrunk.dev/config/#precedence).
@@ -367,7 +367,7 @@ forge.platform = "gitlab"
worktree-path = ".worktrees/{{ branch | sanitize }}"
```
-Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.
+Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index a3c9ea865..52261b476 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -2328,7 +2328,7 @@ Aliases defined here apply to all projects. For project-specific aliases, use th
User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the [project config](/config/#project-configuration) shared with teammates.
-Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See [how the layers rank](/config/#precedence).
@@ -2357,7 +2357,7 @@ forge.platform = "gitlab"
worktree-path = ".worktrees/{{ branch | sanitize }}"
```
-Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string.
+Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
diff --git a/src/git/url.rs b/src/git/url.rs
index 5ab1e504d..d17a7627d 100644
--- a/src/git/url.rs
+++ b/src/git/url.rs
@@ -75,6 +75,8 @@ impl From<ForgeKind> for GitRepoProvider {
/// - `ssh://<host>/<namespace>/<repo>.git`
/// - `ssh://<host>:<port>/<namespace>/<repo>.git`
///
+/// Hosts may be bracketed IPv6 literals (`ssh://git@[2001:db8::1]/...`).
+///
/// # Nested groups (GitLab subgroups)
///
/// GitLab supports arbitrary nesting depth: `gitlab.com/group/subgroup/subsubgroup/repo`
@@ -86,7 +88,13 @@ impl From<ForgeKind> for GitRepoProvider {
/// This ensures unique project identifiers for approval tracking security.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitRemoteUrl {
+ /// Web-facing host: lowercased hostname or bracketed IPv6 literal, plus
+ /// the explicit port of an HTTP(S) or git URL.
host: String,
+ /// Explicit non-default port of an SSH remote. Part of the project
+ /// identity — two SSH servers on one host are different projects — but not
+ /// of [`host`](Self::host), which feeds web and API URLs.
+ ssh_port: Option<u16>,
/// Full namespace path (may include `/` for nested groups)
owner: String,
repo: String,
@@ -146,68 +154,77 @@ pub(crate) fn authority_host(authority: &str) -> Option<&str> {
(!host.is_empty() && !normalized_hostname(host).is_empty()).then_some(host)
}
+/// Normalize a parsed host for display and identity, bracketing IPv6 literals.
+///
+/// `gix-url` strips the brackets from SSH and SCP hosts but keeps them on
+/// HTTP(S) and git hosts. Bracketing every IPv6 literal gives one spelling per
+/// address, and keeps the `:` inside an address from reading as a port
+/// separator in the `host[:port]/owner/repo` identifier. A host containing a
+/// `:` that is not an IPv6 address (e.g. the SCP `[host:port]:path` form) is
+/// rejected rather than guessed at.
+fn identity_host(host: &str) -> Option<String> {
+ let inner = host
+ .strip_prefix('[')
+ .and_then(|h| h.strip_suffix(']'))
+ .unwrap_or(host);
+ if !inner.contains(':') {
+ return (inner == host).then(|| host.to_string());
+ }
+ let address = inner
+ .split_once('%')
+ .map_or(inner, |(address, _zone)| address);
+ address.parse::<std::net::Ipv6Addr>().ok()?;
+ Some(format!("[{inner}]"))
+}
+
impl GitRemoteUrl {
/// Parse a git remote URL into structured components.
///
/// Returns `None` for malformed URLs or unsupported formats.
///
- /// Handles GitLab nested groups by treating all path segments except the last
- /// as the namespace. This ensures unique project identifiers for approval security.
+ /// Transport syntax — scheme, SCP form, userinfo, IPv6 literals, ports —
+ /// is delegated to `gix-url`, which splits userinfo at the final `@` of
+ /// the authority, the host git actually connects to. Worktrunk keeps the
+ /// namespace/repo split: everything but the last path segment is the
+ /// namespace, so GitLab nested groups yield unique project identifiers.
+ /// The path is taken in its original escaped spelling, so `%2F` stays
+ /// inside a segment instead of becoming a namespace boundary.
pub fn parse(url: &str) -> Option<Self> {
- let url = url.trim();
+ use gix_url::Scheme;
- let (host, namespace, repo) = if let Some(rest) = url
- .strip_prefix("https://")
- .or_else(|| url.strip_prefix("http://"))
- .or_else(|| url.strip_prefix("git://"))
- {
- // Scheme URL: [userinfo@]host[:port]/namespace/repo.git.
- let (authority, path) = rest.split_once('/')?;
- let host = authority_host(authority)?;
- let (namespace, repo) = split_namespace_repo(path)?;
- (host, namespace, repo)
- } else if let Some(rest) = url.strip_prefix("ssh://") {
- // ssh://[email protected]/owner/repo.git or ssh://github.com/owner/repo.git
- // ssh://git@host:port/owner/repo.git (port is stripped — irrelevant to project identity)
- //
- // Split the authority off at the first `/` before looking for `@`,
- // exactly as the scheme and SCP-style branches do: `@` is legal in a
- // path, and searching the whole remainder for it lets a later
- // segment pose as the authority. In
- //
- // ssh://[email protected]/owner/[email protected]/org/repo.git
- //
- // the last `@` would otherwise make the host `github.com` — the
- // identity `project_identifier` keys approvals on — for a remote
- // git connects to `attacker.example`.
- let (authority, path) = rest.split_once('/')?;
- let host_with_port = authority_host(authority)?;
- // Strip port from host (e.g., "gitlab.internal:2222" → "gitlab.internal")
- let host = host_with_port.split(':').next().unwrap_or(host_with_port);
- let (namespace, repo) = split_namespace_repo(path)?;
- (host, namespace, repo)
- } else if let Some((authority, path)) = url.split_once(':')
- && !authority.contains('/')
- {
- // SCP-style SSH: [email protected]:owner/repo.git
- // Split the authority before looking for `@` so `@` remains valid in the path.
- let (user, host) = authority.rsplit_once('@')?;
- if user.is_empty() || host.is_empty() {
- return None;
- }
- let (namespace, repo) = split_namespace_repo(path)?;
- (host, namespace, repo)
- } else {
+ let parsed = gix_url::parse(url.trim()).ok()?;
+ let host = identity_host(parsed.host_argument_safe()?)?;
+ if normalized_hostname(&host).is_empty() {
return None;
+ }
+
+ let (host, ssh_port) = match parsed.scheme {
+ // Scheme URLs keep an explicit port in the host, as the web URL
+ // and API hosts derived from it need it too.
+ Scheme::Http | Scheme::Https | Scheme::Git => match parsed.port {
+ Some(port) => (format!("{host}:{port}"), None),
+ None => (host, None),
+ },
+ Scheme::Ssh => {
+ // SCP-style remotes require a user, so a bare `host:path`
+ // (indistinguishable from a local path with a colon) is not
+ // treated as a remote.
+ if parsed.serialize_alternative_form && parsed.user().is_none_or(str::is_empty) {
+ return None;
+ }
+ // The SSH port is not the web port, so it stays out of
+ // `host`; the default port names the same server as no port.
+ (host, parsed.port.filter(|&port| port != 22))
+ }
+ _ => return None,
};
- // Validate non-empty host
- if host.is_empty() {
- return None;
- }
+ let path = std::str::from_utf8(parsed.original_path()).ok()?;
+ let (namespace, repo) = split_namespace_repo(path)?;
Some(Self {
- host: host.to_string(),
+ host,
+ ssh_port,
owner: namespace,
repo,
})
@@ -233,9 +250,14 @@ impl GitRemoteUrl {
/// Project identifier in "host/owner/repo" format.
///
- /// Used for tracking approved commands per project.
+ /// Used for tracking approved commands and selecting `[projects]`
+ /// settings. An explicit SSH port joins the host (`host:2222/owner/repo`),
+ /// so servers on different ports never share approvals.
pub fn project_identifier(&self) -> String {
- format!("{}/{}/{}", self.host, self.owner, self.repo)
+ match self.ssh_port {
+ Some(port) => format!("{}:{port}/{}/{}", self.host, self.owner, self.repo),
+ None => format!("{}/{}/{}", self.host, self.owner, self.repo),
+ }
}
/// The known forge identified by this URL's hostname.
@@ -494,6 +516,7 @@ mod tests {
url,
GitRemoteUrl {
host: "github.com".to_string(),
+ ssh_port: None,
owner: "openai".to_string(),
repo: "codex".to_string(),
}
@@ -528,7 +551,7 @@ mod tests {
#[test]
fn test_ssh_urls_with_ports() {
- // Standard SSH with port
+ // The default SSH port names the same server as no port
let url = GitRemoteUrl::parse("ssh://git@host:22/owner/repo.git").unwrap();
assert_eq!(url.host(), "host");
assert_eq!(url.owner(), "owner");
@@ -540,8 +563,9 @@ mod tests {
assert_eq!(url.host(), "host");
assert_eq!(url.owner(), "owner");
assert_eq!(url.repo(), "repo");
+ assert_eq!(url.project_identifier(), "host:2222/owner/repo");
- // Nested groups with port
+ // Nested groups with port: the SSH port stays out of the web host
let url =
GitRemoteUrl::parse("ssh://[email protected]:2222/group/subgroup/repo.git").unwrap();
assert_eq!(url.host(), "gitlab.internal");
@@ -549,17 +573,90 @@ mod tests {
assert_eq!(url.repo(), "repo");
assert_eq!(
url.project_identifier(),
- "gitlab.internal/group/subgroup/repo"
+ "gitlab.internal:2222/group/subgroup/repo"
+ );
+ assert_eq!(
+ url.web_url().as_deref(),
+ Some("https://gitlab.internal/group/subgroup/repo")
);
+ }
- // Port is stripped — same project identity as without port
- let with_port = GitRemoteUrl::parse("ssh://git@host:2222/owner/repo.git").unwrap();
- let without_port = GitRemoteUrl::parse("ssh://git@host/owner/repo.git").unwrap();
+ /// Two SSH servers on one host are different projects, so they must not
+ /// share approvals or `[projects]` settings.
+ #[test]
+ fn test_ssh_ports_isolate_project_identity() {
+ let identifiers: Vec<String> = [
+ "ssh://git@host/owner/repo.git",
+ "ssh://git@host:2222/owner/repo.git",
+ "ssh://git@host:2223/owner/repo.git",
+ ]
+ .iter()
+ .map(|url| GitRemoteUrl::parse(url).unwrap().project_identifier())
+ .collect();
+ assert_eq!(
+ identifiers,
+ [
+ "host/owner/repo",
+ "host:2222/owner/repo",
+ "host:2223/owner/repo"
+ ]
+ );
+
+ // HTTP(S) keeps its explicit port in the host, as before
+ let url = GitRemoteUrl::parse("https://host:8443/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "host:8443");
+ assert_eq!(url.project_identifier(), "host:8443/owner/repo");
+
+ // A port in hostile userinfo is not the connection port
+ let url =
+ GitRemoteUrl::parse("ssh://[email protected]:[email protected]:2222/owner/repo.git")
+ .unwrap();
+ assert_eq!(url.host(), "attacker.example");
+ assert_eq!(url.project_identifier(), "attacker.example:2222/owner/repo");
+ }
+
+ /// Splitting the authority at its first `:` truncated every IPv6 host to
+ /// `[2001`, so distinct servers shared one approval identity.
+ #[test]
+ fn test_ipv6_hosts() {
+ let first = GitRemoteUrl::parse("ssh://git@[2001:db8::1]/owner/repo.git").unwrap();
+ let second = GitRemoteUrl::parse("ssh://git@[2001:db8::2]/owner/repo.git").unwrap();
+ assert_eq!(first.host(), "[2001:db8::1]");
+ assert_eq!(first.project_identifier(), "[2001:db8::1]/owner/repo");
+ assert_eq!(second.project_identifier(), "[2001:db8::2]/owner/repo");
+
+ // Port, SCP, HTTPS, and git forms bracket the address the same way
+ let url = GitRemoteUrl::parse("ssh://git@[2001:db8::1]:2222/owner/repo.git").unwrap();
+ assert_eq!(url.host(), "[2001:db8::1]");
+ assert_eq!(url.project_identifier(), "[2001:db8::1]:2222/owner/repo");
+ let url = GitRemoteUrl::parse("[2001:DB8::1]:owner/repo.git");
+ assert!(url.is_none(), "SCP form without a user is not a remote");
+ let url = GitRemoteUrl::parse("https://[2001:db8::1]:8443/owner/repo.git").unwrap();
+ assert_eq!(url.project_identifier(), "[2001:db8::1]:8443/owner/repo");
assert_eq!(
- with_port.project_identifier(),
- without_port.project_identifier(),
- "Port is a transport detail — same project identity"
+ url.web_url().as_deref(),
+ Some("https://[2001:db8::1]:8443/owner/repo")
);
+ let url = GitRemoteUrl::parse("git://[2001:db8::1]/owner/repo.git").unwrap();
+ assert_eq!(url.project_identifier(), "[2001:db8::1]/owner/repo");
+
+ // SSH strips brackets from any host, as git does when it connects;
+ // HTTPS accepts them only around an IPv6 address
+ let url = GitRemoteUrl::parse("ssh://git@[git.example]/owner/repo.git").unwrap();
+ assert_eq!(url.project_identifier(), "git.example/owner/repo");
+ assert!(GitRemoteUrl::parse("https://[git.example]/owner/repo.git").is_none());
+ }
+
+ #[test]
+ fn test_unsupported_transport_forms_are_rejected() {
+ // Hosts that would be read as an ssh option
+ assert!(GitRemoteUrl::parse("ssh://-oProxyCommand=evil/owner/repo.git").is_none());
+ // Out-of-range port
+ assert!(GitRemoteUrl::parse("ssh://git@host:70000/owner/repo.git").is_none());
+ // Remote helpers and local paths
+ assert!(GitRemoteUrl::parse("ext::ssh host/owner/repo.git").is_none());
+ assert!(GitRemoteUrl::parse("file:///srv/owner/repo.git").is_none());
+ assert!(GitRemoteUrl::parse("/srv/owner/repo.git").is_none());
}
#[test]
@@ -1372,6 +1469,18 @@ mod tests {
target.project_identifier(),
"URL-encoded slash must not collide with actual nested path"
);
+
+ // `gix-url` decodes URL paths; the identity uses the original spelling
+ // so every transport keeps the escape inside its segment.
+ for url in [
+ "ssh://[email protected]/attacker/evil%2Frepo.git",
+ "[email protected]:attacker/evil%2Frepo.git",
+ "git://gitlab.com/attacker/evil%2Frepo.git",
+ ] {
+ let parsed = GitRemoteUrl::parse(url).unwrap();
+ assert_eq!(parsed.owner(), "attacker", "{url}");
+ assert_eq!(parsed.repo(), "evil%2Frepo", "{url}");
+ }
}
#[test]
diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rs
index 026cf1a5b..977981fed 100644
--- a/tests/integration_tests/repository.rs
+++ b/tests/integration_tests/repository.rs
@@ -354,8 +354,75 @@ fn test_project_identifier_ssh_protocol_with_port() {
let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();
let id = repository.project_identifier().unwrap();
- // Port is stripped — irrelevant to project identity
- assert_eq!(id, "gitlab.example.com/team/project");
+ // An explicit SSH port names a different server, so it is part of the identity
+ assert_eq!(id, "gitlab.example.com:2222/team/project");
+}
+
+/// The project identifier of a repository whose `origin` is `url`.
+fn project_identifier_for_remote(url: &str) -> String {
+ let mut repo = TestRepo::with_initial_commit();
+ repo.setup_remote("main");
+ repo.git_command()
+ .args(["remote", "set-url", "origin", url])
+ .run()
+ .unwrap();
+ Repository::at(repo.root_path().to_path_buf())
+ .unwrap()
+ .project_identifier()
+ .unwrap()
+}
+
+/// Distinct IPv6 hosts once both truncated to `[2001/owner/repo`, sharing
+/// saved approvals and `[projects]` settings.
+#[test]
+fn test_project_identifier_ipv6_hosts_are_distinct() {
+ let first = project_identifier_for_remote("ssh://git@[2001:db8::1]/owner/repo.git");
+ let second = project_identifier_for_remote("ssh://git@[2001:db8::2]/owner/repo.git");
+ assert_eq!(first, "[2001:db8::1]/owner/repo");
+ assert_eq!(second, "[2001:db8::2]/owner/repo");
+}
+
+/// The identifier selects both saved approvals and `[projects]` settings: an
+/// entry keyed on the port-less identifier an SSH port remote used to share
+/// does not carry over, while the ordinary SSH and HTTPS forms of one project
+/// still share one entry.
+#[test]
+fn test_project_identifier_selects_approvals_and_project_settings() {
+ use worktrunk::config::{Approvals, UserConfig};
+
+ let ported =
+ project_identifier_for_remote("ssh://[email protected]:2222/team/project.git");
+ let default_port =
+ project_identifier_for_remote("ssh://[email protected]:22/team/project.git");
+ let https = project_identifier_for_remote("https://gitlab.example.com/team/project.git");
+ assert_eq!(default_port, "gitlab.example.com/team/project");
+ assert_eq!(https, default_port);
+
+ let approvals: Approvals = toml::from_str(
+ r#"
+[projects."gitlab.example.com/team/project"]
+approved-commands = ["npm install"]
+"#,
+ )
+ .unwrap();
+ assert!(approvals.is_command_approved(&https, "npm install"));
+ assert!(approvals.is_command_approved(&default_port, "npm install"));
+ assert!(!approvals.is_command_approved(&ported, "npm install"));
+
+ let config: UserConfig = toml::from_str(
+ r#"
+worktree-path = "global"
+
+[projects."gitlab.example.com/team/project"]
+worktree-path = "default-port"
+
+[projects."gitlab.example.com:2222/team/project"]
+worktree-path = "port-2222"
+"#,
+ )
+ .unwrap();
+ assert_eq!(config.worktree_path_for_project(&https), "default-port");
+ assert_eq!(config.worktree_path_for_project(&ported), "port-2222");
}
#[test]
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
index 59e320412..24765faf7 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap
@@ -312,7 +312,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  #
  # User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the project config (https://worktrunk.dev/config/#project-configuration) shared with teammates.
  #
-  # Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
+  # Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix; an explicit port other than SSH's default 22 stays with the host, as in `gitlab.example.com:2222/team/project`), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.
  #
  # Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See how the layers rank (https://worktrunk.dev/config/#precedence).
  #
@@ -338,7 +338,7 @@ Creates ~/.config/worktrunk/config.toml with the following content:
  # worktree-path = ".worktrees/{{ branch | sanitize }}"
  #
  # Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — `git.company.example/platform/*` over `git.company.example/*` — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-`*` characters in the key. End a host-wide key with `/*` — a bare `git.company.example*` also covers hosts whose names merely start
-  with that string.
+  with that string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is `git.company.example:2222/*`.
  #
  # Entries in `approvals.toml` match the same way, so a hand-written pattern entry approves its commands for every repository it covers.
  #
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 7bc14723d..4d2b705f7 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -359,7 +359,7 @@ Aliases defined here apply to all projects. For project-specific aliases, use th
User config can include a [projects] table for project-specific settings — worktree layout, setting overrides, anything else — separate from the project config shared with teammates.
-Entries are keyed by project identifier — <host>/<owner>/<repo> derived from the primary remote URL (no .git suffix), or the canonical repo path when there is no remote. Run wt config show inside the repo to see the identifier for the current project; it appears in the PROJECT CONFIG section as Identifier: ….
+Entries are keyed by project identifier — <host>/<owner>/<repo> derived from the primary remote URL (no .git suffix; an explicit port other than SSH's default 22 stays with the host, as in gitlab.example.com:2222/team/project), or the canonical repo path when there is no remote. Run wt config show inside the repo to see the identifier for the current project; it appears in the PROJECT CONFIG section as Identifier: ….
Scalar values (like worktree-path) replace the global value; everything else (hooks, aliases, etc.) appends, global first. See how the layers rank.
@@ -385,7 +385,7 @@ A key containing * matches any run of characters, / included, so
  worktree-path = ".worktrees/{{ branch | sanitize }}"
Every matching entry applies, least- to most-specific, following the rule above: a more specific entry — git.company.example/platform/* over git.company.example/* — wins where both set the same setting, while hooks and aliases from every matching entry all run, least-specific first. A literal key is the most specific of all; specificity is the count of non-* characters in the key. End a host-wide key with /* — a bare git.company.example* also covers hosts whose names merely start with that
-string.
+string. A remote on a non-default SSH port carries the port in its identifier, so its host-wide key is git.company.example:2222/*.
Entries in approvals.toml match the same way, so a hand-written pattern entry approves its commands for every repository it covers.