diff --git a/.github/workflows/kiro-no-auth-installation.yml b/.github/workflows/kiro-no-auth-installation.yml index da2699e565..23e657515d 100644 --- a/.github/workflows/kiro-no-auth-installation.yml +++ b/.github/workflows/kiro-no-auth-installation.yml @@ -85,6 +85,14 @@ jobs: shell: bash working-directory: install/integrationctl/agentplugins run: go test -json -count=1 -timeout=180s ./installer -run '^Test(ProjectKiroPublicSDKStdioDataRepairRestartAndRemove|FacadeHostedPreparation(PinsIntentAndSnapshot|PreservesAutomaticAndOtherFailures|RefusesAppearingRetainedInstallation|PreservesRecordedModesAndOwnership|EligibilityDoesNotBroadenScopeOrConsent|RejectsRetainedStateAtMutationLock))$' | tee "$RUNNER_TEMP/kiro-composed-sdk.log" + - name: Verify public Kiro CLI publisher approval install and repair + shell: bash + working-directory: cli + run: go test -json -count=1 -timeout=180s ./internal/agentpluginscli -run '^TestKiro(PublisherMCPApprovalsFullCLI|SkillsWithoutMCPApprovalFullCLI)$' | tee "$RUNNER_TEMP/kiro-composed-cli-trust.log" + - name: Verify Kiro exact MCP approval and ownership lifecycles + shell: bash + working-directory: install/integrationctl/agentplugins + run: go test -json -count=1 -timeout=180s ./clients/kiro -run '^TestKiro(NamedMCPApprovalSchemaFailClosed|ApprovalWithoutSelectedMCPKeepsSkills|ApprovalPreviewAndNoUnselectedPrivilege|ExactApprovalPreservesNativeVerifierAndAutomaticActivation|ExactMCPApprovalDisposableLifecycle|ProjectApprovalDoesNotForgeWorkspaceTrust|ActiveApprovedToolsRefuseStaleReprojection|UserEditedAutoApprovalBlocksRemoval)$' | tee "$RUNNER_TEMP/kiro-composed-sdk-trust.log" - name: Admit actual named cases and unchanged source if: ${{ always() }} shell: bash @@ -132,7 +140,38 @@ jobs: 'TestFacadeHostedPreparationEligibilityDoesNotBroadenScopeOrConsent/attested', 'TestFacadeHostedPreparationEligibilityDoesNotBroadenScopeOrConsent/update', 'TestFacadeHostedPreparationEligibilityDoesNotBroadenScopeOrConsent/recorded', - 'TestFacadeHostedPreparationRejectsRetainedStateAtMutationLock']} + 'TestFacadeHostedPreparationRejectsRetainedStateAtMutationLock'], + 'cli-trust': ['TestKiroPublisherMCPApprovalsFullCLI', + 'TestKiroSkillsWithoutMCPApprovalFullCLI'], + 'sdk-trust': ['TestKiroNamedMCPApprovalSchemaFailClosed', + 'TestKiroApprovalWithoutSelectedMCPKeepsSkills', + 'TestKiroNamedMCPApprovalSchemaFailClosed/empty', + 'TestKiroNamedMCPApprovalSchemaFailClosed/root', + 'TestKiroNamedMCPApprovalSchemaFailClosed/unsupported-version', + 'TestKiroNamedMCPApprovalSchemaFailClosed/empty-list', + 'TestKiroNamedMCPApprovalSchemaFailClosed/wildcard', + 'TestKiroNamedMCPApprovalSchemaFailClosed/embedded-wildcard', + 'TestKiroNamedMCPApprovalSchemaFailClosed/path', + 'TestKiroNamedMCPApprovalSchemaFailClosed/duplicate-tool', + 'TestKiroNamedMCPApprovalSchemaFailClosed/duplicate-server', + 'TestKiroNamedMCPApprovalSchemaFailClosed/unknown-field', + 'TestKiroNamedMCPApprovalSchemaFailClosed/field-alias', + 'TestKiroNamedMCPApprovalSchemaFailClosed/field-alias-server', + 'TestKiroNamedMCPApprovalSchemaFailClosed/noncanonical-number', + 'TestKiroNamedMCPApprovalSchemaFailClosed/wrong-shape', + 'TestKiroNamedMCPApprovalSchemaFailClosed/null', + 'TestKiroNamedMCPApprovalSchemaFailClosed/trailing-content', + 'TestKiroApprovalPreviewAndNoUnselectedPrivilege', + 'TestKiroExactApprovalPreservesNativeVerifierAndAutomaticActivation', + 'TestKiroExactMCPApprovalDisposableLifecycle', + 'TestKiroExactMCPApprovalDisposableLifecycle/install', + 'TestKiroExactMCPApprovalDisposableLifecycle/repeat', + 'TestKiroExactMCPApprovalDisposableLifecycle/update', + 'TestKiroExactMCPApprovalDisposableLifecycle/repair', + 'TestKiroExactMCPApprovalDisposableLifecycle/narrow', + 'TestKiroProjectApprovalDoesNotForgeWorkspaceTrust', + 'TestKiroActiveApprovedToolsRefuseStaleReprojection', + 'TestKiroUserEditedAutoApprovalBlocksRemoval']} receipts = [] for label, tests in required.items(): path = root / ('kiro-composed-' + label + '.log') @@ -153,7 +192,7 @@ jobs: receipt = {'source_before': before, 'source_after': after, 'logs': receipts, 'qualification': 'UAP composed installation only; inert discovery/security/helper seams; no native Kiro loading'} (root / 'kiro-composed-admission.json').write_text(json.dumps(receipt, sort_keys=True, indent=2) + '\n') - print('PASS: exact CLI Git/ZIP and SDK lifecycle RUN/PASS cases; clean source preserved') + print('PASS: exact Kiro CLI+SDK approval cases and Git/ZIP lifecycle RUN/PASS on unchanged source') PYTHON - name: Preserve actual lifecycle logs and source admission if: ${{ always() }} diff --git a/.github/workflows/live-install-audit.yml b/.github/workflows/live-install-audit.yml index cebd0e4440..5eabce3070 100644 --- a/.github/workflows/live-install-audit.yml +++ b/.github/workflows/live-install-audit.yml @@ -6,9 +6,16 @@ on: paths: - 'scripts/prepare-codex-linux-sandbox.sh' - 'scripts/live-install-audit.py' + - 'scripts/pi_project_skill_audit.py' + - 'scripts/test_pi_project_skill_audit.py' + - 'scripts/qoder_prepared_skill_audit.py' + - 'scripts/test_qoder_prepared_skill_audit.py' + - 'scripts/native_client_research.py' + - 'scripts/test_native_client_research.py' - 'scripts/published_codex_baseline.py' - 'scripts/test_published_codex_baseline.py' - 'scripts/test_live_install_audit_env.py' + - 'scripts/test_live_install_audit_opencode_negative.py' - 'scripts/test_kimi_repeat_log_audit.py' - 'scripts/codex_runtime_audit.py' - 'scripts/claude_cache_retirement_audit.py' @@ -70,10 +77,14 @@ jobs: codex --version # The Go source defaults to 0.1.0-development; signed directory policies # require an ordinary release-semver CLI. This is still the PR source - # binary, NOT the published agentplugins-v0.1.95 release. + # binary, NOT the published agentplugins-v0.1.115 release. - name: Refuse ambient native-profile and Git configuration leakage run: | python3 -m unittest discover -s scripts -p 'test_live_install_audit_env.py' + python3 -m unittest discover -s scripts -p 'test_qoder_prepared_skill_audit.py' + python3 -m unittest discover -s scripts -p 'test_native_client_research.py' + python3 -m unittest discover -s scripts -p 'test_pi_project_skill_audit.py' + python3 -m unittest discover -s scripts -p 'test_live_install_audit_opencode_negative.py' python3 -m unittest discover -s scripts -p 'test_kimi_repeat_log_audit.py' python3 -m unittest discover -s scripts -p 'test_gemini_windows_runtime_audit.py' python3 -m unittest discover -s scripts -p 'test_codex_runtime_audit.py' @@ -81,7 +92,7 @@ jobs: - name: Verify exact empty-stderr LintAI exit diagnostic run: go test ./install/integrationctl/agentplugins/adapters/securityscan -run '^TestCommandScannerIncludesNonzeroExitWhenStderrIsEmpty$' -count=1 - name: Build actual PR CLI with current eligible directory version policy - run: go build -trimpath -ldflags='-X main.version=0.1.95' -o "$RUNNER_TEMP/agentplugins-audit" ./cli/cmd/agentplugins + run: go build -trimpath -ldflags='-X main.version=0.1.115' -o "$RUNNER_TEMP/agentplugins-audit" ./cli/cmd/agentplugins - name: Run isolated real source install and remove; preserve per-case proof env: AUDIT_VENDOR_OUTCOME: ${{ steps.native-install-pilot.outcome }} @@ -104,7 +115,7 @@ jobs: published-cli-smoke: - name: Published npm 0.1.95 / Codex CLI parity + name: Historical npm 0.1.95 / Codex lifecycle and default refusal needs: native-pilot runs-on: ubuntu-24.04 timeout-minutes: 25 @@ -137,7 +148,9 @@ jobs: result=0 for kind in plugin skill; do # Keep this immutable release's lifecycle distinct from current Ready. - acceptance=native + # Observe the default feed refusal separately; only the plugin + # lifecycle uses the unexpired, original-key official sequence 48. + acceptance=published-0.1.95-codex-plugins-archived-feed if [ "$kind" = skill ]; then acceptance=published-0.1.95-codex-skills; fi python3 scripts/live-install-audit.py --cli "$(command -v agentplugins)" \ --target codex --kind "$kind" --limit 2 --acceptance "$acceptance" \ @@ -154,7 +167,7 @@ jobs: retention-days: 14 real-native-cli-matrix: - name: All 30 ${{ matrix.kind }} / native ${{ matrix.target }} + name: All 30 ${{ matrix.kind }} / ${{ matrix.target == 'pi' && matrix.kind == 'skill' && 'foreign Prepared + clean native' || matrix.target == 'qoder' && matrix.kind == 'skill' && 'Prepared installation' || 'native' }} ${{ matrix.target }} needs: native-pilot runs-on: ubuntu-24.04 timeout-minutes: 65 @@ -187,6 +200,7 @@ jobs: env: TARGET: ${{ matrix.target }} KIND: ${{ matrix.kind }} + CLINE_NO_AUTO_UPDATE: '1' shell: bash run: | set -euo pipefail @@ -212,10 +226,12 @@ jobs: binary="$TARGET" if [[ "$TARGET" == qoder ]]; then binary=qodercli; fi command -v "$binary" - timeout 25s "$binary" --version + native_version=$(timeout 25s "$binary" --version) + printf '%s\n' "$native_version" + if [[ "$TARGET" == cline ]]; then [[ "$native_version" == 3.0.74 ]]; fi - name: Build PR source CLI with current signed Registry eligibility version if: ${{ !cancelled() }} # BUG-010: retain negative evidence after native bootstrap failure - run: go build -trimpath -ldflags='-X main.version=0.1.95' -o "$RUNNER_TEMP/agentplugins-audit" ./cli/cmd/agentplugins + run: go build -trimpath -ldflags='-X main.version=0.1.115' -o "$RUNNER_TEMP/agentplugins-audit" ./cli/cmd/agentplugins - name: Attempt all 30 independent pinned sources in isolated profiles if: ${{ !cancelled() }} # Missing client produces explicit non-PASS source rows env: @@ -223,9 +239,42 @@ jobs: KIND: ${{ matrix.kind }} AUDIT_VENDOR_OUTCOME: ${{ steps.native-install.outcome }} run: | - python3 scripts/live-install-audit.py --cli "$RUNNER_TEMP/agentplugins-audit" \ - --target "$TARGET" --kind "$KIND" --limit 30 \ - --report-dir "$RUNNER_TEMP/full-proof" + if [[ "$TARGET" == pi && "$KIND" == skill ]]; then + # Two independent fresh invocations: never move or remove a foreign + # Skill to turn an existing Prepared project into a trusted one. + foreign_status=0 + python3 scripts/live-install-audit.py --cli "$RUNNER_TEMP/agentplugins-audit" \ + --target pi --kind skill --limit 30 --acceptance pi-foreign-prepared-skills-installation \ + --report-dir "$RUNNER_TEMP/full-proof/pi-foreign-prepared" || foreign_status=$? + native_status=0 + python3 scripts/live-install-audit.py --cli "$RUNNER_TEMP/agentplugins-audit" \ + --target pi --kind skill --limit 30 --acceptance pi-clean-native-skills \ + --report-dir "$RUNNER_TEMP/full-proof/pi-clean-native" || native_status=$? + [[ "$foreign_status" -eq 0 && "$native_status" -eq 0 ]] + else + acceptance=native + if [[ "$TARGET" == qoder && "$KIND" == skill ]]; then + acceptance=qoder-prepared-skills-installation + fi + python3 scripts/live-install-audit.py --cli "$RUNNER_TEMP/agentplugins-audit" \ + --target "$TARGET" --kind "$KIND" --limit 30 --acceptance "$acceptance" \ + --report-dir "$RUNNER_TEMP/full-proof" + fi + - name: Verify the audited Cline version matches this workflow pin + if: ${{ !cancelled() && matrix.target == 'cline' }} + env: + KIND: ${{ matrix.kind }} + run: | + python3 - <<'CLINE_PIN' + import json, os + from pathlib import Path + report = json.loads((Path(os.environ["RUNNER_TEMP"]) / "full-proof" / + ("cline-" + os.environ["KIND"] + ".json")).read_text()) + version = report.get("client_version", {}) + if not (version.get("status") == "reported" and version.get("value") == "3.0.74" + and type(version.get("exit_code")) is int and version["exit_code"] == 0): + raise SystemExit("Cline audit did not observe this workflow's pinned 3.0.74: " + repr(version)) + CLINE_PIN - name: Upload all per-source installation outcomes (even on failures) if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.0 diff --git a/cli/internal/agentpluginscli/deps_apply.go b/cli/internal/agentpluginscli/deps_apply.go index 8b83b8f99a..cd41c0d6e3 100644 --- a/cli/internal/agentpluginscli/deps_apply.go +++ b/cli/internal/agentpluginscli/deps_apply.go @@ -8,6 +8,7 @@ import ( "fmt" "os" "reflect" + "slices" "github.com/spf13/cobra" @@ -236,6 +237,7 @@ func detectDependencyClients(ctx context.Context, app App) (map[domain.ClientID] } detected := map[domain.ClientID]domain.DetectedClient{} for _, client := range clients { + client.Surfaces = slices.Clone(client.Surfaces) detected[client.ClientID] = client } return detected, nil diff --git a/cli/internal/agentpluginscli/deps_sync.go b/cli/internal/agentpluginscli/deps_sync.go index 64b6ba000b..61724e4e40 100644 --- a/cli/internal/agentpluginscli/deps_sync.go +++ b/cli/internal/agentpluginscli/deps_sync.go @@ -255,7 +255,7 @@ func (adapter *dependencyInstaller) Prepare(ctx context.Context, action environm } } adapter.currentAction = action - request := installer.Request{Scope: adapter.app.scope(), ProjectRoot: adapter.app.ProjectRoot, OperationID: operationID, Operation: installer.Operation(action.Action), ClientID: action.ClientID, ClientConfigRoot: client.ConfigRoot, + request := installer.Request{Scope: adapter.app.scope(), ProjectRoot: adapter.app.ProjectRoot, OperationID: operationID, Operation: installer.Operation(action.Action), ClientID: action.ClientID, ClientConfigRoot: client.ConfigRoot, ClientSurfaces: slices.Clone(client.Surfaces), ConfirmPluginEnable: adapter.opts.confirmPluginEnable && action.Action == "repair", ClientNativeConfigRoot: dependencyNativeConfigRoot(adapter.app, client), ClientExecutable: backendExecutable(client, adapter.detected, adapter.app.scope()), ClientVersion: client.Version, InstallationID: action.InstallationID, diff --git a/cli/internal/agentpluginscli/installer_facade.go b/cli/internal/agentpluginscli/installer_facade.go index 5d62891530..3ac26f55e8 100644 --- a/cli/internal/agentpluginscli/installer_facade.go +++ b/cli/internal/agentpluginscli/installer_facade.go @@ -4,6 +4,7 @@ import ( "context" "errors" "path/filepath" + "slices" "github.com/spf13/cobra" @@ -64,7 +65,7 @@ func runInstallerFacadeLocalAdd(ctx context.Context, cmd *cobra.Command, app App OnlinePreview: !opts.dryRun, SourceRoot: loaded.envelope.Source.CanonicalSource, ExecutableFiles: append([]string{}, loaded.envelope.ExecutableFiles...), - ClientID: string(selected.ClientID), ClientConfigRoot: selected.ConfigRoot, + ClientID: string(selected.ClientID), ClientConfigRoot: selected.ConfigRoot, ClientSurfaces: slices.Clone(selected.Surfaces), ClientExecutable: backendExecutable(selected, detected, app.scope()), ClientVersion: selected.Version, OperationID: operationID, RequiredComponents: requiredFacadeComponents(loaded.envelope), Assessment: &assessment, } diff --git a/cli/internal/agentpluginscli/kiro_mcp_approvals_e2e_test.go b/cli/internal/agentpluginscli/kiro_mcp_approvals_e2e_test.go new file mode 100644 index 0000000000..288d23880c --- /dev/null +++ b/cli/internal/agentpluginscli/kiro_mcp_approvals_e2e_test.go @@ -0,0 +1,198 @@ +package agentpluginscli + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/providers" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/providerstest" +) + +// This drives the public CLI command, official plugin.json extension, loader, +// planner, native staging, ownership receipts, and Kiro's real config mutation. +// The Kiro runtime and account are deliberately not mocked as "verified". +func TestKiroPublisherMCPApprovalsFullCLI(t *testing.T) { + client := fixtureClient(t, domain.ClientKiro) + client.ExecutablePath = "/fixture/kiro-cli" + fixture := newCLIFixture(t, []domain.DetectedClient{client}) + fixture.app.Lifecycle.Activator = providerstest.NewActivator(providers.Activator{}) + + source := writeCLIPlugin(t) + writeCLIMCP(t, source) + manifestPath := filepath.Join(source, "plugin.json") + body, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(body, &manifest); err != nil { + t.Fatal(err) + } + manifest["extensions"] = map[string]any{ + "com.universal-agent-plugins.kiro-mcp-approval": map[string]any{ + "version": 1, + "mcp_auto_approve": map[string]any{"demo": []string{"read_docs"}}, + }, + } + modified, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(manifestPath, modified, 0600); err != nil { + t.Fatal(err) + } + + nativePath := filepath.Join(client.ConfigRoot, "settings", "mcp.json") + assertNative := func() { + t.Helper() + body, err := os.ReadFile(nativePath) + if err != nil { + t.Fatal(err) + } + var config map[string]any + if err := json.Unmarshal(body, &config); err != nil { + t.Fatal(err) + } + servers, ok := config["mcpServers"].(map[string]any) + if !ok { + t.Fatalf("missing native Kiro MCP servers: %s", body) + } + owned, ok := servers["demo"].(map[string]any) + if !ok || !reflect.DeepEqual(owned["autoApprove"], []any{"read_docs"}) { + t.Fatalf("Kiro exact approved tool was not installed: %s", body) + } + if _, err := os.Stat(filepath.Join(client.ConfigRoot, "settings", "permissions.yaml")); !os.IsNotExist(err) { + t.Fatalf("unexpected global Kiro trust: %v", err) + } + } + for _, action := range []string{"add", "add", "repair"} { + args := []string{action, source, "--target", "kiro", "--format", "json"} + if action == "repair" { + args[1] = "demo" + } + out, stderr, err := fixture.execute(false, args...) + if err != nil { + t.Fatalf("%s failed: %s %s (%v)", action, out, stderr, err) + } + if !strings.Contains(out, "prepared") { + t.Fatalf("%s falsely claims native activation or lost preparation: %s", action, out) + } + assertNative() + } + state, err := fixture.store.Load() + if err != nil || len(state.Installations) != 1 || len(state.Installations[0].Clients) != 1 { + t.Fatalf("unexpected persisted installation: %+v, %v", state, err) + } + for _, binding := range state.Installations[0].Clients { + if binding.InstallIntent != domain.InstallIntentPrepare { + t.Fatal("Kiro installation lost prepared runtime boundary") + } + } + installationID := state.Installations[0].InstallationID + // Uninstall must revoke the granted tool consent through the public CLI, + // not only through a direct native-config adapter call. + stdout, stderr, err := fixture.execute(false, "remove", "demo", "--target", "kiro", "--format", "json") + if err != nil { + t.Fatalf("remove failed: %s %s (%v)", stdout, stderr, err) + } + if body, err := os.ReadFile(nativePath); err == nil { + var config map[string]any + if err := json.Unmarshal(body, &config); err != nil { + t.Fatal(err) + } + if servers, ok := config["mcpServers"].(map[string]any); ok { + if _, present := servers["demo"]; present { + t.Fatalf("remove retained the approved Kiro MCP server: %s", body) + } + } + } else if !os.IsNotExist(err) { + t.Fatal(err) + } + state, err = fixture.store.Load() + if err != nil || len(state.Installations) != 1 { + t.Fatalf("remove lost retained-data installation: %+v, %v", state, err) + } + retained := state.Installations[0] + if retained.InstallationID != installationID || len(retained.Clients) != 0 || + !retained.DataRetained || len(retained.DataReceipts) == 0 { + t.Fatalf("remove failed Kiro retained-data contract: %+v", retained) + } +} + +// A Directory preview may offer Skills even when the same source carries a +// Kiro-only MCP consent extension but no MCP server. Test the public install +// path rather than treating the catalog preview as runtime proof. +func TestKiroSkillsWithoutMCPApprovalFullCLI(t *testing.T) { + client := fixtureClient(t, domain.ClientKiro) + client.ExecutablePath = "/fixture/kiro-cli" + fixture := newCLIFixture(t, []domain.DetectedClient{client}) + fixture.app.Lifecycle.Activator = providerstest.NewActivator(providers.Activator{}) + + source := writeCLIPlugin(t) + skill := filepath.Join(source, "skills", "docs", "SKILL.md") + if err := os.MkdirAll(filepath.Dir(skill), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(skill, []byte("---\nname: docs\ndescription: Harmless documentation Skill\n---\n\n# Docs\n"), 0600); err != nil { + t.Fatal(err) + } + manifestPath := filepath.Join(source, "plugin.json") + body, err := os.ReadFile(manifestPath) + if err != nil { + t.Fatal(err) + } + var manifest map[string]any + if err := json.Unmarshal(body, &manifest); err != nil { + t.Fatal(err) + } + manifest["extensions"] = map[string]any{ + "com.universal-agent-plugins.kiro-mcp-approval": map[string]any{ + "version": 1, "mcp_auto_approve": map[string]any{"missing": []string{"read_docs"}}, + }, + } + modified, err := json.Marshal(manifest) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(manifestPath, modified, 0600); err != nil { + t.Fatal(err) + } + stdout, stderr, err := fixture.execute(false, "add", source, "--target", "kiro", "--format", "json") + if err != nil { + t.Fatalf("Skills-only Kiro add failed: %s %s (%v)", stdout, stderr, err) + } + assertVersionedJSON(t, stdout, "add") + if _, err := os.Stat(filepath.Join(client.ConfigRoot, "skills", "docs", "SKILL.md")); err != nil { + t.Fatalf("Kiro portable Skill was not installed: %v", err) + } + for _, path := range []string{ + filepath.Join(client.ConfigRoot, "settings", "mcp.json"), + filepath.Join(client.ConfigRoot, "settings", "permissions.yaml"), + } { + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Fatalf("Kiro invented unselected MCP permissions at %s: %v", path, err) + } + } + state, err := fixture.store.Load() + if err != nil || len(state.Installations) != 1 || len(state.Installations[0].Clients) != 1 { + t.Fatalf("Skills-only Kiro installation lost ownership: %+v, %v", state, err) + } + for _, binding := range state.Installations[0].Clients { + ownedKinds := make(map[string]string, len(binding.NativeObjects)) + for _, object := range binding.NativeObjects { + ownedKinds[object.ObjectID] = object.Kind + } + wantKinds := map[string]string{ + "package:kiro:" + binding.PhysicalArtifact: "managed_package_directory", + "kiro-skill:docs": "kiro_global_skill_directory", + } + if len(binding.NativeObjects) != len(wantKinds) || !reflect.DeepEqual(ownedKinds, wantKinds) { + t.Fatalf("Skills-only Kiro installation gained foreign or MCP ownership: %+v", binding.NativeObjects) + } + } +} diff --git a/cli/internal/agentpluginscli/skills_batch.go b/cli/internal/agentpluginscli/skills_batch.go index 6fd40202bd..beade31a96 100644 --- a/cli/internal/agentpluginscli/skills_batch.go +++ b/cli/internal/agentpluginscli/skills_batch.go @@ -96,7 +96,7 @@ func (p *PreparedSkillsBatch) check(ctx context.Context) error { return ErrSkillsPlanStale } old, current := p.request.detected[domain.ClientID(action.ClientID)], detected[domain.ClientID(action.ClientID)] - if old.ConfigRoot != current.ConfigRoot || old.ExecutablePath != current.ExecutablePath { + if old.ConfigRoot != current.ConfigRoot || old.ExecutablePath != current.ExecutablePath || !reflect.DeepEqual(old.Surfaces, current.Surfaces) { return ErrSkillsPlanStale } } diff --git a/cli/internal/agentpluginscli/skills_native_surfaces_test.go b/cli/internal/agentpluginscli/skills_native_surfaces_test.go new file mode 100644 index 0000000000..c2b5ddf017 --- /dev/null +++ b/cli/internal/agentpluginscli/skills_native_surfaces_test.go @@ -0,0 +1,337 @@ +package agentpluginscli + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" + + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/adapters/statev2" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients/cline" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients/copilot" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/installer" + legacyports "github.com/777genius/plugin-kit-ai/install/integrationctl/ports" +) + +// Only ordinary native catalogs are controlled. Package projection, registration, +// ownership receipts, activation and public rendering use the real installer. +type rawSurfaceRunner struct { + t *testing.T + client domain.ClientID + project, executable, profile string + falseCatalog bool + calls []string +} + +func (r *rawSurfaceRunner) Run(ctx context.Context, command legacyports.Command) (legacyports.CommandResult, error) { + return r.catalog(ctx, command) +} + +func (r *rawSurfaceRunner) RunWithTreeExitGrace(ctx context.Context, command legacyports.Command, grace time.Duration) (legacyports.CommandResult, error) { + if grace != time.Second { + r.t.Fatalf("native catalog closure grace: %s", grace) + } + return r.catalog(ctx, command) +} + +func (r *rawSurfaceRunner) catalog(ctx context.Context, c legacyports.Command) (legacyports.CommandResult, error) { + r.t.Helper() + if _, bounded := ctx.Deadline(); !bounded || c.Dir != r.project || c.StdoutLimitBytes <= 0 || c.StdoutLimitBytes > 1<<20 { + r.t.Fatalf("unbounded or wrong-project native query: %+v", c) + } + kind := "skills" + want := []string{r.executable, "--auto-approve", "false", "--cwd", r.project, "config", "skills", "--json"} + if r.client == domain.ClientCopilot { + if len(c.Argv) != 4 { + r.t.Fatalf("unexpected Copilot command: %+v", c) + } + kind = c.Argv[1] + want = []string{r.executable, kind, "list", "--json"} + if kind != "plugin" && kind != "skill" { + r.t.Fatalf("unexpected catalog kind %q", kind) + } + } + if !reflect.DeepEqual(c.Argv, want) { + r.t.Fatalf("native query changed: %+v", c) + } + r.calls = append(r.calls, kind) + rows := []map[string]any{} + if !r.falseCatalog { + if r.client == domain.ClientCopilot { + rows = r.copilotRows(kind) + } else { + rows = r.clineRows() + } + } + body, err := json.Marshal(rows) + return legacyports.CommandResult{Stdout: body, CleanupComplete: true}, err +} + +func (r *rawSurfaceRunner) readJSON(path string, target any) { + r.t.Helper() + body, err := os.ReadFile(path) + if err != nil { + r.t.Fatal(err) + } + if err := json.Unmarshal(body, target); err != nil { + r.t.Fatal(path, err) + } +} + +func (r *rawSurfaceRunner) copilotRows(kind string) []map[string]any { + r.t.Helper() + var settings struct { + Marketplaces map[string]struct{ Source struct{ Source, Path string } } `json:"extraKnownMarketplaces"` + Enabled map[string]bool `json:"enabledPlugins"` + } + r.readJSON(filepath.Join(r.project, ".github", "copilot", "settings.local.json"), &settings) + if len(settings.Enabled) != 1 || len(settings.Marketplaces) != 1 { + r.t.Fatalf("unexpected real registration: %+v", settings) + } + rows := []map[string]any{} + for key, enabled := range settings.Enabled { + name, market, ok := strings.Cut(key, "@") + source := settings.Marketplaces[market].Source + if !ok || !enabled || source.Source != "directory" { + r.t.Fatalf("invalid installed registration: %q %+v", key, source) + } + active := source.Path + if !filepath.IsAbs(active) { + active = filepath.Join(r.project, filepath.FromSlash(active)) + } + var manifest struct{ Name string } + r.readJSON(filepath.Join(active, "plugin.json"), &manifest) + if manifest.Name != name { + r.t.Fatalf("registration/manifest mismatch: %q %+v", key, manifest) + } + if kind == "plugin" { + var marketplace struct { + Name string + Plugins []struct{ Name, Version, Source string } + } + r.readJSON(filepath.Join(active, ".github", "plugin", "marketplace.json"), &marketplace) + if marketplace.Name != market || len(marketplace.Plugins) != 1 || marketplace.Plugins[0].Name != name || marketplace.Plugins[0].Source != "." { + r.t.Fatalf("projected marketplace differs from registration: %+v", marketplace) + } + rows = append(rows, map[string]any{"name": name, "marketplace": market, "version": marketplace.Plugins[0].Version, "enabled": enabled, "source": "live", "installedFrom": active}) + } else { + rows = append(rows, r.skillRows(filepath.Join(active, "skills"), false)...) + } + } + return rows +} + +func (r *rawSurfaceRunner) clineRows() []map[string]any { + return r.skillRows(filepath.Join(r.project, ".cline", "skills"), true) +} + +func (r *rawSurfaceRunner) skillRows(root string, clineCatalog bool) []map[string]any { + r.t.Helper() + entries, err := os.ReadDir(root) + if err != nil { + r.t.Fatal(err) + } + rows := make([]map[string]any, 0, len(entries)) + for _, entry := range entries { + path := filepath.Join(root, entry.Name(), "SKILL.md") + body, err := os.ReadFile(path) + if err != nil { + r.t.Fatal(err) + } + // This source is owned by managementMutableWebsite. Assert the real + // installed bytes before producing a catalog; no private receipts are made. + if string(body) != "---\nname: pdf\ndescription: Read PDFs\n---\nFirst reviewed content.\n" { + r.t.Fatalf("unexpected installed Skill: %s", body) + } + row := map[string]any{"name": entry.Name(), "description": "Read PDFs", "path": filepath.Dir(path), "source": "plugin", "enabled": true} + if clineCatalog { + row = map[string]any{"name": entry.Name(), "description": "Read PDFs", "path": path, "instructions": "First reviewed content.", "frontmatter": map[string]any{"name": "pdf", "description": "Read PDFs"}} + } + rows = append(rows, row) + } + if len(rows) != 1 { + r.t.Fatalf("expected exactly one actually installed Skill: %+v", rows) + } + return rows +} + +func rawSurfaceFixture(t *testing.T, id domain.ClientID, mode string) (savedJourney, *rawSurfaceRunner, string) { + t.Helper() + _, journey, source, _ := managementMutableWebsite(t) + base, err := filepath.EvalSymlinks(journey.cli.root) + if err != nil { + t.Fatal(err) + } + project, profile := filepath.Join(base, "project"), filepath.Join(base, "native-profile") + for _, path := range []string{project, profile, filepath.Join(base, "bin")} { + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + } + dependencyWrite(t, filepath.Join(project, "foreign.txt"), "foreign original bytes") + executable := filepath.Join(base, "bin", string(id)) + dependencyWrite(t, executable, "inert fixture; controlled native runner only") + if err := os.Chmod(executable, 0700); err != nil { + t.Fatal(err) + } + version := "1.0.105" + if id == domain.ClientCline { + version = "3.0.74" + } + surface := domain.ClientSurface{ID: string(id) + "_cli", Detected: true, Evidence: "fixture observed CLI"} + switch mode { + case "false-surface": + surface.Detected = false + case "wrong-surface": + surface.ID = "editor" + } + client := domain.DetectedClient{ClientID: id, Status: domain.DetectionDetected, Version: version, ExecutablePath: executable, ConfigRoot: profile, Surfaces: []domain.ClientSurface{surface}} + // Cline ordinary detection resolves its CLI only at the guarded session seam. + if id == domain.ClientCline { + client.ExecutablePath = "" + } + if mode == "missing-surface" { + client.Surfaces = nil + } + if id == domain.ClientCopilot { + body, err := json.Marshal(map[string]any{"trustedFolders": []string{project}, "foreign": "retained"}) + if err != nil { + t.Fatal(err) + } + dependencyWrite(t, filepath.Join(profile, "config.json"), string(body)) + } + runner := &rawSurfaceRunner{t: t, client: id, project: project, profile: profile, executable: executable, falseCatalog: mode == "false-catalog"} + configureRawSurfaceApp(t, &journey, client, runner) + return journey, runner, source +} + +func configureRawSurfaceApp(t *testing.T, journey *savedJourney, client domain.DetectedClient, runner *rawSurfaceRunner) { + t.Helper() + stateRoot := filepath.Join(runner.project, ".uap") + journey.cli.store = statev2.Store{Path: filepath.Join(stateRoot, "state-v2.json"), ProjectRoot: runner.project} + journey.cli.operations = filepath.Join(stateRoot, "operations-v2") + app := &journey.cli.app + app.Scope, app.ProjectRoot, app.ManagedRoot = domain.ScopeProject, runner.project, filepath.Join(stateRoot, "managed") + app.DependenciesRoot, app.StateStore = runner.project, journey.cli.store + app.EnvironmentLockPath, app.EnvironmentStoreRoot = filepath.Join(stateRoot, "environment.lock"), filepath.Join(stateRoot, "store") + app.Detector = staticDetector{clients: []domain.DetectedClient{client}} + var err error + app.ClientRegistry, err = clients.NewRegistry(copilot.New(), cline.New()) + if err != nil { + t.Fatal(err) + } + helper, err := os.Executable() + if err != nil { + t.Fatal(err) + } + app.Installer, err = installer.New(installer.Config{ProjectRoot: runner.project, StateRoot: stateRoot, StateFile: journey.cli.store.Path, + Registry: app.ClientRegistry, Runner: runner, HelperExecutable: helper, EnableNativeObserver: true, + LookupExecutable: func(name string) (string, error) { + if name != string(client.ClientID) { + t.Fatalf("unexpected executable lookup %q", name) + } + return runner.executable, nil + }}) + if err != nil { + t.Fatal(err) + } +} + +func TestRawSkillsPreserveObservedNativeCLISurfaces(t *testing.T) { + for _, id := range []domain.ClientID{domain.ClientCopilot, domain.ClientCline} { + for _, mode := range []string{"observed", "missing-surface", "false-surface", "wrong-surface", "false-catalog"} { + t.Run(string(id)+"/"+mode, func(t *testing.T) { checkRawSurfaceAdd(t, id, mode) }) + } + } +} + +func TestPreparedRawSkillsRejectChangedCLISurface(t *testing.T) { + for _, id := range []domain.ClientID{domain.ClientCopilot, domain.ClientCline} { + t.Run(string(id), func(t *testing.T) { + journey, runner, source := rawSurfaceFixture(t, id, "observed") + plan, err := journey.cli.app.PrepareSkills(t.Context(), SkillsBatchRequest{ + Selections: []SkillsSelection{{Website: source, Name: "pdf"}}, TargetIDs: []string{string(id)}, + }) + if err != nil { + t.Fatal(err) + } + defer plan.Close() + // The detector deliberately reuses its backing slice. A fresh host + // observation must not mutate the already reviewed surface evidence. + detector := journey.cli.app.Detector.(staticDetector) + detector.clients[0].Surfaces[0].Detected = false + if err := plan.Check(t.Context()); !errors.Is(err, ErrSkillsPlanStale) { + t.Fatalf("changed surface passed prepared review: %v", err) + } + if _, err := plan.Apply(t.Context()); !errors.Is(err, ErrSkillsPlanStale) { + t.Fatalf("changed surface reached installation: %v", err) + } + if len(runner.calls) != 0 || len(journey.state(t).Installations) != 0 { + t.Fatal("stale surface plan ran native catalogs or committed installation") + } + for _, path := range []string{filepath.Join(runner.project, "uap.toml"), filepath.Join(runner.project, "uap.lock")} { + if _, err := os.Lstat(path); !os.IsNotExist(err) { + t.Fatalf("stale surface plan published intent at %s: %v", path, err) + } + } + }) + } +} + +func checkRawSurfaceAdd(t *testing.T, id domain.ClientID, mode string) { + t.Helper() + journey, runner, source := rawSurfaceFixture(t, id, mode) + profile := savedJourneyTree(t, runner.profile) + out := journey.run(t, "skills", "add", source, "--skill", "pdf", "--target", string(id), "--scope", "project", "--project-root", runner.project, "--no-ui", "--yes", "--format", "json") + var document map[string]any + if err := json.Unmarshal([]byte(out), &document); err != nil { + t.Fatal(err) + } + binding := savedJourneyBinding(t, journey.state(t), string(id)) + if binding.Verification != domain.VerificationInstalled { + t.Fatalf("real installation not verified: %+v", binding) + } + if mode == "observed" { + want := []string{"skills"} + if id == domain.ClientCopilot { + want = []string{"plugin", "skill"} + } + if !reflect.DeepEqual(runner.calls, want) || binding.Activation != domain.ActivationActive || binding.Authentication != domain.AuthenticationNotRequired || document["readiness"] != "ready" { + t.Fatalf("observed surface lost across public Skills path: calls=%v binding=%+v output=%s", runner.calls, binding, out) + } + } else { + if binding.Activation != domain.ActivationPrepared || document["readiness"] == "ready" { + t.Fatalf("unqualified native evidence promoted: %+v %s", binding, out) + } + expected := 0 + if mode == "false-catalog" { + expected = 1 + } + if len(runner.calls) != expected { + t.Fatalf("unexpected native calls without qualified surface/catalog: %v", runner.calls) + } + } + after := savedJourneyTree(t, runner.profile) + if id == domain.ClientCopilot { + // Explicit add bootstraps the ordinary native-config advisory lock. + // Its exact empty regular file is separate from existing profile bytes. + lock, exists := after["config.json.agentplugins.lock"] + if !exists || !lock.Mode.IsRegular() || lock.Body != "" { + t.Fatalf("unexpected native-config lock: %+v", lock) + } + delete(after, "config.json.agentplugins.lock") + } + if !reflect.DeepEqual(profile, after) { + t.Fatalf("native observation changed original user profile: %s", savedJourneyDifferences(profile, after)) + } + if body, err := os.ReadFile(filepath.Join(runner.project, "foreign.txt")); err != nil || string(body) != "foreign original bytes" { + t.Fatal("foreign project bytes changed", err) + } +} diff --git a/docs/KIRO_MCP_TOOL_APPROVALS.md b/docs/KIRO_MCP_TOOL_APPROVALS.md new file mode 100644 index 0000000000..0818e7fc97 --- /dev/null +++ b/docs/KIRO_MCP_TOOL_APPROVALS.md @@ -0,0 +1,44 @@ +# Kiro: narrowly scoped automatic MCP tool approval + +Kiro already receives automatically installed, UAP-owned user Skills and MCP entries when its native setup is available. A project installation is **Prepared** until Kiro itself establishes workspace trust and discovery. The Kiro permissions system intentionally keeps workspace trust outside the cloned repository; UAP must not forge the `workspaceTrusted` record. + +## One-command approved tools for publisher-declared packages + +A package author who has reviewed the actual safe MCP tool set can add this optional Kiro-specific extension to the standard **plugin.json** (the portable **mcp.json** schema does not permit Kiro's `autoApprove` field): + +```json +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "example-docs", + "version": "1.0.0", + "extensions": { + "com.universal-agent-plugins.kiro-mcp-approval": { + "version": 1, + "mcp_auto_approve": { + "docs": ["read_docs", "find_docs"] + } + } + } +} +``` + +The same package's portable `mcp.json` must declare the **docs** server. The package's source digest includes the approved names. An ordinary `agentplugins add --target kiro` uses the confirmed package selection and projects the exact tool allowlist into **only the selected server's** Kiro-native `autoApprove` array in `~/.kiro/settings/mcp.json` (User) or `.kiro/settings/mcp.json` (Project). No Kiro-native JSON editing by the user is needed for these tools. The plan displays `docs/read_docs, docs/find_docs` before confirmation, with an explicit warning that it is granting per-tool consent. + +The extension is optional. If absent, UAP does not automatically approve any tools. A package cannot set `"*"`, a glob pattern, duplicate tool names, unexpected extension fields, an unselected server, or a foreign extension and receive auto-approval. Tool names are exact, not pattern-based; vendor-level `deny` and `ask` rules retain priority. Never use this to approve tools with privileged writes, sensitive data access, or unreviewed side effects. Safe publication requires the publisher to verify those tool contracts. + +On update/repair, the approval is regenerated from the exact selected and verified package source; a removed server loses its owned approval along with the owned MCP entry. UAP's exact native ownership digest protects user modifications and existing unrelated MCP servers, including their approvals. + +## What this does **not** automate + +**Workspace trust remains a separate Kiro-native decision.** Gated interactive Kiro CLI V3 sessions do not load project Skills or MCP servers until the workspace is trusted, even with an `autoApprove` list. Kiro's `--no-interactive` launches and older V1/V2 sessions are not gated and can load workspace configuration without asking; this does not grant persistent workspace trust. Kiro's documented `--trust-workspace` only skips the prompt for **one CLI invocation**, and does not persist a trust decision or grant IDE trust. There is no documented persistent, headless workspace-trust grant to use for later sessions. UAP does not synthesize the private workspace-roots hash or edit `workspaceTrusted`, grant global all-tools access, obtain credentials, or claim native tool execution without actual authenticated evidence. + +Security references: https://kiro.dev/docs/permissions/ and https://kiro.dev/docs/mcp/configuration/ and https://kiro.dev/docs/mcp/security/. + +## E2E acceptance + +- [ ] Real package schema accepts the new Kiro extension without changing the portable MCP schema. +- [ ] CLI/SDK selected User and Project files contain only exact approved tools; no wildcard. +- [ ] Fresh, unchanged repeat, update, repair, removal, and user-edited/foreign collision cases preserve native receipts and third-party bytes. +- [ ] Native no-auth Linux, macOS and Windows checks pass on one exact SHA; evidence must not equate *prepared* with *runtime verified*. +- [ ] No unrelated client changes, global trust file writes, or automatic elevation through other targets. +- [ ] All review findings addressed; merge only on successful final-HEAD checks. diff --git a/docs/plans/2026-11-21-kiro-owned-trust-e2e.md b/docs/plans/2026-11-21-kiro-owned-trust-e2e.md new file mode 100644 index 0000000000..a17eb6c936 --- /dev/null +++ b/docs/plans/2026-11-21-kiro-owned-trust-e2e.md @@ -0,0 +1,24 @@ +# Kiro — selected installation and native trust (21 Nov 2026) + +## Baseline and goal +Main already contains the Kiro user-scope native Skills/MCP transaction and ACP observer. PR #927 merged and proved a **Prepared**, no-auth Kiro lifecycle. Current Project delivery deliberately remains Prepared because workspace trust, custom-agent selection and native discovery are separate authorities. Open #931 and #1016 are E2E/research, not an automatic-trust implementation. + +One `agentplugins add ... --target kiro` should install selected Kiro components without manual JSON editing, and the confirmed installation plan should supply only the selected package's MCP tool consent where Kiro provides a documented, ownership-safe config. No vendor login, credential acquisition, broad agent shell trust, unrelated client changes, or native trust database hacks. + +## Plan R1: architecture criticism and resolution +**Risk:** a new installer, generic `ClientID == Kiro` branch or second JSON engine violates SOLID/DRY. **Resolution:** keep changes in `clients/kiro`, reuse the existing `shared.ProjectMCPServers`, Kiro exact JSONC mutation, plan ownership digests, native receipts and rollback. A scoped projected-server transform may be required; no new state store or adapter interface. + +## Plan R2: trust/security criticism and resolution +**Risk:** `autoApprove: ["*"]` silently grants every future tool of one server, and writing a workspace trust hash is undocumented. Kiro's official security guidance recommends only individually audited safe MCP tools. **Resolution:** do not add broad wildcard approval, global trust-all, permissions.yaml changes or undocumented workspace trust file writes. Reuse explicitly authored per-server allowlists only when the confirmed plan authorizes them; validate and preserve the selected servers and existing foreign/deny settings. Kiro's documented `--trust-workspace` lasts only one V3 CLI launch (2.34+); it does not persist IDE or later workspace trust. Project delivery must stay Prepared until native trust and discovery can be proven. + +## Plan R3: acceptance criticism and resolution +**Risk:** a green compilation, mocked ACP response, skipped native job or a copied config is not user-ready Kiro. **Resolution:** cover owned User/Project Skills/MCP initial add, exact repeat, safe replacement, repair, remove, idempotency, foreign entries and changed-file rejection; inspect the real native no-auth boundary without presenting a login refusal as callable tool success. Keep working across Linux, macOS and Windows. Require final-HEAD CI, review threads resolved and postmerge evidence before reporting complete. + +## Implementation work +1. Inspect the actual existing Kiro schema and tests, and whether a trustworthy native list of tool names is available. Prefer no production change if configuration already satisfies an approved exact-list case. +2. Add a Kiro-only, least-privilege, confirmed-install path for selected MCP tool approvals if and only if there is a stable native authorization representation. If not available, keep an honest explicit limitation rather than synthesizing trust. +3. Add focused regressions and exact-source E2E evidence; review twice for boundaries and security, then once for lifecycle/results. +4. Draft PR first; publish each commit immediately. Mark ready and merge only when the actual native and mandatory CI gates pass; no unrelated PRs, release or generated changes. + +## Estimates (before implementation) +Production: 60–180 LoC. Tests: 150–350 LoC. Complexity 5/10; reliability target 9/10; confidence 7/10 before real native acceptance. Scope excludes changes to vendor Kiro binaries, user's credentials, and implicit trust of entire workspaces. diff --git a/install/integrationctl/agentplugins/clients/grok/project_skill_inspect.go b/install/integrationctl/agentplugins/clients/grok/project_skill_inspect.go index d8082d5adf..382ad9540f 100644 --- a/install/integrationctl/agentplugins/clients/grok/project_skill_inspect.go +++ b/install/integrationctl/agentplugins/clients/grok/project_skill_inspect.go @@ -91,40 +91,8 @@ func projectSkillRowsObserved(rows []any, proof *projectSkillProof) bool { } func projectSkillEntry(row map[string]any) bool { - fields := []string{"name", "description", "source", "userInvocable"} - if disabled, exists := row["disabled"]; exists { - if _, ok := disabled.(bool); !ok { - return false - } - fields = append(fields, "disabled") - } - // Grok reports unrelated native Skills alongside plugin Skills. - // Keep only the native optional inspect fields and their exact types. - if vendor, present := row["vendor"]; present { - if value, ok := vendor.(string); !ok || value == "" { - return false - } - fields = append(fields, "vendor") - } - if status, present := row["compatibilityStatus"]; present { - if status != "enabled" && status != "disabled" { - return false - } - fields = append(fields, "compatibilityStatus") - } - if collision, present := row["collidesWith"]; present { - if value, ok := collision.(string); !ok || value == "" { - return false - } - fields = append(fields, "collidesWith") - } - if invoked, present := row["invocableAs"]; present { - if value, ok := invoked.(string); !ok || value == "" { - return false - } - fields = append(fields, "invocableAs") - } - if !projectSkillFields(row, fields...) { + fields, valid := projectSkillOptionalFields(row) + if !valid || !projectSkillFields(row, fields...) { return false } if _, ok := row["description"].(string); !ok { @@ -157,6 +125,43 @@ func projectSkillEntry(row map[string]any) bool { } } +func projectSkillOptionalFields(row map[string]any) ([]string, bool) { + fields := []string{"name", "description", "source", "userInvocable"} + if disabled, exists := row["disabled"]; exists { + if _, ok := disabled.(bool); !ok { + return nil, false + } + fields = append(fields, "disabled") + } + // Grok reports unrelated native Skills alongside plugin Skills. + // Keep only the native optional inspect fields and their exact types. + if vendor, present := row["vendor"]; present { + if value, ok := vendor.(string); !ok || value == "" { + return nil, false + } + fields = append(fields, "vendor") + } + if status, present := row["compatibilityStatus"]; present { + if status != "enabled" && status != "disabled" { + return nil, false + } + fields = append(fields, "compatibilityStatus") + } + if collision, present := row["collidesWith"]; present { + if value, ok := collision.(string); !ok || value == "" { + return nil, false + } + fields = append(fields, "collidesWith") + } + if invoked, present := row["invocableAs"]; present { + if value, ok := invoked.(string); !ok || value == "" { + return nil, false + } + fields = append(fields, "invocableAs") + } + return fields, true +} + func projectSkillPluginObserved(document map[string]any, proof *projectSkillProof) bool { rows, ok := document["plugins"].([]any) if !ok { diff --git a/install/integrationctl/agentplugins/clients/kiro/activate.go b/install/integrationctl/agentplugins/clients/kiro/activate.go index 4dbde2466b..1479e47cf8 100644 --- a/install/integrationctl/agentplugins/clients/kiro/activate.go +++ b/install/integrationctl/agentplugins/clients/kiro/activate.go @@ -23,12 +23,12 @@ func (*Adapter) AutomaticallyActivates(_ clients.Env, request domain.ActivationR func automaticallyActivates(request domain.ActivationRequest) bool { if request.Plan.Scope == domain.ScopeProject { - return request.Plan.InstallIntent == domain.InstallIntentAutomatic && shared.OnlyNativeComponents(request.Plan.Components) + return request.Plan.InstallIntent == domain.InstallIntentAutomatic && kiroNativeComponents(request.Plan.Components) } if request.Plan.InstallIntent != domain.InstallIntentAutomatic { return false } - if strings.TrimSpace(request.Client.ConfigRoot) == "" || !shared.OnlyNativeComponents(request.Plan.Components) { + if strings.TrimSpace(request.Client.ConfigRoot) == "" || !kiroNativeComponents(request.Plan.Components) { return false } return !shared.HasSupportedMCP(request.Plan.Components) || @@ -40,23 +40,15 @@ func automaticallyActivates(request domain.ActivationRequest) bool { // that does not look like Kiro cannot prove Kiro state. func (*Adapter) VerifierAvailable(_ domain.DetectedClient, plan domain.DeliveryPlan, backendExecutable string) bool { if plan.Scope == domain.ScopeProject { - return shared.OnlyNativeComponents(plan.Components) + return kiroNativeComponents(plan.Components) } if strings.TrimSpace(backendExecutable) == "" { return false } - if !strings.Contains(strings.ToLower(backendExecutable), "kiro") || len(plan.Components) == 0 { + if !strings.Contains(strings.ToLower(backendExecutable), "kiro") { return false } - for _, component := range plan.Components { - if component.Support == domain.SupportUnsupported { - continue - } - if component.Kind != domain.ComponentSkill && component.Kind != domain.ComponentMCPServer { - return false - } - } - return true + return kiroNativeComponents(plan.Components) } // PreflightActivation rejects a prepare request that cannot own native objects, @@ -66,7 +58,7 @@ func (*Adapter) PreflightActivation(env clients.Env, request domain.ActivationRe return preflightKiroProject(env, request) } if request.Plan.InstallIntent == domain.InstallIntentPrepare { - if request.Plan.Scope != domain.ScopeUser || strings.TrimSpace(request.Client.ConfigRoot) == "" || !shared.OnlyNativeComponents(request.Plan.Components) { + if request.Plan.Scope != domain.ScopeUser || strings.TrimSpace(request.Client.ConfigRoot) == "" || !kiroNativeComponents(request.Plan.Components) { return kiroErrorf("Kiro preparation requires native configuration and supported components") } return nil diff --git a/install/integrationctl/agentplugins/clients/kiro/mcp_approvals.go b/install/integrationctl/agentplugins/clients/kiro/mcp_approvals.go new file mode 100644 index 0000000000..d3a0e09f46 --- /dev/null +++ b/install/integrationctl/agentplugins/clients/kiro/mcp_approvals.go @@ -0,0 +1,223 @@ +package kiro + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + "slices" + "strings" + + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients/shared" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" +) + +// MCPApprovalNamespace is an opt-in, publisher-authored Kiro extension of +// plugin.json. Its exact tool names, not package-selected wildcards, are shown +// during review and projected into Kiro's documented autoApprove setting. +const MCPApprovalNamespace = "com.universal-agent-plugins.kiro-mcp-approval" + +type mcpApprovals struct { + Version int `json:"version"` + Servers map[string][]string `json:"mcp_auto_approve"` +} + +var _ clients.ExtensionInterpreter = (*Adapter)(nil) + +func (*Adapter) InterpretExtension(namespace string, raw json.RawMessage) (domain.SupportLevel, string) { + if namespace != MCPApprovalNamespace { + return domain.SupportUnsupported, "extension_semantics_not_established" + } + if _, err := decodeMCPApprovals(raw); err != nil { + return domain.SupportUnsupported, "kiro_mcp_approval_invalid" + } + return domain.SupportNative, "" +} + +func decodeMCPApprovals(raw json.RawMessage) (mcpApprovals, error) { + var value mcpApprovals + if len(raw) == 0 || len(raw) > 16<<10 { + return value, fmt.Errorf("kiro MCP approval extension exceeds its limit") + } + fields, err := shared.DecodeStrictJSONObject(raw) + if err != nil { + return value, fmt.Errorf("invalid Kiro MCP approval object: %w", err) + } + // encoding/json accepts field names case-insensitively by default. Kiro's + // trust declaration is an exact, versioned contract: refuse aliases. + _, hasServers := fields["mcp_auto_approve"] + if len(fields) != 2 || fields["version"] != json.Number("1") || !hasServers { + return value, fmt.Errorf("kiro MCP approval fields must match the exact v1 schema") + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&value); err != nil { + return value, fmt.Errorf("invalid Kiro MCP approval fields: %w", err) + } + if err := decoder.Decode(new(any)); err != io.EOF { + return value, fmt.Errorf("kiro MCP approval extension must contain one object") + } + if value.Version != 1 || len(value.Servers) == 0 || len(value.Servers) > 32 { + return value, fmt.Errorf("unsupported Kiro MCP approval version or server count") + } + for server, tools := range value.Servers { + if !validKiroApprovalName(server) || len(tools) == 0 || len(tools) > 64 { + return value, fmt.Errorf("invalid Kiro MCP approval server or tool count") + } + seen := map[string]bool{} + for _, tool := range tools { + if !validKiroApprovalName(tool) || seen[tool] { + return value, fmt.Errorf("invalid or duplicate Kiro MCP auto-approved tool for %q", server) + } + seen[tool] = true + } + } + return value, nil +} + +// Kiro's wildcard is intentionally excluded: a package update may expose new +// tools, and a reviewed source cannot authorize their future unknown behavior. +func validKiroApprovalName(value string) bool { + if value == "" || len(value) > 128 { + return false + } + // Trust previews must not permit invisible, bidirectional or markup-like + // names to impersonate a different tool. Native Kiro tool names are ASCII. + for _, r := range value { + if (r < 'a' || r > 'z') && (r < 'A' || r > 'Z') && + (r < '0' || r > '9') && r != '_' && r != '-' && r != '.' { + return false + } + } + return true +} + +func kiroNativeComponents(components []domain.ComponentDecision) bool { + found := false + for _, component := range components { + if component.Support == domain.SupportUnsupported { + continue + } + switch component.Kind { + case domain.ComponentSkill, domain.ComponentMCPServer: + found = true + case domain.ComponentExtension: + if component.Name != MCPApprovalNamespace { + return false + } + default: + return false + } + } + return found +} + +func selectedKiroApprovals(envelope domain.PackageEnvelope, plan domain.DeliveryPlan) (mcpApprovals, error) { + // An unselected MCP cannot receive tool consent. Keep independent Skills + // deliverable, while retaining strict validation when MCP is selected. + if !shared.HasSupportedMCP(plan.Components) { + return mcpApprovals{}, nil + } + raw, exists := envelope.Manifest.Extensions[MCPApprovalNamespace] + if !exists { + return mcpApprovals{}, nil + } + approved, err := decodeMCPApprovals(raw) + if err != nil { + return approved, err + } + extensionSelected := false + for _, component := range plan.Components { + if component.Kind == domain.ComponentExtension && component.Name == MCPApprovalNamespace && + component.Support == domain.SupportNative { + extensionSelected = true + break + } + } + if !extensionSelected { + return approved, fmt.Errorf("kiro tool approvals were not selected by the plan") + } + selected := shared.SupportedMCPNames(plan) + for server := range approved.Servers { + if !slices.Contains(selected, server) { + return approved, fmt.Errorf("kiro approval references an unselected MCP server %q", server) + } + } + return approved, nil +} + +// Only Kiro's generated native projection is changed. Source MCP documents +// stay portable and exact, and the resulting native entry is receipt-owned. +func applyKiroApprovals(root string, approval mcpApprovals) error { + if len(approval.Servers) == 0 { + return nil + } + path := filepath.Join(root, "mcp.json") + body, err := os.ReadFile(path) + if err != nil { + return err + } + document, err := shared.DecodeStrictJSONObject(body) + if err != nil { + return err + } + servers, ok := document["mcpServers"].(map[string]any) + if !ok { + return fmt.Errorf("kiro MCP projection has no servers") + } + for name, tools := range approval.Servers { + server, ok := servers[name].(map[string]any) + if !ok { + return fmt.Errorf("kiro MCP projection lacks approved server %q", name) + } + if _, existing := server["autoApprove"]; existing { + return fmt.Errorf("kiro MCP projection has conflicting approval for %q", name) + } + server["autoApprove"] = tools + } + return shared.WriteJSON(path, document) +} + +// Reconstructing exact native ownership from an unchanged active package must +// not silently accept a stale projection that omitted the publisher's approved +// tools. A caller can re-stage the confirmed source, but never forge a receipt. +func verifyKiroActiveApprovals(root string, envelope domain.PackageEnvelope, plan domain.DeliveryPlan) error { + approved, err := selectedKiroApprovals(envelope, plan) + if err != nil { + return err + } + for name, tools := range approved.Servers { + server, err := projectedKiroMCPServer(root, name) + if err != nil { + return fmt.Errorf("%w: read native Kiro approval for %q: %w", domain.ErrProjectionRefreshRequired, name, err) + } + actual, ok := server["autoApprove"].([]any) + if !ok || len(actual) != len(tools) { + return fmt.Errorf("%w: native Kiro approved tools changed for %q", domain.ErrProjectionRefreshRequired, name) + } + for index, tool := range tools { + if actual[index] != tool { + return fmt.Errorf("%w: native Kiro approved tool changed for %q", domain.ErrProjectionRefreshRequired, name) + } + } + } + return nil +} + +func kiroApprovalDisclosure(approved mcpApprovals) string { + if len(approved.Servers) == 0 { + return "" + } + var entries []string + for name, tools := range approved.Servers { + for _, tool := range tools { + entries = append(entries, name+"/"+tool) + } + } + slices.Sort(entries) + return "Kiro will automatically approve these publisher-declared MCP tools only: " + + strings.Join(entries, ", ") + ". Review the selected source before confirming; workspace trust, higher-priority deny/ask rules and authentication remain separate." +} diff --git a/install/integrationctl/agentplugins/clients/kiro/mcp_approvals_test.go b/install/integrationctl/agentplugins/clients/kiro/mcp_approvals_test.go new file mode 100644 index 0000000000..31b6331a9b --- /dev/null +++ b/install/integrationctl/agentplugins/clients/kiro/mcp_approvals_test.go @@ -0,0 +1,394 @@ +package kiro + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/clients" + "github.com/777genius/plugin-kit-ai/install/integrationctl/agentplugins/domain" +) + +const kiroApprovalTestServer = "docs" + +func testKiroApprovedEnvelope(approvals string) domain.PackageEnvelope { + return domain.PackageEnvelope{ + Manifest: domain.PluginManifest{Extensions: map[string]json.RawMessage{ + MCPApprovalNamespace: json.RawMessage(approvals), + }}, + MCP: domain.MCPComponent{Present: true, Enabled: true, Servers: map[string]domain.MCPServer{ + kiroApprovalTestServer: { + Name: kiroApprovalTestServer, Type: "streamable-http", + Decoded: map[string]any{"type": "streamable-http", "url": "https://docs.example.test/mcp"}, + }, + }}, + } +} + +func testKiroApprovalPlan(root, active string, scope domain.InstallScope) domain.DeliveryPlan { + return domain.DeliveryPlan{ + ClientID: domain.ClientKiro, Scope: scope, + InstallIntent: domain.InstallIntentPrepare, Status: domain.PlanReady, + NativeRegistryRoot: root, ActivePath: active, + Components: []domain.ComponentDecision{ + {Kind: domain.ComponentMCPServer, Name: kiroApprovalTestServer, Support: domain.SupportNative}, + {Kind: domain.ComponentExtension, Name: MCPApprovalNamespace, Support: domain.SupportNative}, + }, + } +} + +func TestKiroNamedMCPApprovalSchemaFailClosed(t *testing.T) { + valid := `{"version":1,"mcp_auto_approve":{"docs":["read_docs","get-library.id"]}}` + for name, raw := range map[string]string{ + "empty": "", + "root": "[]", + "unsupported-version": `{"version":2,"mcp_auto_approve":{"docs":["read"]}}`, + "empty-list": `{"version":1,"mcp_auto_approve":{"docs":[]}}`, + "wildcard": `{"version":1,"mcp_auto_approve":{"docs":["*"]}}`, + "embedded-wildcard": `{"version":1,"mcp_auto_approve":{"docs":["read*"]}}`, + "path": `{"version":1,"mcp_auto_approve":{"docs":["../secret"]}}`, + "duplicate-tool": `{"version":1,"mcp_auto_approve":{"docs":["read","read"]}}`, + "duplicate-server": `{"version":1,"mcp_auto_approve":{"docs":["read"],"docs":["write"]}}`, + "unknown-field": `{"version":1,"mcp_auto_approve":{"docs":["read"]},"all_tools":true}`, + "field-alias": `{"Version":1,"mcp_auto_approve":{"docs":["read"]}}`, + "field-alias-server": `{"version":1,"MCP_AUTO_APPROVE":{"docs":["read"]}}`, + "noncanonical-number": `{"version":1.0,"mcp_auto_approve":{"docs":["read"]}}`, + "wrong-shape": `{"version":1,"mcp_auto_approve":{"docs":"read"}}`, + "null": `{"version":1,"mcp_auto_approve":null}`, + "trailing-content": valid + " {}", + } { + t.Run(name, func(t *testing.T) { + if _, err := decodeMCPApprovals(json.RawMessage(raw)); err == nil { + t.Fatal("accepted an unsafe Kiro tool approval manifest") + } + }) + } + for _, name := range []string{"read docs", "read\u202e", "read\u200b", "read\nwrite", "