Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,24 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- `apm.yml` marketplace blocks accept an optional `sourceBase` field: a git base
(`https://host/path`, arbitrary depth) that host-less relative package `source`
values compose onto, enabling deeply nested enterprise GitLab group paths that
the `host.tld/owner/repo` shorthand cannot express. Per-entry host-prefixed and
full-URL sources override the base; local and base-less configs are unchanged.
(by @leocamello, #1519)

### Fixed

- `apm marketplace check` now resolves each package against its effective host
with that host's token (matching `apm pack`), instead of always probing the
default host with no token. Entries on a non-default host -- a
`host.tld/owner/repo` shorthand or a relative source composed onto
`marketplace.sourceBase` -- now validate correctly, and local `./` packages
skip the network entirely. (by @leocamello, #1519)

## [0.18.0] - 2026-06-04

### Added
Expand Down
27 changes: 27 additions & 0 deletions docs/src/content/docs/producer/publish-to-a-marketplace.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,33 @@ compiled `marketplace.json` -- that rename is the only structural
transform `apm pack` performs. Strict schema: unknown keys raise an
error, never silently ignored.

### Deeply nested hosts: `sourceBase`

If your packages live on a self-managed host whose group nesting is
deeper than the `host.tld/owner/repo` shorthand can express (a common
self-managed GitLab shape), declare a `sourceBase` once and write each
`source` relative to it:

```yaml
marketplace:
owner:
name: acme-org
sourceBase: https://gitlab.acme.example.com/group/sub-group/team/projects
packages:
- name: my-package
source: my-package # -> .../team/projects/my-package
version: "^1.0.0"
- name: from-github
source: github.com/acme-org/helper # host-prefixed: overrides the base
ref: v1.0.0
```

A host-less `source` composes onto `sourceBase`; a `source` that names
its own host (the `host.tld/owner/repo` or full `https://` URL form) or
a local `./` path overrides it and the base is ignored. Marketplaces
without a `sourceBase` resolve exactly as before. See the
[manifest schema](../reference/manifest-schema/) for the full rules.

Add and edit packages without leaving the shell:

```bash
Expand Down
40 changes: 39 additions & 1 deletion docs/src/content/docs/reference/manifest-schema.md
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,7 @@ Overrides exist for the rare case where the published marketplace identity diffe
| `output` | `string` | OPTIONAL | `.claude-plugin/marketplace.json` | Output path for the generated marketplace JSON. |
| `metadata` | `object` | OPTIONAL | `{}` | Free-form metadata forwarded verbatim to `marketplace.json` (e.g. `homepage`, `support`). |
| `build` | `Build` | OPTIONAL | `tagPattern: "v{version}"` | Build configuration for resolving package refs. See Section 7.4. |
| `sourceBase` | `string` | OPTIONAL | -- | Git base (`https://<host.tld>/<path>`, arbitrary depth) that host-less relative package `source` values compose onto. See Section 7.5. |
| `packages` | `list<Package>` | OPTIONAL | `[]` | Packages exposed in the marketplace. See Section 7.5. |

Unknown keys inside `marketplace:` are rejected at parse time.
Expand Down Expand Up @@ -790,7 +791,7 @@ Each entry MUST be a mapping. Unknown keys are rejected.
| Field | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | REQUIRED | Package identifier as it appears in the marketplace. |
| `source` | `string` | REQUIRED | One of: `<owner>/<repo>` (remote on the default host), `<host.tld>/<owner>/<repo>` (remote on a non-default host such as GitHub Enterprise or self-hosted GitLab -- shorthand), `https://<host.tld>/<owner>/<repo>[.git]` (same, full URL form -- a trailing `.git` is stripped), or `./<path>` (local). Must match the source pattern; path traversal (`..`) is refused, and URL forms with userinfo (`user@host`), ports, query strings, or non-`https` schemes are rejected. |
| `source` | `string` | REQUIRED | One of: `<owner>/<repo>` (remote on the default host), `<host.tld>/<owner>/<repo>` (remote on a non-default host such as GitHub Enterprise or self-hosted GitLab -- shorthand), `https://<host.tld>/<owner>/<repo>[.git]` (same, full URL form -- a trailing `.git` is stripped), or `./<path>` (local). When the block declares `sourceBase` (Section 7.2), a host-less relative form (`my-package`, `a/b/c`) is additionally accepted and composes onto the base; without a `sourceBase` the relative form is rejected. Must match the source pattern; path traversal (`..`) is refused, and URL forms with userinfo (`user@host`), ports, query strings, or non-`https` schemes are rejected. |
| `subdir` | `string` | OPTIONAL | Subdirectory inside the source repo. Path-traversal-validated. Ignored for local sources. |
| `version` | `string` | Conditional | Semver range (e.g. `^1.0.0`, `~2.1.0`, `>=3.0`). Stored as a string; resolution happens at pack time. REQUIRED for remote packages unless `ref` is given. |
| `ref` | `string` | Conditional | Explicit git ref (SHA, tag, or branch). Overrides `version` range when both are present. REQUIRED for remote packages unless `version` is given. |
Expand All @@ -810,6 +811,43 @@ The first three `source` forms target a remote git host; the second and third na

Non-default hosts authenticate via the standard APM token chain -- see the [authentication guide](../getting-started/authentication/) for the per-host-class lookup order. A token resolved for the default host is never forwarded to a non-default host.

#### Composing relative sources onto `marketplace.sourceBase`

`sourceBase` (Section 7.2) declares a git base -- `https://<host.tld>/<path>` with arbitrary path depth -- that host-less relative `source` values compose onto. It exists for enterprise hosts whose group nesting is deeper than the `host.tld/owner/repo` shorthand can express, e.g. a self-managed GitLab subgroup path `gitlab.example.com/group/sub-group/team/projects`.

`sourceBase` is validated with the same posture as a per-entry `source`: it MUST be `https://`, the host MUST be an FQDN, and userinfo (`user@host`), ports, query strings, fragments, and a trailing `.git` are rejected. Each path segment is traversal-checked (`..` refused) and a trailing `/` is normalized away.

When `sourceBase` is set, each package `source` resolves as:

| `source` shape | Resolves to |
|---|---|
| `my-package` (relative, 1 segment) | `sourceBase` + `/my-package` |
| `a/b/c` (relative, N segments) | `sourceBase` + `/a/b/c` |
| `host.tld/owner/repo` (host-prefixed) | that host -- **base ignored (override)** |
| `https://host.tld/owner/repo[.git]` (full URL) | that URL -- **base ignored (override)** |
| `./local-pkg` (local) | local path -- **base ignored** |

The rule: a `source` that carries its own host (host-prefixed or full-URL forms) or is local **overrides** the base; a host-less `source` **composes** onto it. Per-entry overrides are absolute and do not inherit the base path.

Two consequences are intentional:

- **Migration.** Existing marketplaces that do not declare `sourceBase` are unaffected -- every `source` resolves exactly as before. There is no migration step.
- **No silent default-host routing.** Once `sourceBase` is declared, a bare `owner/repo` composes onto the base rather than resolving to the default host. To target the default host (e.g. github.com) from inside a `sourceBase` marketplace, write the explicit `github.com/owner/repo` host-prefixed form.

```yaml
marketplace:
owner:
name: contoso
sourceBase: https://gitlab.example.com/group/sub-group/team/projects
packages:
- name: my-package
source: my-package # -> https://gitlab.example.com/group/sub-group/team/projects/my-package
version: "^1.0.0"
- name: upstream-helper
source: github.com/contoso/helper # host-prefixed override: base ignored
ref: v1.0.0
```

### 7.6. Complete Marketplace Block

```yaml
Expand Down
39 changes: 35 additions & 4 deletions src/apm_cli/commands/marketplace/check.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import click

from ...core.command_logger import CommandLogger
from ...marketplace.auth_helpers import resolve_token_for_host
from ...marketplace.errors import GitLsRemoteError, OfflineMissError
from ...marketplace.ref_resolver import RefResolver
from ...marketplace.semver import satisfies_range
Expand Down Expand Up @@ -40,15 +41,44 @@ def check(offline, verbose):
symbol="info",
)

resolver = RefResolver(offline=offline)
# One resolver per effective host. A package whose ``source`` named a
# non-default host -- a #1288 host-prefixed entry, or a relative entry
# composed onto ``marketplace.sourceBase`` -- carries that host on
# ``entry.host``; it must be resolved with a host-bound resolver and the
# host's token (e.g. GITLAB_APM_PAT), exactly like ``apm pack`` does.
# Default-host entries (``entry.host is None``) keep today's behaviour:
# a bare ``RefResolver(offline=...)`` with ambient credentials.
resolvers: dict[str | None, RefResolver] = {}

def _resolver_for(host: str | None) -> RefResolver:
if host not in resolvers:
if host is None:
resolvers[host] = RefResolver(offline=offline)
else:
token = resolve_token_for_host(host, offline=offline)
resolvers[host] = RefResolver(offline=offline, host=host, token=token)
return resolvers[host]

results = []
failure_count = 0

try:
for entry in yml.packages:
# Local-path packages skip git resolution entirely.
if entry.is_local:
results.append(
_CheckResult(
name=entry.name,
reachable=True,
version_found=True,
ref_ok=True,
error="",
)
)
continue
try:
# Attempt to resolve each entry
refs = resolver.list_remote_refs(entry.source)
# Attempt to resolve each entry against its effective host.
refs = _resolver_for(entry.host).list_remote_refs(entry.source)

# Check version/ref resolution
ref_ok = False
Expand Down Expand Up @@ -152,4 +182,5 @@ def check(offline, verbose):
logger.success(f"All {total} entries OK", symbol="check")

finally:
resolver.close()
for resolver in resolvers.values():
resolver.close()
48 changes: 48 additions & 0 deletions src/apm_cli/marketplace/auth_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
"""Shared auth helpers for marketplace commands.

Both ``apm pack`` (``MarketplaceBuilder``) and ``apm marketplace check`` need
to resolve a per-host token before running ``git ls-remote`` against a
non-default host (self-managed GitLab, GHES, ADO, Bitbucket DC). This module
is the single home for that logic so the two paths cannot drift.
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING

if TYPE_CHECKING:
from ..core.auth import AuthResolver

logger = logging.getLogger(__name__)


def resolve_token_for_host(
host: str,
*,
offline: bool = False,
auth_resolver: AuthResolver | None = None,
) -> str | None:
"""Resolve an auth token for a non-default *host* via ``AuthResolver``.

Returns ``None`` -- letting ``git`` fall back to ambient credentials --
when offline, when no token is configured for the host, or when
``AuthResolver`` raises. Never raises.

Pass *auth_resolver* to reuse a cached resolver across many calls (the
builder does this during metadata prefetch); otherwise a fresh one is
created per call.
"""
if offline:
return None
try:
from ..core.auth import AuthResolver # lazy import to avoid cycles

resolver = auth_resolver if auth_resolver is not None else AuthResolver()
ctx = resolver.resolve(host)
if ctx.token:
logger.debug("Resolved token for host %s (source=%s)", host, ctx.source)
return ctx.token
except Exception:
logger.debug("Could not resolve token for host %s", host, exc_info=True)
return None
32 changes: 16 additions & 16 deletions src/apm_cli/marketplace/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -416,26 +416,26 @@ def _get_resolver_for_host(self, host: str | None) -> RefResolver:
def _resolve_token_for_host(self, host: str) -> str | None:
"""Resolve an auth token for a non-default *host* via ``AuthResolver``.

Returns ``None`` -- letting ``git`` fall back to ambient credentials
-- when offline, when no token is configured for the host, or when
``AuthResolver`` raises. Never raises.
Delegates to the shared
:func:`marketplace.auth_helpers.resolve_token_for_host` so ``apm pack``
and ``apm marketplace check`` share one implementation, reusing a
cached ``AuthResolver`` across calls. Returns ``None`` -- letting
``git`` fall back to ambient credentials -- when offline, when no token
is configured, or on any error. Never raises.
"""
if self._options.offline:
return None
try:
from ..core.auth import AuthResolver # lazy import
from .auth_helpers import resolve_token_for_host

resolver = self._auth_resolver
if resolver is None:
resolver = AuthResolver()
self._auth_resolver = resolver
ctx = resolver.resolve(host) # type: ignore[union-attr]
if ctx.token:
logger.debug("Resolved token for host %s (source=%s)", host, ctx.source)
return ctx.token
except Exception:
logger.debug("Could not resolve token for host %s", host, exc_info=True)
return None
if self._auth_resolver is None:
try:
from ..core.auth import AuthResolver # lazy import

self._auth_resolver = AuthResolver()
except Exception:
logger.debug("Could not create AuthResolver for host %s", host, exc_info=True)
return None
return resolve_token_for_host(host, auth_resolver=self._auth_resolver)

def _ensure_auth(self) -> None:
"""Lazily resolve host classification and GitHub token.
Expand Down
60 changes: 40 additions & 20 deletions src/apm_cli/marketplace/yml_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
from ._io import atomic_write
from .errors import MarketplaceYmlError
from .yml_schema import (
RELATIVE_SOURCE_RE,
SOURCE_RE,
load_marketplace_from_apm_yml,
load_marketplace_yml,
Expand Down Expand Up @@ -129,23 +130,39 @@ def _find_entry_index(packages, name: str) -> int:
raise MarketplaceYmlError(f"Package '{name}' not found")


def _validate_source(source: str) -> None:
def _validate_source(source: str, source_base: str | None = None) -> None:
"""Validate that *source* has one of the accepted shapes.

Accepts ``owner/repo``, ``host.tld/owner/repo``, ``https://host.tld/
owner/repo[.git]`` (remote forms), or ``./<path>`` (local).
owner/repo[.git]`` (remote forms), or ``./<path>`` (local). When
*source_base* is set (the file declares ``marketplace.sourceBase``), a
host-less relative form (``my-package``, ``a/b/c``) is also accepted and
composes onto the base. Mirrors ``yml_schema._validate_source``.
"""
if not SOURCE_RE.match(source):
raise MarketplaceYmlError(
f"'source' must be one of "
f"'<owner>/<repo>', '<host.tld>/<owner>/<repo>', "
f"'https://<host.tld>/<owner>/<repo>[.git]', or './<path>', "
f"got '{source}'"
)
try:
validate_path_segments(source, context="source", allow_current_dir=True)
except PathTraversalError as exc:
raise MarketplaceYmlError(str(exc)) from exc
if SOURCE_RE.match(source):
try:
validate_path_segments(source, context="source", allow_current_dir=True)
except PathTraversalError as exc:
raise MarketplaceYmlError(str(exc)) from exc
return
if source_base is not None and RELATIVE_SOURCE_RE.match(source):
try:
validate_path_segments(source, context="source")
except PathTraversalError as exc:
raise MarketplaceYmlError(str(exc)) from exc
return
hint = (
" (or a host-less relative path like '<owner>/<repo>' that composes "
"onto marketplace.sourceBase)"
if source_base is not None
else " -- to use a relative path, declare 'marketplace.sourceBase'"
)
raise MarketplaceYmlError(
f"'source' must be one of "
f"'<owner>/<repo>', '<host.tld>/<owner>/<repo>', "
f"'https://<host.tld>/<owner>/<repo>[.git]', or './<path>'"
f"{hint}, got '{source}'"
)


def _validate_subdir(subdir: str) -> None:
Expand Down Expand Up @@ -177,8 +194,14 @@ def add_plugin_entry(

Returns the resolved package name.
"""
# --- load first so a declared sourceBase can inform source validation ---
data, original_text = _load_rt(yml_path)
container = _get_marketplace_container(data)
raw_base = container.get("sourceBase")
source_base = raw_base.strip() if isinstance(raw_base, str) and raw_base.strip() else None

# --- input validation ---
_validate_source(source)
_validate_source(source, source_base=source_base)

if version is not None and ref is not None:
raise MarketplaceYmlError("Cannot specify both 'version' and 'ref' -- pick one")
Expand All @@ -188,13 +211,10 @@ def add_plugin_entry(
if subdir is not None:
_validate_subdir(subdir)

# Derive name from source repo if not provided.
# Derive name from the source's last path segment if not provided
# ('owner/repo' -> 'repo', 'a/b/c' -> 'c', 'my-package' -> 'my-package').
if name is None:
name = source.split("/", 1)[1]

# --- load ---
data, original_text = _load_rt(yml_path)
container = _get_marketplace_container(data)
name = source.rstrip("/").rsplit("/", 1)[-1]
packages = container.get("packages")
if packages is None:
from ruamel.yaml.comments import CommentedSeq
Expand Down
Loading