Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
fix(integrations): secure explicit writes and Git sources
  • Loading branch information
pi-dal committed Aug 18, 2026
commit c750c15d026f478a72f6c2327114334eb2627d2b
3 changes: 2 additions & 1 deletion integrations/pi/plugins/powercontext/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,8 @@ export async function handlePcCommand(
return
}
if (command === 'flush') {
const result = await invokeScopedOperation(runtime, context, 'flush_memory', {})
const confirmation = await confirmDurableWrite(context, 'flush operation')
const result = confirmation ?? await invokeScopedOperation(runtime, context, 'flush_memory', {})
report(context, format(result), !result.ok)
return
}
Expand Down
2 changes: 1 addition & 1 deletion integrations/pi/plugins/powercontext/src/flush.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export function createPendingSourceFlusher(
for (let attempt = 0; attempt < config.flushMaxCalls; attempt += 1) {
try {
const result = await client.request('flush_memory', { scope_id: scopeId }, combined)
const cursor = result.kind === 'json' ? currentCursor(result.value) : undefined
const cursor = currentCursor(result.value)
if (cursor !== undefined && cursor >= position) {
if (pending.get(scopeId) === position) pending.delete(scopeId)
break
Expand Down
10 changes: 7 additions & 3 deletions integrations/pi/plugins/powercontext/tests/commands.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ describe('/pc command', () => {
expect(notifications.every(({ level }) => level === 'info')).toBe(true)
})

it('reports a confirmation requirement before /pc remember can persist data', async () => {
it('reports a confirmation requirement before explicit commands can persist data', async () => {
const log = vi.spyOn(console, 'log').mockImplementation(() => undefined)
const fetch = vi.fn(async () => new Response(JSON.stringify({ entry: { text: 'remembered' } })))
const context = {
Expand All @@ -82,9 +82,13 @@ describe('/pc command', () => {
}

await handlePcCommand('remember keep API async', runtime(fetch), context)
await handlePcCommand('flush', runtime(fetch), context)

const report = log.mock.calls.map(([message]) => JSON.parse(String(message))).find(Boolean)
expect(report).toMatchObject({ ok: false, code: 'confirmation_required' })
const reports = log.mock.calls.map(([message]) => JSON.parse(String(message))).filter(Boolean)
expect(reports).toEqual([
expect.objectContaining({ ok: false, code: 'confirmation_required' }),
expect.objectContaining({ ok: false, code: 'confirmation_required' }),
])
expect(fetch).not.toHaveBeenCalled()
})

Expand Down
43 changes: 17 additions & 26 deletions src/powercontext/cli/dsh.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
from pathlib import Path
from shutil import which

from powercontext.cli.git_source import (
InvalidGitHubSourceError,
clone_github_source,
)
from powercontext.cli.git_source import (
github_clone_url as _github_clone_url,
)
from powercontext.cli.git_source import (
is_local_source as _is_local_source,
)
from powercontext.cli.system import Diagnostic, DiagnosticStatus, SetupError
from powercontext.paths import powercontext_data_dir

Expand Down Expand Up @@ -131,14 +141,10 @@ def plugin_id_installed(output: str) -> bool:
def github_clone_url(source: str) -> str:
"""Accept a GitHub slug or repository URL and return a clone URL."""

text = source.strip()
if text.startswith(("https://github.com/", "http://github.com/", "git@github.com:")):
return text if text.endswith(".git") else f"{text}.git"
if "://" in text or text.startswith("git@"):
raise SetupError.invalid_dsh_source(source)
if "/" in text and not text.startswith("."):
return f"https://github.com/{text}.git"
raise SetupError.invalid_dsh_source(source)
try:
return _github_clone_url(source)
except InvalidGitHubSourceError:
raise SetupError.invalid_dsh_source() from None


def checkout_target(ref: str) -> Path:
Expand All @@ -157,11 +163,6 @@ def checkout_target(ref: str) -> Path:
return target


def _is_local_source(source: str) -> bool:
candidate = Path(source).expanduser()
return source.startswith((".", "/", "~")) or (len(source) >= 2 and source[1] == ":") or candidate.exists()


def _is_dsh_plugin(path: Path) -> bool:
manifest = path / "package.json"
if not manifest.is_file():
Expand Down Expand Up @@ -189,20 +190,10 @@ def _materialize_remote_checkout(source: str, ref: str) -> Path:


def _clone_github_source(source: str, ref: str, target: Path) -> None:
command = ["git", "clone", "--depth", "1", "--branch", ref, github_clone_url(source), str(target)]
try:
completed = subprocess.run( # noqa: S603 - arguments are passed directly to git.
command,
check=False,
capture_output=True,
text=True,
timeout=120,
)
except (OSError, subprocess.SubprocessError) as error:
raise SetupError.command_unavailable(command, error) from error
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or f"exit code {completed.returncode}"
raise SetupError.command_failed(command, detail)
clone_github_source(source, ref, target)
except InvalidGitHubSourceError:
raise SetupError.invalid_dsh_source() from None


def _run_dsh(*arguments: str) -> str:
Expand Down
68 changes: 68 additions & 0 deletions src/powercontext/cli/git_source.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
"""Validate and clone credential-free GitHub sources for CLI integrations."""

from __future__ import annotations

import subprocess
from pathlib import Path
from urllib.parse import urlsplit

from powercontext.cli.system import SetupError

_GITHUB_HOST = "github.com"


class InvalidGitHubSourceError(ValueError):
"""Raised when a source is not a supported credential-free GitHub repository."""


def is_local_source(source: str) -> bool:
"""Return whether a source describes a local filesystem path."""

candidate = Path(source).expanduser()
return source.startswith((".", "/", "~")) or (len(source) >= 2 and source[1] == ":") or candidate.exists()


def github_clone_url(source: str) -> str:
"""Return a clone URL for a GitHub slug or credential-free GitHub URL."""

text = source.strip()
if text.startswith("git@github.com:"):
return f"git@github.com:{_repository_path(text.removeprefix('git@github.com:'))}"
if text.startswith("git@"):
raise InvalidGitHubSourceError

parsed = urlsplit(text)
if parsed.scheme:
if parsed.scheme not in {"http", "https"} or parsed.netloc != _GITHUB_HOST or parsed.query or parsed.fragment:
raise InvalidGitHubSourceError
return f"{parsed.scheme}://{_GITHUB_HOST}/{_repository_path(parsed.path)}"

return f"https://{_GITHUB_HOST}/{_repository_path(text)}"


def clone_github_source(source: str, ref: str, target: Path) -> None:
"""Clone a supported source without returning command or remote error details."""

command = ["git", "clone", "--depth", "1", "--branch", ref, github_clone_url(source), str(target)]
try:
completed = subprocess.run( # noqa: S603 - arguments are passed directly to git.
command,
check=False,
capture_output=True,
text=True,
timeout=120,
)
except (OSError, subprocess.SubprocessError) as error:
raise SetupError.git_clone_failed() from error
if completed.returncode != 0:
raise SetupError.git_clone_failed()


def _repository_path(value: str) -> str:
path = value.strip().strip("/")
if path.endswith(".git"):
path = path.removesuffix(".git")
parts = path.split("/")
if len(parts) != 2 or any(not part or any(character.isspace() for character in part) for part in parts):
raise InvalidGitHubSourceError
return f"{parts[0]}/{parts[1]}.git"
43 changes: 17 additions & 26 deletions src/powercontext/cli/pi.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,16 @@
from pathlib import Path
from shutil import which

from powercontext.cli.git_source import (
InvalidGitHubSourceError,
clone_github_source,
)
from powercontext.cli.git_source import (
github_clone_url as _github_clone_url,
)
from powercontext.cli.git_source import (
is_local_source as _is_local_source,
)
from powercontext.cli.system import Diagnostic, DiagnosticStatus, SetupError
from powercontext.paths import powercontext_data_dir

Expand Down Expand Up @@ -132,14 +142,10 @@ def pi_package_installed(output: str) -> bool:
def github_clone_url(source: str) -> str:
"""Accept a GitHub slug or repository URL and return a clone URL."""

text = source.strip()
if text.startswith(("https://github.com/", "http://github.com/", "git@github.com:")):
return text if text.endswith(".git") else f"{text}.git"
if "://" in text or text.startswith("git@"):
raise SetupError.invalid_pi_source(source)
if "/" in text and not text.startswith("."):
return f"https://github.com/{text}.git"
raise SetupError.invalid_pi_source(source)
try:
return _github_clone_url(source)
except InvalidGitHubSourceError:
raise SetupError.invalid_pi_source() from None


def checkout_target(ref: str) -> Path:
Expand All @@ -158,11 +164,6 @@ def checkout_target(ref: str) -> Path:
return root / "current"


def _is_local_source(source: str) -> bool:
candidate = Path(source).expanduser()
return source.startswith((".", "/", "~")) or (len(source) >= 2 and source[1] == ":") or candidate.exists()


def _is_pi_package(path: Path) -> bool:
manifest = path / "package.json"
if not manifest.is_file():
Expand Down Expand Up @@ -255,20 +256,10 @@ def _remove_existing_pi_packages() -> None:


def _clone_github_source(source: str, ref: str, target: Path) -> None:
command = ["git", "clone", "--depth", "1", "--branch", ref, github_clone_url(source), str(target)]
try:
completed = subprocess.run( # noqa: S603 - arguments are passed directly to git.
command,
check=False,
capture_output=True,
text=True,
timeout=120,
)
except (OSError, subprocess.SubprocessError) as error:
raise SetupError.command_unavailable(command, error) from error
if completed.returncode != 0:
detail = completed.stderr.strip() or completed.stdout.strip() or f"exit code {completed.returncode}"
raise SetupError.command_failed(command, detail)
clone_github_source(source, ref, target)
except InvalidGitHubSourceError:
raise SetupError.invalid_pi_source() from None


def _run_pi(*arguments: str) -> str:
Expand Down
12 changes: 8 additions & 4 deletions src/powercontext/cli/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,16 +85,20 @@ def invalid_dsh_ref(cls, ref: str) -> SetupError:
return cls(f"invalid DeepSeek Harness ref: {ref}")

@classmethod
def invalid_dsh_source(cls, source: str) -> SetupError:
return cls(f"invalid DeepSeek Harness source: {source}")
def invalid_dsh_source(cls) -> SetupError:
return cls("invalid DeepSeek Harness source; use a local path or credential-free GitHub repository")

@classmethod
def invalid_pi_ref(cls, ref: str) -> SetupError:
return cls(f"invalid Pi ref: {ref}")

@classmethod
def invalid_pi_source(cls, source: str) -> SetupError:
return cls(f"invalid Pi source: {source}")
def invalid_pi_source(cls) -> SetupError:
return cls("invalid Pi source; use a local path or credential-free GitHub repository")

@classmethod
def git_clone_failed(cls) -> SetupError:
return cls("failed to clone the GitHub source")

@classmethod
def data_directory(cls, path: Path, error: OSError) -> SetupError:
Expand Down
13 changes: 13 additions & 0 deletions tests/test_dsh_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ def test_setup_dsh_rejects_a_ref_that_escapes_the_checkout_root(tmp_path: Path,
dsh_cli.resolve_dsh_plugin_dir(source="oceanbase/powercontext", ref="../../etc")


def test_setup_dsh_does_not_echo_source_credentials(tmp_path: Path, monkeypatch) -> None:
import powercontext.cli.dsh as dsh_cli

marker = "redacted-value"
source = f"https://{marker}@github.com/oceanbase/powercontext"
monkeypatch.setenv("POWERCONTEXT_HOME", str(tmp_path / "data"))

with pytest.raises(SetupError) as raised:
dsh_cli.resolve_dsh_plugin_dir(source=source, ref="master")

assert marker not in str(raised.value)


def test_setup_dsh_clones_a_github_url_and_replaces_a_broken_checkout(tmp_path: Path, monkeypatch) -> None:
import powercontext.cli.dsh as dsh_cli

Expand Down
33 changes: 32 additions & 1 deletion tests/test_pi_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@

import json
from pathlib import Path
from subprocess import CompletedProcess

import pytest
from typer.testing import CliRunner

from powercontext.cli.app import create_cli
from powercontext.cli.system import doctor_app, setup_app
from powercontext.cli.system import SetupError, doctor_app, setup_app


def _write_pi_package(root: Path) -> Path:
Expand Down Expand Up @@ -85,6 +87,35 @@ def clone(source: str, ref: str, target: Path) -> None:
assert (current_root / "source.txt").read_text(encoding="utf-8") == "another/powercontext@master"


def test_setup_pi_does_not_echo_source_credentials(tmp_path: Path, monkeypatch) -> None:
import powercontext.cli.pi as pi_cli

marker = "redacted-value"
source = f"https://{marker}@github.com/oceanbase/powercontext"
monkeypatch.setenv("POWERCONTEXT_HOME", str(tmp_path / "data"))

with pytest.raises(SetupError) as raised:
pi_cli.resolve_pi_plugin_dir(source=source, ref="master")

assert marker not in str(raised.value)


def test_setup_pi_does_not_echo_git_clone_output(tmp_path: Path, monkeypatch) -> None:
import powercontext.cli.pi as pi_cli

marker = "redacted-value"
monkeypatch.setenv("POWERCONTEXT_HOME", str(tmp_path / "data"))
monkeypatch.setattr(
"subprocess.run",
lambda command, **_kwargs: CompletedProcess(command, 1, "", f"fatal: https://{marker}@github.com/failed"),
)

with pytest.raises(SetupError) as raised:
pi_cli.resolve_pi_plugin_dir(source="oceanbase/powercontext", ref="master")

assert marker not in str(raised.value)


def test_doctor_pi_reports_a_missing_cli(monkeypatch) -> None:
import powercontext.cli.pi as pi_cli

Expand Down