diff --git a/changelog.d/added-18490-owner-prompt-source-repos.md b/changelog.d/added-18490-owner-prompt-source-repos.md new file mode 100644 index 0000000000..42b3884520 --- /dev/null +++ b/changelog.d/added-18490-owner-prompt-source-repos.md @@ -0,0 +1 @@ +- **Owners can approve their own managed repos as prompt and definition sources.** Settings → Security → Prompt sources and the owner-only `GET /api/config/prompt-sources` / `PUT /api/config/prompt-sources/owner-repos` let the hive owner allow one of the hive's `project.repos` for `agents..prompt_source` and `definition_source` without editing the config volume, behind a confirm naming the trust implication (whoever can merge there can steer the agents). Approvals cover that repo only, are audit-logged as `config_prompt_source_repo`, persist to `variables.security.owner_github_prompt_repos` in the PVC runtime config, and lapse if the repo leaves `project.repos`. Non-owners get 403, repos outside the hive are refused, and the seed `github_prompt_allowlist` path is unchanged ([#18490](https://github.com/hivecommons/hive/issues/18490)). diff --git a/dashboard/openapi.json b/dashboard/openapi.json index 9e9e2cf90c..04c391deb2 100644 --- a/dashboard/openapi.json +++ b/dashboard/openapi.json @@ -6103,6 +6103,173 @@ } } }, + "/api/config/prompt-sources": { + "get": { + "tags": [ + "System" + ], + "summary": "Get prompt and definition source repos", + "description": "Lists the hive's managed repos and whether agents' prompt_source / definition_source may read from each, via the config-volume allowlist or an owner approval (#18490). Requires owner role.", + "responses": { + "200": { + "description": "Prompt source gate state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": { + "type": "object", + "properties": { + "repo": { + "type": "string" + }, + "managed": { + "type": "boolean" + }, + "owner_approved": { + "type": "boolean" + }, + "seed_allowed": { + "type": "boolean" + }, + "allowed": { + "type": "boolean" + }, + "approved_by": { + "type": "string" + }, + "approved_at": { + "type": "string", + "description": "RFC 3339 time of the owner approval." + } + } + }, + "description": "One row per managed repo (project.repos), then any owner approval whose repo is no longer managed (inert)." + }, + "seed_enabled": { + "type": "boolean", + "description": "variables.security.allow_github_prompt from the config volume." + }, + "seed_allowlist": { + "type": "array", + "items": { + "type": "string" + } + }, + "trust_notice": { + "type": "string" + }, + "seed_only_note": { + "type": "string" + } + } + } + } + } + } + } + } + }, + "/api/config/prompt-sources/owner-repos": { + "put": { + "tags": [ + "System" + ], + "summary": "Approve or revoke a managed repo as a prompt source", + "description": "Approves (allowed: true, with acknowledge_trust: true) or revokes (allowed: false) one of the hive's managed repos as a prompt_source / definition_source repo. A repo outside project.repos, a malformed slug, or an approval without acknowledge_trust is refused with 400 and nothing changes. Persisted to variables.security.owner_github_prompt_repos in the running config and audit-logged. Requires owner role.", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object", + "required": [ + "repo", + "allowed" + ], + "properties": { + "repo": { + "type": "string", + "description": "owner/repo slug of a managed repo." + }, + "allowed": { + "type": "boolean" + }, + "acknowledge_trust": { + "type": "boolean", + "description": "Must be true to approve: anyone who can merge to the repo can steer the hive's agents." + } + } + } + } + } + }, + "responses": { + "200": { + "description": "Updated prompt source gate state", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "repos": { + "type": "array", + "items": { + "type": "object", + "properties": { + "repo": { + "type": "string" + }, + "managed": { + "type": "boolean" + }, + "owner_approved": { + "type": "boolean" + }, + "seed_allowed": { + "type": "boolean" + }, + "allowed": { + "type": "boolean" + }, + "approved_by": { + "type": "string" + }, + "approved_at": { + "type": "string", + "description": "RFC 3339 time of the owner approval." + } + } + }, + "description": "One row per managed repo (project.repos), then any owner approval whose repo is no longer managed (inert)." + }, + "seed_enabled": { + "type": "boolean", + "description": "variables.security.allow_github_prompt from the config volume." + }, + "seed_allowlist": { + "type": "array", + "items": { + "type": "string" + } + }, + "trust_notice": { + "type": "string" + }, + "seed_only_note": { + "type": "string" + } + } + } + } + } + } + } + } + }, "/api/config/reference-repos": { "get": { "tags": [ diff --git a/src/docs/agent-configuration.md b/src/docs/agent-configuration.md index e730be44ed..361979416d 100644 --- a/src/docs/agent-configuration.md +++ b/src/docs/agent-configuration.md @@ -1067,7 +1067,7 @@ Two merge rules to know before you rely on this: ### The trust boundary: allowlisted repos are seed-only -`definition_source` is gated by `Config.GitHubDefinitionAllowed(slug)` (`config.go:4731`), which simply delegates to `Config.GitHubPromptAllowed(slug)` (`config.go:4711`) — the **same** seed-only gate used by `prompt_source`. Fetching requires both: +`definition_source` is gated by `Config.GitHubDefinitionAllowed(slug)` (`config.go:4731`), which simply delegates to `Config.GitHubPromptAllowed(slug)` (`config.go:4711`) — the **same** seed-only gate used by `prompt_source`. On the seed path, fetching requires both (the owner approval for managed repos is [below](#owner-approval-for-the-hives-own-managed-repos)): ```yaml variables: @@ -1085,6 +1085,19 @@ This is the property operators most need to understand before enabling the featu An empty allowlist denies every repo even with `allow_github_prompt: true` — the allowlist is required, not merely advisory. +### Owner approval for the hive's own managed repos + +The seed edit is still the only way to allow a repo outside the hive. For one of the hive's **own managed repos** (an entry of `project.repos`, qualified with `project.org`), the hive owner can approve it from the dashboard instead of editing the volume ([#18490](https://github.com/hivecommons/hive/issues/18490)): + +- **Settings → Security → Prompt sources** lists each managed repo and whether `prompt_source` / `definition_source` may read from it. **Approve…** opens a confirm that names the trust implication: anyone who can merge to that repo can change what the hive's agents are told to do and how they are defined. **Revoke** removes the approval. +- The API is `GET /api/config/prompt-sources` and `PUT /api/config/prompt-sources/owner-repos` with `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` (`"allowed": false` revokes). Both are owner-only: read, read-write and merger sessions get 403. A repo outside `project.repos` is refused with a 400, and an approval without `acknowledge_trust: true` is refused. +- Each approval covers that one repo only. It does not need `allow_github_prompt` and does not turn it on, so nothing on `github_prompt_allowlist` starts loading because of it. +- Approvals are stored in the running config as `variables.security.owner_github_prompt_repos` (`repo`, `approved_by`, `approved_at`), written by the dashboard Save to the PVC runtime config, so they survive a restart. Every change is audit-logged as `config_prompt_source_repo`. +- The dashboard overlay still cannot approve a repo: its `variables` block is never merged, so only the owner endpoint (or a seed edit) writes the list. +- An approval counts only while its repo is still in `project.repos`. Removing the repo from the hive lapses the approval; the Prompt sources panel shows it as inert until it is revoked. + +`Config.GitHubPromptAllowed(slug)` (and `GitHubDefinitionAllowed`, which delegates to it) admits a repo when either the seed gate or an owner approval allows it, so every caller (prompt, definition and review-perspective resolvers) honors both paths without change. + `review.perspectives_source` (the live-linked review perspective set; see [review-swarm.md](review-swarm.md#live-linked-perspectives-reviewperspectives_source)) uses the same seed-only gate: the resolver is allowed to read a repo only when `GitHubPromptAllowed` permits it, it resolves at the same resolve points (startup and every reload), and it follows the same fallback shape as `Resolve` above (last-known-good, then the inline config). ### Fetch failures never blank an agent diff --git a/src/docs/api-reference/configuration.md b/src/docs/api-reference/configuration.md index e30aeeb97d..fe5fc80cd6 100644 --- a/src/docs/api-reference/configuration.md +++ b/src/docs/api-reference/configuration.md @@ -103,6 +103,8 @@ Part of the [Dashboard REST API reference](../api-reference.md); see that page f | `PUT` | `/api/config/write-surface` | Owner only | Replace the lane write allowlist; `{"allowlist": {}}` clears it; unknown operation or bad lane name is a 400 with nothing changed | `pkg/dashboard/api.go:525` | | `GET` | `/api/config/reference-repos` | Owner only | `project.reference_repos` ([#18136](https://github.com/hivecommons/hive/issues/18136)): `reference_repos` (`{repo, write, write_token_file}` plus `derived_from` on a derived entry and, on every write entry, `credential_state`, `credential_reason` and `credential_login`, the GitHub account the writes appear under ([#18197](https://github.com/hivecommons/hive/issues/18197)); always an array) and `write_kinds` | `pkg/dashboard/api.go:551` | | `PUT` | `/api/config/reference-repos` | Owner only | Replace `project.reference_repos`; `{"reference_repos": []}` clears it. Refused with a 400 and nothing changed when the config loader would reject the list (bare name, repo also in `project.repos`, duplicate, unknown write kind, token file without write) or when a write entry has no credential boot would accept — the same message boot exits 22 with — or when an entry carries a `write_token_file` the config file does not already hold for that repo (the path is operator-only; a dashboard write opt-in writes as the hive owner's connected GitHub account). Entries with `derived_from` ([#18139](https://github.com/hivecommons/hive/issues/18139)) are the request issue's grant: echo them back as served; changing one's write set, leaving one out, sending one the hive did not derive or adding a hand-written entry for the same repo is a 409 naming the issue to change instead ([#18161](https://github.com/hivecommons/hive/issues/18161)). They are never stored: the saved list holds the hand-written entries and the derived set is merged back in memory after the save. 500 when the file could not be written (proxy restored, nothing changed). On success the GitHub proxy's reference policies are replaced without a restart; audited as `config_reference_repos` | `pkg/dashboard/api.go:552` | +| `GET` | `/api/config/prompt-sources` | Owner only | Repo-sourced prompt and definition gate ([#18490](https://github.com/hivecommons/hive/issues/18490)): `repos` (one row per managed repo, then any owner approval whose repo is no longer managed, each `{repo, managed, owner_approved, seed_allowed, allowed, approved_by, approved_at}`), `seed_enabled`, `seed_allowlist`, `trust_notice`, `seed_only_note` | `pkg/dashboard/api.go:561` | +| `PUT` | `/api/config/prompt-sources/owner-repos` | Owner only | `{"repo": "org/name", "allowed": true, "acknowledge_trust": true}` approves one of the hive's managed repos as a `prompt_source` / `definition_source` repo; `"allowed": false` revokes. 400 with nothing changed for a repo outside `project.repos` (still needs the seed edit), a malformed slug, or an approval without `acknowledge_trust: true`. Persisted to `variables.security.owner_github_prompt_repos` in the running config; audited as `config_prompt_source_repo`. Responds with the GET body | `pkg/dashboard/api.go:562` | | `GET` | `/api/config/review` | Dashboard auth/session | Review Config Get | `pkg/dashboard/api.go:218` | | `PUT` | `/api/config/review` | Owner only | Review Config Set | `pkg/dashboard/api.go:221` | | `PUT` | `/api/config/governor/features` | Owner only | Governor Features | `pkg/dashboard/api.go:227` | diff --git a/src/hive.yaml.example b/src/hive.yaml.example index bd25839993..343415b840 100644 --- a/src/hive.yaml.example +++ b/src/hive.yaml.example @@ -1097,6 +1097,9 @@ dashboard: # http_allowlist: [] # allow_github_prompt: false # github_prompt_allowlist: [] +# # Owner-approved managed repos, written by Settings -> Security -> Prompt +# # sources (owner-only). Not needed in a hand-written seed. +# owner_github_prompt_repos: [] # defs: # EXAMPLE_TOKEN: # type: env diff --git a/src/pkg/config/config.go b/src/pkg/config/config.go index 5b0950dfe5..454a890283 100644 --- a/src/pkg/config/config.go +++ b/src/pkg/config/config.go @@ -1110,6 +1110,14 @@ type VarSecurityConfig struct { // bounds the blast radius to repos the operator explicitly trusts, so the // feature cannot be used to read every repo the App happens to be installed on. GitHubPromptAllowlist []string `yaml:"github_prompt_allowlist,omitempty"` + // OwnerGitHubPromptRepos is the owner-approved subset of the hive's own + // managed repos that prompt_source and definition_source may read from, + // each approved on its own from the dashboard (hivecommons/hive#18490). + // Unlike GitHubPromptAllowlist it needs no AllowGitHubPrompt, and an entry + // counts only while the repo is still in project.repos. Written only by the + // owner-only dashboard endpoint through Save; the overlay cannot set it. + // See owner_prompt_repos.go. + OwnerGitHubPromptRepos []OwnerPromptRepo `yaml:"owner_github_prompt_repos,omitempty"` } type ProjectConfig struct { @@ -6562,19 +6570,21 @@ func (c *Config) ResolveRegistryForAgent(agentName string, logger *slog.Logger) // given "owner/repo" slug is permitted to be fetched. This mirrors the seed-only // gating used for exec/http resolvers: it consults c.Variables.Security, which // LoadWithDashboardOverlay guarantees comes ONLY from the trusted config seed -// (the dashboard overlay's Variables block is never merged). It returns false -// unless the feature is explicitly enabled AND the slug is on the seed-declared +// (the dashboard overlay's Variables block is never merged). The seed path +// needs the feature explicitly enabled AND the slug on the seed-declared // allowlist, so a user-writable overlay can never widen the set of readable repos. +// +// It also admits a repo the hive owner approved from the dashboard +// (OwnerPromptRepoAllowed, hivecommons/hive#18490): one of the hive's own +// managed repos, approved individually and persisted through Save. That path +// is bounded to project.repos, so it cannot widen the set beyond repos the +// hive already manages. Callers (the prompt, definition and perspectives +// resolvers, and repo-discovered agents) should keep using this function. func (c *Config) GitHubPromptAllowed(slug string) bool { - if slug == "" || !c.Variables.Security.AllowGitHubPrompt { + if slug == "" { return false } - for _, allowed := range c.Variables.Security.GitHubPromptAllowlist { - if strings.EqualFold(strings.TrimSpace(allowed), slug) { - return true - } - } - return false + return c.SeedGitHubPromptAllowed(slug) || c.OwnerPromptRepoAllowed(slug) } // GitHubDefinitionAllowed reports whether an agent's definition_source pointing diff --git a/src/pkg/config/owner_prompt_repos.go b/src/pkg/config/owner_prompt_repos.go new file mode 100644 index 0000000000..91cdaddf44 --- /dev/null +++ b/src/pkg/config/owner_prompt_repos.go @@ -0,0 +1,216 @@ +package config + +import ( + "errors" + "fmt" + "strings" + "sync" + "time" +) + +// Owner-approved prompt and definition repos (hivecommons/hive#18490). +// +// The seed-only gate (variables.security.allow_github_prompt plus +// github_prompt_allowlist) stays exactly as it was. This file adds a second, +// narrower way in: the hive OWNER may approve one of the hive's own managed +// repos (project.org + project.repos) as a source for agents' prompt_source and +// definition_source. Each approval covers that one repo only; it does not turn +// on the seed allowlist, and a repo outside the managed set can never be +// approved this way. +// +// Approvals live in variables.security.owner_github_prompt_repos. Like the rest +// of variables.security they are honored only from the loaded config file (the +// seed, or on a hosted spoke the PVC runtime config the dashboard Save writes); +// the user-writable dashboard overlay's variables block is still never merged, +// so an overlay cannot approve a repo. The only writer is the owner-only +// dashboard endpoint, which persists through Save. + +// OwnerPromptRepo is one owner approval: the repo and who approved it, when. +type OwnerPromptRepo struct { + // Repo is the approved "owner/repo" slug. It must be one of the hive's + // managed repos, both when it is approved and every time it is checked. + Repo string `yaml:"repo" json:"repo"` + // ApprovedBy is the dashboard login that approved the repo (audit only). + ApprovedBy string `yaml:"approved_by,omitempty" json:"approved_by,omitempty"` + // ApprovedAt is the RFC 3339 time of the approval (audit only). + ApprovedAt string `yaml:"approved_at,omitempty" json:"approved_at,omitempty"` +} + +// ErrNotManagedRepo is returned when an owner tries to approve a repo that is +// not one of the hive's managed repos. Such a repo still needs the seed edit. +var ErrNotManagedRepo = errors.New("repo is not one of this hive's managed repos") + +// ownerPromptReposMu guards Variables.Security.OwnerGitHubPromptRepos: the +// prompt and definition resolvers read it from scheduler goroutines while the +// dashboard writes it. Lock order is saveMu then ownerPromptReposMu. +var ownerPromptReposMu sync.RWMutex + +// IsManagedRepo reports whether slug ("owner/repo") is one of the hive's own +// managed repos: an entry of project.repos, qualified with project.org when it +// carries no owner. The match ignores case, as GitHub does. +func (c *Config) IsManagedRepo(slug string) bool { + if c == nil { + return false + } + key := strings.ToLower(strings.TrimSpace(slug)) + if key == "" || !strings.Contains(key, "/") { + return false + } + for _, repo := range c.Project.Repos { + if agentRepoKey(c.Project.Org, repo) == key { + return true + } + } + return false +} + +// ManagedRepoSlugs returns the hive's managed repos as "owner/repo" slugs, in +// project.repos order. +func (c *Config) ManagedRepoSlugs() []string { + if c == nil { + return nil + } + out := make([]string, 0, len(c.Project.Repos)) + for _, repo := range c.Project.Repos { + if slug := qualifyAgentRepo(c.Project.Org, repo); strings.Contains(slug, "/") { + out = append(out, slug) + } + } + return out +} + +// NormalizeOwnerPromptRepo validates slug for an owner approval and returns +// the managed repo's canonical slug. It refuses a malformed slug and any repo +// outside the managed set (wrapping ErrNotManagedRepo). +func (c *Config) NormalizeOwnerPromptRepo(slug string) (string, error) { + slug = strings.TrimSpace(slug) + parts := strings.Split(slug, "/") + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", fmt.Errorf("repo %q must be an \"owner/repo\" slug", slug) + } + if c == nil { + return "", fmt.Errorf("%w: %s", ErrNotManagedRepo, slug) + } + key := strings.ToLower(slug) + for _, managed := range c.ManagedRepoSlugs() { + if strings.ToLower(managed) == key { + return managed, nil + } + } + return "", fmt.Errorf("%w: %s", ErrNotManagedRepo, slug) +} + +// OwnerPromptRepos returns a copy of the owner-approved repos. +func (c *Config) OwnerPromptRepos() []OwnerPromptRepo { + if c == nil { + return nil + } + ownerPromptReposMu.RLock() + defer ownerPromptReposMu.RUnlock() + src := c.Variables.Security.OwnerGitHubPromptRepos + if len(src) == 0 { + return nil + } + return append([]OwnerPromptRepo(nil), src...) +} + +// OwnerPromptRepoAllowed reports whether slug is owner-approved AND still one +// of the hive's managed repos. Removing a repo from project.repos therefore +// revokes its approval without anyone having to remember the allowlist. +func (c *Config) OwnerPromptRepoAllowed(slug string) bool { + if c == nil || strings.TrimSpace(slug) == "" || !c.IsManagedRepo(slug) { + return false + } + ownerPromptReposMu.RLock() + defer ownerPromptReposMu.RUnlock() + return ownerPromptRepoIndex(c.Variables.Security.OwnerGitHubPromptRepos, slug) >= 0 +} + +// ownerPromptRepoIndex returns the index of slug in list (case-insensitive), +// or -1. Callers hold ownerPromptReposMu. +func ownerPromptRepoIndex(list []OwnerPromptRepo, slug string) int { + key := strings.TrimSpace(slug) + for i, e := range list { + if strings.EqualFold(strings.TrimSpace(e.Repo), key) { + return i + } + } + return -1 +} + +// AllowOwnerPromptRepoAndSave approves one managed repo as a prompt and +// definition source and persists the config, under the same saveMu as every +// other saver. A repo outside the managed set is refused before anything +// changes. Returns the stored entry and whether anything changed; approving an +// already-approved repo is a no-op that keeps the original approval record. +func (c *Config) AllowOwnerPromptRepoAndSave(slug, approvedBy string, at time.Time) (OwnerPromptRepo, bool, error) { + repo, err := c.NormalizeOwnerPromptRepo(slug) + if err != nil { + return OwnerPromptRepo{}, false, err + } + saveMu.Lock() + defer saveMu.Unlock() + + ownerPromptReposMu.Lock() + list := c.Variables.Security.OwnerGitHubPromptRepos + if i := ownerPromptRepoIndex(list, repo); i >= 0 { + existing := list[i] + ownerPromptReposMu.Unlock() + return existing, false, nil + } + entry := OwnerPromptRepo{ + Repo: repo, + ApprovedBy: strings.TrimSpace(approvedBy), + ApprovedAt: at.UTC().Format(time.RFC3339), + } + next := make([]OwnerPromptRepo, 0, len(list)+1) + next = append(next, list...) + c.Variables.Security.OwnerGitHubPromptRepos = append(next, entry) + ownerPromptReposMu.Unlock() + + return entry, true, c.saveLocked() +} + +// RevokeOwnerPromptRepoAndSave removes an owner approval and persists the +// config. Revoking is allowed for any slug on the list, managed or not, so an +// approval left behind by a repo dropped from project.repos can be cleaned up. +// Returns whether anything changed. +func (c *Config) RevokeOwnerPromptRepoAndSave(slug string) (bool, error) { + if c == nil { + return false, fmt.Errorf("no config loaded") + } + saveMu.Lock() + defer saveMu.Unlock() + + ownerPromptReposMu.Lock() + list := c.Variables.Security.OwnerGitHubPromptRepos + i := ownerPromptRepoIndex(list, slug) + if i < 0 { + ownerPromptReposMu.Unlock() + return false, nil + } + next := make([]OwnerPromptRepo, 0, len(list)-1) + next = append(next, list[:i]...) + next = append(next, list[i+1:]...) + if len(next) == 0 { + next = nil + } + c.Variables.Security.OwnerGitHubPromptRepos = next + ownerPromptReposMu.Unlock() + + return true, c.saveLocked() +} + +// SeedGitHubPromptAllowed reports whether the SEED gate alone permits slug: +// allow_github_prompt on and slug on github_prompt_allowlist. +func (c *Config) SeedGitHubPromptAllowed(slug string) bool { + if c == nil || slug == "" || !c.Variables.Security.AllowGitHubPrompt { + return false + } + for _, allowed := range c.Variables.Security.GitHubPromptAllowlist { + if strings.EqualFold(strings.TrimSpace(allowed), slug) { + return true + } + } + return false +} diff --git a/src/pkg/config/owner_prompt_repos_test.go b/src/pkg/config/owner_prompt_repos_test.go new file mode 100644 index 0000000000..16cf15d7ba --- /dev/null +++ b/src/pkg/config/owner_prompt_repos_test.go @@ -0,0 +1,238 @@ +package config + +import ( + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func ownerPromptTestConfig() *Config { + return &Config{ + Project: ProjectConfig{Org: "myorg", Repos: []string{"repo1", "Other-Org/shared", " "}}, + } +} + +func TestIsManagedRepo(t *testing.T) { + c := ownerPromptTestConfig() + for slug, want := range map[string]bool{ + "myorg/repo1": true, + "MyOrg/Repo1": true, + " myorg/repo1 ": true, + "other-org/shared": true, + "myorg/shared": false, + "evil/repo1": false, + "repo1": false, + "": false, + } { + if got := c.IsManagedRepo(slug); got != want { + t.Errorf("IsManagedRepo(%q) = %v, want %v", slug, got, want) + } + } + var nilCfg *Config + if nilCfg.IsManagedRepo("myorg/repo1") || nilCfg.ManagedRepoSlugs() != nil || nilCfg.OwnerPromptRepos() != nil || nilCfg.OwnerPromptRepoAllowed("myorg/repo1") || nilCfg.SeedGitHubPromptAllowed("myorg/repo1") { + t.Fatal("nil config must deny everything") + } +} + +func TestManagedRepoSlugs(t *testing.T) { + got := ownerPromptTestConfig().ManagedRepoSlugs() + if strings.Join(got, ",") != "myorg/repo1,Other-Org/shared" { + t.Fatalf("ManagedRepoSlugs = %v", got) + } + noOrg := &Config{Project: ProjectConfig{Repos: []string{"bare", "a/b"}}} + if got := noOrg.ManagedRepoSlugs(); strings.Join(got, ",") != "a/b" { + t.Fatalf("a bare repo with no org is not a slug: %v", got) + } +} + +func TestNormalizeOwnerPromptRepo(t *testing.T) { + c := ownerPromptTestConfig() + if got, err := c.NormalizeOwnerPromptRepo(" MYORG/REPO1 "); err != nil || got != "myorg/repo1" { + t.Fatalf("managed repo: got %q, %v", got, err) + } + if _, err := c.NormalizeOwnerPromptRepo("evil/repo"); !errors.Is(err, ErrNotManagedRepo) { + t.Fatalf("non-managed repo: err = %v, want ErrNotManagedRepo", err) + } + for _, bad := range []string{"", "repo1", "a/b/c", "/repo", "org/"} { + if _, err := c.NormalizeOwnerPromptRepo(bad); err == nil || errors.Is(err, ErrNotManagedRepo) { + t.Fatalf("malformed %q: err = %v, want a slug error", bad, err) + } + } + var nilCfg *Config + if _, err := nilCfg.NormalizeOwnerPromptRepo("a/b"); !errors.Is(err, ErrNotManagedRepo) { + t.Fatalf("nil config: err = %v", err) + } +} + +func TestGitHubPromptAllowedOwnerPath(t *testing.T) { + c := ownerPromptTestConfig() + c.Variables.Security.OwnerGitHubPromptRepos = []OwnerPromptRepo{{Repo: "myorg/repo1"}, {Repo: "evil/repo"}} + c.Variables.Security.GitHubPromptAllowlist = []string{"seed/defs"} + + // Owner approval works without allow_github_prompt, for that repo only. + if !c.GitHubPromptAllowed("myorg/repo1") || !c.GitHubDefinitionAllowed("MYORG/repo1") { + t.Fatal("owner-approved managed repo must be allowed") + } + if c.GitHubPromptAllowed("seed/defs") { + t.Fatal("an owner approval must not switch the seed allowlist on") + } + // An approval for a repo outside project.repos never counts. + if c.GitHubPromptAllowed("evil/repo") { + t.Fatal("owner entry for a non-managed repo must be inert") + } + // Dropping the repo from project.repos revokes it. + c.Project.Repos = []string{"other"} + if c.GitHubPromptAllowed("myorg/repo1") { + t.Fatal("approval must lapse when the repo is no longer managed") + } + if c.GitHubPromptAllowed("") { + t.Fatal("empty slug must be denied") + } + + // The seed path is unchanged. + c.Variables.Security.AllowGitHubPrompt = true + if !c.GitHubPromptAllowed("seed/defs") || !c.SeedGitHubPromptAllowed("Seed/Defs") { + t.Fatal("seed allowlist must still work") + } + if c.SeedGitHubPromptAllowed("") { + t.Fatal("empty slug must be denied by the seed gate") + } +} + +func redirectPVCFiles(t *testing.T, dir string) { + t.Helper() + origRuntime, origOverlay := RuntimeConfigFile, DashboardOverlayFile + RuntimeConfigFile = filepath.Join(dir, "hive.yaml.runtime") + DashboardOverlayFile = filepath.Join(dir, "hive.yaml.dashboard") + t.Cleanup(func() { RuntimeConfigFile, DashboardOverlayFile = origRuntime, origOverlay }) +} + +const ownerPromptSeed = ` +project: + org: testorg + repos: [repo1, repo2] +github: + token: ghp_x +agents: + scanner: + backend: copilot +` + +func TestOwnerPromptRepoPersistsAcrossReload(t *testing.T) { + dir := t.TempDir() + redirectPVCFiles(t, dir) + seedPath := filepath.Join(dir, "hive.yaml") + if err := os.WriteFile(seedPath, []byte(ownerPromptSeed), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := Load(seedPath) + if err != nil { + t.Fatalf("Load: %v", err) + } + if cfg.GitHubPromptAllowed("testorg/repo1") { + t.Fatal("nothing approved yet") + } + + at := time.Date(2026, 11, 16, 12, 0, 0, 0, time.UTC) + entry, changed, err := cfg.AllowOwnerPromptRepoAndSave("TestOrg/Repo1", "alice", at) + if err != nil || !changed { + t.Fatalf("approve: changed=%v err=%v", changed, err) + } + if entry.Repo != "testorg/repo1" || entry.ApprovedBy != "alice" || entry.ApprovedAt != "2026-11-16T12:00:00Z" { + t.Fatalf("entry = %+v", entry) + } + // Re-approving is a no-op that keeps the first record. + again, changed, err := cfg.AllowOwnerPromptRepoAndSave("testorg/repo1", "bob", at.Add(time.Hour)) + if err != nil || changed || again.ApprovedBy != "alice" { + t.Fatalf("re-approve: %+v changed=%v err=%v", again, changed, err) + } + // A non-managed repo is refused and nothing changes. + if _, changed, err := cfg.AllowOwnerPromptRepoAndSave("evil/repo", "alice", at); !errors.Is(err, ErrNotManagedRepo) || changed { + t.Fatalf("non-managed: changed=%v err=%v", changed, err) + } + + for _, p := range []string{seedPath, RuntimeConfigFile} { + data, err := os.ReadFile(p) + if err != nil { + t.Fatalf("read %s: %v", p, err) + } + if !strings.Contains(string(data), "owner_github_prompt_repos") { + t.Fatalf("%s does not carry the approval:\n%s", p, data) + } + } + + reloaded, err := Load(seedPath) + if err != nil { + t.Fatalf("reload: %v", err) + } + if !reloaded.GitHubPromptAllowed("testorg/repo1") || reloaded.GitHubPromptAllowed("testorg/repo2") { + t.Fatalf("after reload: %+v", reloaded.OwnerPromptRepos()) + } + if got := reloaded.OwnerPromptRepos(); len(got) != 1 || got[0].ApprovedBy != "alice" { + t.Fatalf("reloaded approvals = %+v", got) + } + + // Revoke persists too. + if changed, err := reloaded.RevokeOwnerPromptRepoAndSave("TESTORG/repo1"); err != nil || !changed { + t.Fatalf("revoke: changed=%v err=%v", changed, err) + } + if changed, err := reloaded.RevokeOwnerPromptRepoAndSave("testorg/repo1"); err != nil || changed { + t.Fatalf("second revoke: changed=%v err=%v", changed, err) + } + again2, err := Load(seedPath) + if err != nil { + t.Fatalf("reload after revoke: %v", err) + } + if again2.GitHubPromptAllowed("testorg/repo1") || len(again2.OwnerPromptRepos()) != 0 { + t.Fatal("revoke did not survive reload") + } +} + +func TestRevokeOwnerPromptRepoKeepsOthers(t *testing.T) { + c := ownerPromptTestConfig() + c.Variables.Security.OwnerGitHubPromptRepos = []OwnerPromptRepo{{Repo: "a/one"}, {Repo: "myorg/repo1"}, {Repo: "b/two"}} + // No source path: the in-memory change happens and the save error is returned. + changed, err := c.RevokeOwnerPromptRepoAndSave("myorg/repo1") + if !changed || err == nil { + t.Fatalf("changed=%v err=%v, want change plus a no-source-path error", changed, err) + } + got := c.OwnerPromptRepos() + if len(got) != 2 || got[0].Repo != "a/one" || got[1].Repo != "b/two" { + t.Fatalf("remaining = %+v", got) + } + var nilCfg *Config + if _, err := nilCfg.RevokeOwnerPromptRepoAndSave("a/b"); err == nil { + t.Fatal("nil config revoke must error") + } +} + +// TestOwnerPromptRepoOverlayCannotApprove keeps the seed-only invariant: the +// user-writable dashboard overlay cannot approve a repo. +func TestOwnerPromptRepoOverlayCannotApprove(t *testing.T) { + dir := t.TempDir() + redirectPVCFiles(t, dir) + seedPath := filepath.Join(dir, "hive.yaml") + if err := os.WriteFile(seedPath, []byte(ownerPromptSeed), 0o644); err != nil { + t.Fatal(err) + } + overlay := ownerPromptSeed + ` +variables: + security: + owner_github_prompt_repos: + - repo: testorg/repo1 +` + if err := os.WriteFile(DashboardOverlayFile, []byte(overlay), 0o600); err != nil { + t.Fatal(err) + } + t.Setenv("KUBERNETES_SERVICE_HOST", "10.0.0.1") + cfg, err := LoadWithDashboardOverlay(seedPath) + if err != nil { + t.Fatalf("LoadWithDashboardOverlay: %v", err) + } + if cfg.GitHubPromptAllowed("testorg/repo1") { + t.Fatal("the dashboard overlay must not be able to approve a prompt source repo") + } +} diff --git a/src/pkg/config/testdata/agent_runtime_golden.json b/src/pkg/config/testdata/agent_runtime_golden.json index ac2e1ecd62..1ecf118998 100644 --- a/src/pkg/config/testdata/agent_runtime_golden.json +++ b/src/pkg/config/testdata/agent_runtime_golden.json @@ -688,7 +688,8 @@ "ExecTimeoutS": 0, "HTTPTimeoutS": 0, "AllowGitHubPrompt": false, - "GitHubPromptAllowlist": null + "GitHubPromptAllowlist": null, + "OwnerGitHubPromptRepos": null }, "Defs": null }, diff --git a/src/pkg/dashboard/api.go b/src/pkg/dashboard/api.go index 4f15bfc25b..000b2b8d2a 100644 --- a/src/pkg/dashboard/api.go +++ b/src/pkg/dashboard/api.go @@ -556,6 +556,10 @@ func (s *Server) RegisterAPI(deps *Dependencies) { s.mux.HandleFunc("POST /api/github-owner-identity/start", s.handleOwnerIdentityStart) s.mux.HandleFunc("POST /api/github-owner-identity/poll", s.handleOwnerIdentityPoll) s.mux.HandleFunc("DELETE /api/github-owner-identity", s.handleOwnerIdentityDelete) + // Owner-approved prompt/definition source repos (#18490, + // api_config_prompt_sources.go). + s.mux.HandleFunc("GET /api/config/prompt-sources", s.handlePromptSourcesGet) + s.mux.HandleFunc("PUT /api/config/prompt-sources/owner-repos", s.handlePromptSourcesOwnerRepoPut) } var ( diff --git a/src/pkg/dashboard/api_agents.go b/src/pkg/dashboard/api_agents.go index 504a340a04..8e2cc1433a 100644 --- a/src/pkg/dashboard/api_agents.go +++ b/src/pkg/dashboard/api_agents.go @@ -438,7 +438,7 @@ func (s *Server) handleAgentImport(w http.ResponseWriter, r *http.Request) { return } if !s.deps.Config.GitHubDefinitionAllowed(defSrc.Slug()) { - jsonError(w, fmt.Sprintf("keep linked: repo %q is not on the GitHub definition allowlist (an operator must add it to the seed config's variables.security.github_prompt_allowlist and set allow_github_prompt)", defSrc.Slug()), http.StatusBadRequest) + jsonError(w, fmt.Sprintf("keep linked: repo %q is not on the GitHub definition allowlist (an operator must add it to the seed config's variables.security.github_prompt_allowlist and set allow_github_prompt; for one of this hive's managed repos the owner can approve it under Settings → Security → Prompt sources)", defSrc.Slug()), http.StatusBadRequest) return } agentCfg.DefinitionSource = defSrc @@ -524,7 +524,7 @@ func (s *Server) bakePromptSource(ctx context.Context, name string, agent *confi slug := agent.PromptSource.Slug() allow := func(sl string) bool { return s.deps.Config.GitHubPromptAllowed(sl) } if !allow(slug) { - return fmt.Errorf("repo %q is not on the GitHub prompt allowlist (an operator must add it to the seed config's variables.security.github_prompt_allowlist and set allow_github_prompt)", slug) + return fmt.Errorf("repo %q is not on the GitHub prompt allowlist (an operator must add it to the seed config's variables.security.github_prompt_allowlist and set allow_github_prompt; for one of this hive's managed repos the owner can approve it under Settings → Security → Prompt sources)", slug) } src := promptsrc.Source{ Owner: agent.PromptSource.Owner, diff --git a/src/pkg/dashboard/api_config_prompt_sources.go b/src/pkg/dashboard/api_config_prompt_sources.go new file mode 100644 index 0000000000..a4af447ae7 --- /dev/null +++ b/src/pkg/dashboard/api_config_prompt_sources.go @@ -0,0 +1,191 @@ +package dashboard + +import ( + "errors" + "net/http" + "strings" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +// Owner-approved prompt and definition source repos (hivecommons/hive#18490). +// +// An agent's prompt_source and definition_source read text from a GitHub repo +// and run it as the agent's instructions, so whoever can merge to that repo can +// steer the agent. The seed allowlist (allow_github_prompt plus +// github_prompt_allowlist) is still edited on the config volume only. These +// endpoints add the owner approval step for the hive's OWN managed repos: +// +// GET /api/config/prompt-sources +// PUT /api/config/prompt-sources/owner-repos {"repo": "org/name", "allowed": true, "acknowledge_trust": true} +// +// Both are owner-only (403 otherwise). A repo outside project.repos is refused; +// it still needs the seed edit. Approving requires acknowledge_trust: true, +// the API form of the dashboard's confirm dialog. Each change is audit-logged +// and persisted through Save into the running config on the PVC, as +// variables.security.owner_github_prompt_repos[].repo with +// variables.security.owner_github_prompt_repos[].approved_by and +// variables.security.owner_github_prompt_repos[].approved_at recording the +// approval. + +// promptSourceTrustNotice is the trust implication the confirm names, returned +// by GET so the dashboard and API clients show the same words. +const promptSourceTrustNotice = "Anyone who can merge to this repo can change what this hive's agents are told to do and how they are defined. Approve only a repo whose merge rights you trust as much as owner access to this hive." + +// promptSourceAuditAction is the audit action for owner approvals and revokes. +const promptSourceAuditAction = "config_prompt_source_repo" + +type promptSourceRepoRow struct { + Repo string `json:"repo"` + Managed bool `json:"managed"` + Owner bool `json:"owner_approved"` + Seed bool `json:"seed_allowed"` + Allowed bool `json:"allowed"` + ApprovedBy string `json:"approved_by,omitempty"` + ApprovedAt string `json:"approved_at,omitempty"` +} + +type promptSourcesResponse struct { + Repos []promptSourceRepoRow `json:"repos"` + SeedEnabled bool `json:"seed_enabled"` + SeedAllowlist []string `json:"seed_allowlist"` + TrustNotice string `json:"trust_notice"` + SeedOnlyNote string `json:"seed_only_note"` +} + +// promptSourcesSeedOnlyNote explains how a repo outside the managed set is +// allowed: the seed edit, unchanged by #18490. +const promptSourcesSeedOnlyNote = "Repos outside this hive's managed repos can only be allowed by editing the config volume (allow_github_prompt and github_prompt_allowlist)." + +func (s *Server) handlePromptSourcesGet(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s == nil || s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + jsonResponse(w, promptSourcesSection(s.deps.Config)) +} + +func (s *Server) handlePromptSourcesOwnerRepoPut(w http.ResponseWriter, r *http.Request) { + if !requireOwnerRole(w, r) { + return + } + if s == nil || s.deps == nil || s.deps.Config == nil { + jsonError(w, "config unavailable", http.StatusServiceUnavailable) + return + } + var body struct { + Repo string `json:"repo"` + Allowed *bool `json:"allowed"` + AcknowledgeTrust bool `json:"acknowledge_trust"` + } + if err := decodeBody(r, &body); err != nil { + jsonError(w, "invalid body", http.StatusBadRequest) + return + } + if strings.TrimSpace(body.Repo) == "" || body.Allowed == nil { + jsonError(w, `repo and allowed are required, e.g. {"repo": "org/name", "allowed": true, "acknowledge_trust": true}`, http.StatusBadRequest) + return + } + cfg := s.deps.Config + user := requestUser(r) + + if !*body.Allowed { + if s.deps.SkipReloadFunc != nil { + s.deps.SkipReloadFunc() + } + changed, err := cfg.RevokeOwnerPromptRepoAndSave(body.Repo) + if err != nil && s.logger != nil { + s.logger.Error("failed to persist config after prompt source revoke", "repo", body.Repo, "error", err) + } + if changed { + s.auditFromRequest(r, promptSourceAuditAction, auditDetail("repo", strings.TrimSpace(body.Repo), "allowed", "false"), "") + } + jsonResponse(w, promptSourcesSection(cfg)) + return + } + + // --- validate before mutating anything --- + repo, err := cfg.NormalizeOwnerPromptRepo(body.Repo) + if err != nil { + msg := err.Error() + if errors.Is(err, config.ErrNotManagedRepo) { + msg += ". " + promptSourcesSeedOnlyNote + } + jsonError(w, msg, http.StatusBadRequest) + return + } + if !body.AcknowledgeTrust { + jsonError(w, "acknowledge_trust must be true to approve "+repo+": "+promptSourceTrustNotice, http.StatusBadRequest) + return + } + + // --- apply --- + if s.deps.SkipReloadFunc != nil { + s.deps.SkipReloadFunc() + } + _, changed, err := cfg.AllowOwnerPromptRepoAndSave(repo, user, time.Now()) + if err != nil && s.logger != nil { + s.logger.Error("failed to persist config after prompt source approval", "repo", repo, "error", err) + } + if changed { + s.auditFromRequest(r, promptSourceAuditAction, auditDetail("repo", repo, "allowed", "true"), "") + if s.logger != nil { + s.logger.Info("owner approved repo as prompt/definition source", "repo", repo, "user", user) + } + } + jsonResponse(w, promptSourcesSection(cfg)) +} + +// promptSourcesSection lists every managed repo with its gate state, then any +// owner approval whose repo is no longer managed (inert, but revocable). +func promptSourcesSection(cfg *config.Config) promptSourcesResponse { + owner := cfg.OwnerPromptRepos() + byRepo := make(map[string]config.OwnerPromptRepo, len(owner)) + for _, e := range owner { + byRepo[strings.ToLower(e.Repo)] = e + } + rows := []promptSourceRepoRow{} + seen := map[string]bool{} + for _, slug := range cfg.ManagedRepoSlugs() { + key := strings.ToLower(slug) + if seen[key] { + continue + } + seen[key] = true + e, ok := byRepo[key] + rows = append(rows, promptSourceRepoRow{ + Repo: slug, + Managed: true, + Owner: ok, + Seed: cfg.SeedGitHubPromptAllowed(slug), + Allowed: cfg.GitHubPromptAllowed(slug), + ApprovedBy: e.ApprovedBy, + ApprovedAt: e.ApprovedAt, + }) + } + for _, e := range owner { + if seen[strings.ToLower(e.Repo)] { + continue + } + rows = append(rows, promptSourceRepoRow{ + Repo: e.Repo, + Owner: true, + Seed: cfg.SeedGitHubPromptAllowed(e.Repo), + Allowed: cfg.GitHubPromptAllowed(e.Repo), + ApprovedBy: e.ApprovedBy, + ApprovedAt: e.ApprovedAt, + }) + } + seedList := append([]string{}, cfg.Variables.Security.GitHubPromptAllowlist...) + return promptSourcesResponse{ + Repos: rows, + SeedEnabled: cfg.Variables.Security.AllowGitHubPrompt, + SeedAllowlist: seedList, + TrustNotice: promptSourceTrustNotice, + SeedOnlyNote: promptSourcesSeedOnlyNote, + } +} diff --git a/src/pkg/dashboard/api_config_prompt_sources_test.go b/src/pkg/dashboard/api_config_prompt_sources_test.go new file mode 100644 index 0000000000..af413b04f5 --- /dev/null +++ b/src/pkg/dashboard/api_config_prompt_sources_test.go @@ -0,0 +1,215 @@ +package dashboard + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/hivecommons/hive/pkg/config" +) + +const ( + promptSourcesPath = "/api/config/prompt-sources" + promptSourcesOwnerRepoPut = "/api/config/prompt-sources/owner-repos" +) + +func doPromptSourcesAs(s *Server, method, path, role string, body any) *httptest.ResponseRecorder { + var b bytes.Buffer + if body != nil { + _ = json.NewEncoder(&b).Encode(body) + } + req := httptest.NewRequest(method, path, &b) + req.Header.Set("Content-Type", "application/json") + if role == config.RoleOwner { + markOwnerRequest(req) + } else if role != "" { + req.Header.Set("X-Hive-Role", role) + } + req.Header.Set("X-Hive-User", "alice") + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + return rec +} + +func decodePromptSources(t *testing.T, rec *httptest.ResponseRecorder) promptSourcesResponse { + t.Helper() + var out promptSourcesResponse + if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil { + t.Fatalf("decode: %v (%s)", err, rec.Body.String()) + } + return out +} + +func TestPromptSourcesNonOwnersForbidden(t *testing.T) { + s := covApiServer(t) + body := map[string]any{"repo": "myorg/repo1", "allowed": true, "acknowledge_trust": true} + for _, role := range []string{config.RoleRead, config.RoleReadWrite, config.RoleMerger, ""} { + if rec := doPromptSourcesAs(s, http.MethodGet, promptSourcesPath, role, nil); rec.Code != http.StatusForbidden { + t.Fatalf("GET as %q: status %d, want 403", role, rec.Code) + } + if rec := doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, role, body); rec.Code != http.StatusForbidden { + t.Fatalf("PUT as %q: status %d, want 403", role, rec.Code) + } + } + // An unverified owner header is not enough. + req := httptest.NewRequest(http.MethodPut, promptSourcesOwnerRepoPut, strings.NewReader(`{"repo":"myorg/repo1","allowed":true,"acknowledge_trust":true}`)) + req.Header.Set("X-Hive-Role", config.RoleOwner) + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + if rec.Code != http.StatusForbidden { + t.Fatalf("unverified owner: status %d, want 403", rec.Code) + } + if s.deps.Config.GitHubPromptAllowed("myorg/repo1") { + t.Fatal("a refused request must not approve the repo") + } +} + +func TestPromptSourcesOwnerApproveAndRevoke(t *testing.T) { + s := covApiServer(t) + cfg := s.deps.Config + skipped := 0 + s.deps.SkipReloadFunc = func() { skipped++ } + + rec := doPromptSourcesAs(s, http.MethodGet, promptSourcesPath, config.RoleOwner, nil) + if rec.Code != http.StatusOK { + t.Fatalf("GET: %d %s", rec.Code, rec.Body.String()) + } + got := decodePromptSources(t, rec) + if len(got.Repos) != 1 || got.Repos[0].Repo != "myorg/repo1" || !got.Repos[0].Managed || got.Repos[0].Allowed { + t.Fatalf("initial repos = %+v", got.Repos) + } + if got.TrustNotice == "" || got.SeedOnlyNote == "" || got.SeedAllowlist == nil { + t.Fatalf("response missing notices: %+v", got) + } + + // Approval without the acknowledgement is refused. + rec = doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "myorg/repo1", "allowed": true}) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "acknowledge_trust") { + t.Fatalf("no ack: %d %s", rec.Code, rec.Body.String()) + } + if cfg.GitHubPromptAllowed("myorg/repo1") { + t.Fatal("unacknowledged approval must not apply") + } + + rec = doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "MyOrg/Repo1", "allowed": true, "acknowledge_trust": true}) + if rec.Code != http.StatusOK { + t.Fatalf("approve: %d %s", rec.Code, rec.Body.String()) + } + got = decodePromptSources(t, rec) + if row := got.Repos[0]; !row.Allowed || !row.Owner || row.ApprovedBy != "alice" || row.ApprovedAt == "" { + t.Fatalf("approved row = %+v", row) + } + if !cfg.GitHubPromptAllowed("myorg/repo1") || !cfg.GitHubDefinitionAllowed("myorg/repo1") { + t.Fatal("approval must open both prompt and definition gates") + } + if cfg.Variables.Security.AllowGitHubPrompt { + t.Fatal("approval must not flip the seed-wide flag") + } + if skipped == 0 { + t.Fatal("approval must skip the next watcher reload") + } + entries := s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), promptSourceAuditAction) + if len(entries) != 1 || !strings.Contains(entries[0].Detail, "myorg/repo1") || !strings.Contains(entries[0].Detail, "true") { + t.Fatalf("approval audit = %+v", entries) + } + + // Approving again changes nothing and is not re-audited. + if rec := doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "myorg/repo1", "allowed": true, "acknowledge_trust": true}); rec.Code != http.StatusOK { + t.Fatalf("re-approve: %d", rec.Code) + } + if n := len(s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), promptSourceAuditAction)); n != 1 { + t.Fatalf("re-approve audited: %d entries", n) + } + + // Revoke. + rec = doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "myorg/repo1", "allowed": false}) + if rec.Code != http.StatusOK { + t.Fatalf("revoke: %d %s", rec.Code, rec.Body.String()) + } + if cfg.GitHubPromptAllowed("myorg/repo1") { + t.Fatal("revoke must close the gate") + } + if n := len(s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), promptSourceAuditAction)); n != 2 { + t.Fatalf("revoke not audited: %d entries", n) + } + // Revoking a repo that is not approved is a quiet no-op. + if rec := doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "myorg/repo1", "allowed": false}); rec.Code != http.StatusOK { + t.Fatalf("second revoke: %d", rec.Code) + } + if n := len(s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), promptSourceAuditAction)); n != 2 { + t.Fatalf("no-op revoke audited: %d entries", n) + } +} + +func TestPromptSourcesRefusesNonManagedAndBadBodies(t *testing.T) { + s := covApiServer(t) + rec := doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "evil/prompts", "allowed": true, "acknowledge_trust": true}) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "config volume") { + t.Fatalf("non-managed: %d %s", rec.Code, rec.Body.String()) + } + if s.deps.Config.GitHubPromptAllowed("evil/prompts") || len(s.deps.Config.OwnerPromptRepos()) != 0 { + t.Fatal("non-managed repo must not be approved") + } + for name, raw := range map[string]string{ + "malformed": "{nope", + "no repo": `{"allowed":true,"acknowledge_trust":true}`, + "no allowed": `{"repo":"myorg/repo1","acknowledge_trust":true}`, + "bad slug": `{"repo":"repo1","allowed":true,"acknowledge_trust":true}`, + "blank repo": `{"repo":" ","allowed":false}`, + "nested slug": `{"repo":"a/b/c","allowed":true,"acknowledge_trust":true}`, + } { + t.Run(name, func(t *testing.T) { + req := httptest.NewRequest(http.MethodPut, promptSourcesOwnerRepoPut, strings.NewReader(raw)) + markOwnerRequest(req) + rec := httptest.NewRecorder() + s.mux.ServeHTTP(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("status %d, want 400 (%s)", rec.Code, rec.Body.String()) + } + }) + } + if n := len(s.audit.RecentWithPrefixSince(time.Now().Add(-time.Minute), promptSourceAuditAction)); n != 0 { + t.Fatalf("refused requests audited: %d", n) + } +} + +func TestPromptSourcesSectionShowsSeedAndInertApprovals(t *testing.T) { + cfg := &config.Config{Project: config.ProjectConfig{Org: "myorg", Repos: []string{"repo1", "MyOrg/repo1", "repo2"}}} + cfg.Variables.Security.AllowGitHubPrompt = true + cfg.Variables.Security.GitHubPromptAllowlist = []string{"myorg/repo2"} + cfg.Variables.Security.OwnerGitHubPromptRepos = []config.OwnerPromptRepo{ + {Repo: "myorg/repo1", ApprovedBy: "alice", ApprovedAt: "2026-11-16T00:00:00Z"}, + {Repo: "gone/repo", ApprovedBy: "bob"}, + } + got := promptSourcesSection(cfg) + if len(got.Repos) != 3 { + t.Fatalf("rows = %+v", got.Repos) + } + if r := got.Repos[0]; r.Repo != "myorg/repo1" || !r.Owner || !r.Allowed || r.ApprovedBy != "alice" { + t.Fatalf("owner row = %+v", r) + } + if r := got.Repos[1]; r.Repo != "myorg/repo2" || !r.Seed || !r.Allowed || r.Owner { + t.Fatalf("seed row = %+v", r) + } + if r := got.Repos[2]; r.Repo != "gone/repo" || r.Managed || !r.Owner || r.Allowed { + t.Fatalf("inert row = %+v", r) + } + if !got.SeedEnabled || len(got.SeedAllowlist) != 1 { + t.Fatalf("seed fields = %+v", got) + } +} + +func TestPromptSourcesConfigUnavailable(t *testing.T) { + s := covApiServer(t) + s.deps.Config = nil + if rec := doPromptSourcesAs(s, http.MethodGet, promptSourcesPath, config.RoleOwner, nil); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("GET: %d", rec.Code) + } + if rec := doPromptSourcesAs(s, http.MethodPut, promptSourcesOwnerRepoPut, config.RoleOwner, map[string]any{"repo": "a/b", "allowed": true}); rec.Code != http.StatusServiceUnavailable { + t.Fatalf("PUT: %d", rec.Code) + } +} diff --git a/src/pkg/dashboard/static-src/js/config-watchdog-security.js b/src/pkg/dashboard/static-src/js/config-watchdog-security.js index f8cb3e1d36..f542d0e2f4 100644 --- a/src/pkg/dashboard/static-src/js/config-watchdog-security.js +++ b/src/pkg/dashboard/static-src/js/config-watchdog-security.js @@ -1007,6 +1007,13 @@ const writeSurface = `
Loading…
`; + /* Prompt sources (#18490): owner approval of the hive's own managed + repos for prompt_source / definition_source, from its own + owner-only endpoint. */ + loadPromptSourcesPanel(); + const promptSources = ` +
Loading…
`; + /* Suspicious Activity (sentinel): flags PRs that look like security overrides, privilege escalation or codebase damage. Untrusted authors get the blocking alert label; trusted authors default to notice-only. */ @@ -1060,6 +1067,7 @@ ${renderSecuritySection('Suspicious Activity', suspicious + suspiciousFindings)} ${renderSecuritySection('Isolation', isolation)} ${renderSecuritySection('Write Surface', writeSurface)} + ${renderSecuritySection('Prompt sources', promptSources)} ${renderSecuritySection('GitHub App permissions', securityCapabilitiesHtml((window._lastStatus || {}).capabilities, (window._lastStatus || {}).githubAppInstallURL))} ${renderSecuritySection('Backup', backupKey)}`; } @@ -1187,6 +1195,96 @@ }); } + /* Prompt sources (#18490): lists the hive's managed repos and whether an + agent's prompt_source / definition_source may read from each. The owner + approves one repo at a time behind a confirm that names the trust + implication; the server refuses repos outside project.repos, audits + the change and persists it to the running config. Rendered with DOM + nodes and textContent only. */ + async function loadPromptSourcesPanel() { + let host = null; + try { + const r = await fetch('/api/config/prompt-sources'); + host = document.getElementById('gov-prompt-sources-host'); + if (!host) return; + if (r.status === 403) { + host.textContent = ''; + host.appendChild(writeSurfaceNode('div', 'color:var(--muted);font-size:0.8rem', + 'Only the hive owner can approve repos as prompt and definition sources.')); + return; + } + if (!r.ok) throw new Error('HTTP ' + r.status); + renderPromptSourcesPanel(host, await r.json()); + } catch (e) { + host = host || document.getElementById('gov-prompt-sources-host'); + if (!host) return; + host.textContent = ''; + host.appendChild(writeSurfaceNode('div', 'color:var(--red);font-size:0.8rem', + 'Failed to load prompt sources: ' + e.message)); + } + } + + async function setPromptSourceRepo(host, repo, allowed, notice) { + if (allowed) { + const ok = await hiveConfirm({ + title: 'Trust ' + repo + ' as a prompt source?', + message: notice + '\n\nAgents whose prompt_source or definition_source points at ' + repo + ' will load it on their next kick or reload. This is audit-logged.', + confirmLabel: 'Approve ' + repo, + danger: true + }); + if (!ok) return; + } + try { + const res = await fetch('/api/config/prompt-sources/owner-repos', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify({ repo, allowed, acknowledge_trust: !!allowed }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + renderPromptSourcesPanel(host, await res.json()); + showToast(allowed ? repo + ' approved as a prompt source' : repo + ' approval revoked', 'success'); + } catch (e) { + showToast('Prompt source change failed: ' + e.message, 'error'); + } + } + + function renderPromptSourcesPanel(host, d) { + if (!host) return; + d = d || {}; + host.textContent = ''; + const card = writeSurfaceNode('div', 'border:1px solid var(--border);border-radius:8px;padding:14px;background:var(--surface);max-width:640px'); + card.appendChild(writeSurfaceNode('div', 'font-weight:600;font-size:0.9rem;margin-bottom:var(--sp-4)', 'Repo-sourced prompts and definitions')); + card.appendChild(writeSurfaceNode('div', 'font-size:0.74rem;color:var(--muted);line-height:1.5;margin-bottom:var(--sp-4)', + 'An agent can load its kick prompt from a GitHub repo with prompt_source, or its whole definition with definition_source. ' + + (d.trust_notice || '') + ' ' + (d.seed_only_note || ''))); + const repos = d.repos || []; + if (!repos.length) { + card.appendChild(writeSurfaceNode('div', 'font-size:0.8rem;color:var(--muted)', 'This hive has no managed repos.')); + } + repos.forEach(row => { + const line = writeSurfaceNode('div', 'display:flex;align-items:center;gap:10px;padding:var(--sp-2) var(--sp-0);border-top:1px solid var(--border);font-size:0.8rem'); + line.appendChild(writeSurfaceNode('code', 'flex:1', row.repo)); + let state = 'Not allowed'; + if (row.seed_allowed) state = 'Allowed by the config volume'; + else if (row.owner_approved && row.managed) state = 'Owner-approved' + (row.approved_by ? ' by ' + row.approved_by : '') + (row.approved_at ? ' on ' + row.approved_at.slice(0, 10) : ''); + else if (row.owner_approved) state = 'Approval inert: no longer a managed repo'; + line.appendChild(writeSurfaceNode('span', 'color:' + (row.allowed ? 'var(--green)' : 'var(--muted)'), state)); + if (row.owner_approved) { + const btn = writeSurfaceNode('button', '', 'Revoke'); + btn.className = 'hv-btn btn-secondary btn-sm'; + btn.addEventListener('click', () => setPromptSourceRepo(host, row.repo, false, d.trust_notice || '')); + line.appendChild(btn); + } else if (row.managed && !row.seed_allowed) { + const btn = writeSurfaceNode('button', '', 'Approve…'); + btn.className = 'hv-btn btn-primary btn-sm'; + btn.addEventListener('click', () => setPromptSourceRepo(host, row.repo, true, d.trust_notice || '')); + line.appendChild(btn); + } + card.appendChild(line); + }); + host.appendChild(card); + } + /* loadBackupKeyStatus fetches presence-only backup-key status and paints the Backup panel. The response carries `configured`/`usable` and a safe `source` string ("file:" / "env:") — never the key value. diff --git a/src/pkg/dashboard/static/index.html b/src/pkg/dashboard/static/index.html index 4a43e8d843..092d2f7e76 100644 --- a/src/pkg/dashboard/static/index.html +++ b/src/pkg/dashboard/static/index.html @@ -73126,6 +73126,13 @@

Escalation Breaker

const writeSurface = `
Loading…
`; + /* Prompt sources (#18490): owner approval of the hive's own managed + repos for prompt_source / definition_source, from its own + owner-only endpoint. */ + loadPromptSourcesPanel(); + const promptSources = ` +
Loading…
`; + /* Suspicious Activity (sentinel): flags PRs that look like security overrides, privilege escalation or codebase damage. Untrusted authors get the blocking alert label; trusted authors default to notice-only. */ @@ -73179,6 +73186,7 @@

Escalation Breaker

${renderSecuritySection('Suspicious Activity', suspicious + suspiciousFindings)} ${renderSecuritySection('Isolation', isolation)} ${renderSecuritySection('Write Surface', writeSurface)} + ${renderSecuritySection('Prompt sources', promptSources)} ${renderSecuritySection('GitHub App permissions', securityCapabilitiesHtml((window._lastStatus || {}).capabilities, (window._lastStatus || {}).githubAppInstallURL))} ${renderSecuritySection('Backup', backupKey)}`; } @@ -73306,6 +73314,96 @@

Escalation Breaker

}); } + /* Prompt sources (#18490): lists the hive's managed repos and whether an + agent's prompt_source / definition_source may read from each. The owner + approves one repo at a time behind a confirm that names the trust + implication; the server refuses repos outside project.repos, audits + the change and persists it to the running config. Rendered with DOM + nodes and textContent only. */ + async function loadPromptSourcesPanel() { + let host = null; + try { + const r = await fetch('/api/config/prompt-sources'); + host = document.getElementById('gov-prompt-sources-host'); + if (!host) return; + if (r.status === 403) { + host.textContent = ''; + host.appendChild(writeSurfaceNode('div', 'color:var(--muted);font-size:0.8rem', + 'Only the hive owner can approve repos as prompt and definition sources.')); + return; + } + if (!r.ok) throw new Error('HTTP ' + r.status); + renderPromptSourcesPanel(host, await r.json()); + } catch (e) { + host = host || document.getElementById('gov-prompt-sources-host'); + if (!host) return; + host.textContent = ''; + host.appendChild(writeSurfaceNode('div', 'color:var(--red);font-size:0.8rem', + 'Failed to load prompt sources: ' + e.message)); + } + } + + async function setPromptSourceRepo(host, repo, allowed, notice) { + if (allowed) { + const ok = await hiveConfirm({ + title: 'Trust ' + repo + ' as a prompt source?', + message: notice + '\n\nAgents whose prompt_source or definition_source points at ' + repo + ' will load it on their next kick or reload. This is audit-logged.', + confirmLabel: 'Approve ' + repo, + danger: true + }); + if (!ok) return; + } + try { + const res = await fetch('/api/config/prompt-sources/owner-repos', { + method: 'PUT', + headers: _inceptionAuthHeaders(), + body: JSON.stringify({ repo, allowed, acknowledge_trust: !!allowed }) + }); + if (!res.ok) throw new Error(await saveErrorMessage(res)); + renderPromptSourcesPanel(host, await res.json()); + showToast(allowed ? repo + ' approved as a prompt source' : repo + ' approval revoked', 'success'); + } catch (e) { + showToast('Prompt source change failed: ' + e.message, 'error'); + } + } + + function renderPromptSourcesPanel(host, d) { + if (!host) return; + d = d || {}; + host.textContent = ''; + const card = writeSurfaceNode('div', 'border:1px solid var(--border);border-radius:8px;padding:14px;background:var(--surface);max-width:640px'); + card.appendChild(writeSurfaceNode('div', 'font-weight:600;font-size:0.9rem;margin-bottom:var(--sp-4)', 'Repo-sourced prompts and definitions')); + card.appendChild(writeSurfaceNode('div', 'font-size:0.74rem;color:var(--muted);line-height:1.5;margin-bottom:var(--sp-4)', + 'An agent can load its kick prompt from a GitHub repo with prompt_source, or its whole definition with definition_source. ' + + (d.trust_notice || '') + ' ' + (d.seed_only_note || ''))); + const repos = d.repos || []; + if (!repos.length) { + card.appendChild(writeSurfaceNode('div', 'font-size:0.8rem;color:var(--muted)', 'This hive has no managed repos.')); + } + repos.forEach(row => { + const line = writeSurfaceNode('div', 'display:flex;align-items:center;gap:10px;padding:var(--sp-2) var(--sp-0);border-top:1px solid var(--border);font-size:0.8rem'); + line.appendChild(writeSurfaceNode('code', 'flex:1', row.repo)); + let state = 'Not allowed'; + if (row.seed_allowed) state = 'Allowed by the config volume'; + else if (row.owner_approved && row.managed) state = 'Owner-approved' + (row.approved_by ? ' by ' + row.approved_by : '') + (row.approved_at ? ' on ' + row.approved_at.slice(0, 10) : ''); + else if (row.owner_approved) state = 'Approval inert: no longer a managed repo'; + line.appendChild(writeSurfaceNode('span', 'color:' + (row.allowed ? 'var(--green)' : 'var(--muted)'), state)); + if (row.owner_approved) { + const btn = writeSurfaceNode('button', '', 'Revoke'); + btn.className = 'hv-btn btn-secondary btn-sm'; + btn.addEventListener('click', () => setPromptSourceRepo(host, row.repo, false, d.trust_notice || '')); + line.appendChild(btn); + } else if (row.managed && !row.seed_allowed) { + const btn = writeSurfaceNode('button', '', 'Approve…'); + btn.className = 'hv-btn btn-primary btn-sm'; + btn.addEventListener('click', () => setPromptSourceRepo(host, row.repo, true, d.trust_notice || '')); + line.appendChild(btn); + } + card.appendChild(line); + }); + host.appendChild(card); + } + /* loadBackupKeyStatus fetches presence-only backup-key status and paints the Backup panel. The response carries `configured`/`usable` and a safe `source` string ("file:" / "env:") — never the key value.