Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions docs/organizations-commit-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,24 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran
the content path, as for the first agent. The answer then names no Kustomization, and
a delete asks for no step by hand: the organization's Kustomization prunes. A refused
read of a Kustomization of another name stays an error.
- A content path can have no `kustomization.yaml`: git did not get it from
`create_organization` in mode commit, for example for an organization created in mode
apply. Flux then generates its kustomization from the files there, with `agent-manager/`
of the agent tools. An organization write in mode commit into such a content path does
not create a `kustomization.yaml` there, also when it only removes a file, and does not
list the content path in a `kustomization.yaml` above it. A dry run shows no such file
in `commit.files`. Flux continues to generate the list, with the agents and every
other file. A `kustomization.yaml` of the write's own objects would leave them out,
and the organization's Kustomization would prune them. A write that removes a file
adds `<contentPrefix>/<name>/.gitkeep` when git does not have it: git keeps no empty
directory, and the organization's Kustomization would fail on a path that does not
exist and prune nothing. Flux's generator lists YAML files only, so the `.gitkeep`
changes nothing that Flux applies, and a delete of the organization removes it with the
rest of the content path. A content path with a `kustomization.yml`
or `Kustomization` also gets no `kustomization.yaml`, because Kustomize refuses a
directory with two kustomization files; but no write lists its objects in that file,
so Flux does not apply them. Where the content path has a `kustomization.yaml`, the
write lists its objects there, as before.
- The admins are not a file of the content path: they are `spec.admins` of the
organization's file, and agent-platform-operator binds them to `agent-platform:admin`
in the organization namespace.
Expand Down
2 changes: 2 additions & 0 deletions internal/api/credential_operations_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -403,6 +403,8 @@ func TestCredentialOperationCommitsConsumerAndEncryptedSecretTogether(t *testing
files := forge.Files(mcRepo, forge.PullRequests()[0].Head)
require.Contains(t, files, paymentsPath+"/modelconfig-claude.yaml")
require.Contains(t, string(files[paymentsPath+"/tenant-credential-claude-secret.enc.yaml"]), "ENC[AES256_GCM,")
_, created := files[contentKustomization]
require.False(t, created, "a content path without kustomization.yaml stays Flux's to generate")
for _, raw := range files {
require.NotContains(t, string(raw), "synthetic-credential")
require.NotContains(t, string(raw), "c3ludGhldGljLWNyZWRlbnRpYWw=")
Expand Down
167 changes: 156 additions & 11 deletions internal/api/organizations_commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ package api
import (
"context"
"errors"
"maps"
"net/http"
"slices"
"strings"
"testing"

Expand All @@ -22,6 +24,7 @@ import (

"github.com/giantswarm/agent-manager/internal/agents"
"github.com/giantswarm/agent-manager/internal/organizations"
"github.com/giantswarm/agent-manager/internal/tags/tagstest"
)

var mcRepo = commit.Repository{Owner: "giantswarm", Name: "gazelle-config"}
Expand Down Expand Up @@ -224,11 +227,13 @@ func gitOrganizationWith(t *testing.T, wrap func(*commit.Fake) organizations.Git
}

// Delete in commit mode, two steps: the pull request removes the object's
// file and the whole content path and the live object is marked with it; a
// live delete is refused while the file is in git; after the merge, which
// removed the file, Erase now marks the delete intent and deletes.
// file and the whole content path, its .gitkeep too, and the live object is
// marked with it; a live delete is refused while the file is in git; after
// the merge, which removed the file, Erase now marks the delete intent and
// deletes.
func TestDeleteOrganizationInCommitModeTakesTwoSteps(t *testing.T) {
f, fake := gitOrganization(t)
require.NoError(t, fake.Commit(t.Context(), mcRepo, "main", "keep the path", map[string][]byte{paymentsPath + "/.gitkeep": []byte("\n")}))
del := func(confirm string) (string, bool) {
args := map[string]any{"name": "payments", "mode": "commit"}
if confirm != "" {
Expand Down Expand Up @@ -1042,9 +1047,29 @@ func TestEveryContentToolCommits(t *testing.T) {
}

// The removal of the last object of an organization's content path keeps
// its kustomization.yaml, with an empty list: the organization's
// Kustomization builds that path, and would fail on one that does not exist.
// the path: the organization's Kustomization builds it, and would fail on one
// that does not exist, pruning nothing. A content path with a
// kustomization.yaml keeps it, with an empty list. One whose kustomization
// Flux generates gets a .gitkeep, since git keeps no empty directory, and no
// kustomization file; a .gitkeep that git carries already is not written
// again.
func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) {
for _, tc := range []struct {
name string
base map[string][]byte
marker bool
}{
{"with a kustomization.yaml", map[string][]byte{contentKustomization: []byte("resources:\n - rolebinding-organization-editors.yaml\n")}, false},
{"generated by Flux", nil, true},
{"generated by Flux, with a .gitkeep", map[string][]byte{paymentsPath + "/.gitkeep": []byte("\n")}, false},
} {
t.Run(tc.name, func(t *testing.T) {
testRemovingTheLastContentObject(t, tc.base, tc.marker)
})
}
}

func testRemovingTheLastContentObject(t *testing.T, more map[string][]byte, marker bool) {
editors := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "rbac.authorization.k8s.io/v1", "kind": "RoleBinding",
"metadata": map[string]any{"name": "organization-editors"},
Expand All @@ -1056,17 +1081,137 @@ func TestRemovingTheLastContentObjectKeepsTheContentPath(t *testing.T) {
live := editors.DeepCopy()
live.SetNamespace(orgNS)
live.SetLabels(fromGitLabels("agents-payments-x7k2q"))
f, fake := commitFixture(t, map[string][]byte{
paymentsPath + "/kustomization.yaml": []byte("resources:\n - rolebinding-organization-editors.yaml\n"),
paymentsPath + "/rolebinding-organization-editors.yaml": file,
}, live)
base := map[string][]byte{paymentsPath + "/rolebinding-organization-editors.yaml": file}
maps.Copy(base, more)
f, fake := commitFixture(t, base, live)

text, isErr := f.call(t, ToolRemoveOrganizationMember, map[string]any{"organization": "payments", "group": "payments-team", "mode": "commit"})
require.False(t, isErr, text)
require.Len(t, fake.PullRequests(), 1)
head := fake.Files(mcRepo, fake.PullRequests()[0].Head)
assert.NotContains(t, head, paymentsPath+"/rolebinding-organization-editors.yaml")
assert.Equal(t, "resources: []\n", string(head[paymentsPath+"/kustomization.yaml"]))
var left []string
for p := range head {
if strings.HasPrefix(p, paymentsPath+"/") {
left = append(left, p)
}
}
slices.Sort(left)
if _, kept := more[contentKustomization]; kept {
assert.Equal(t, []string{contentKustomization}, left)
assert.Equal(t, "resources: []\n", string(head[contentKustomization]))
return
}
assert.Equal(t, []string{paymentsPath + "/.gitkeep"}, left, "the path stays with no kustomization file")
assert.Equal(t, marker, slices.Contains(commitFiles(t, text), paymentsPath+"/.gitkeep"), "the .gitkeep is written only when git lacks it")
}

// contentKustomization is the content path's own kustomization.yaml.
const contentKustomization = paymentsPath + "/kustomization.yaml"

// commitFiles are the paths of the files a tool's answer names in
// commit.files.
func commitFiles(t *testing.T, text string) []string {
t.Helper()
var out []string
for _, file := range decode(t, text)["commit"].(map[string]any)["files"].([]any) {
out = append(out, file.(map[string]any)["path"].(string))
}
return out
}

// An organization that git did not get from create_organization in mode
// commit, one created in mode apply, has no kustomization.yaml in its content
// path: Flux generates one from the path's files, with agent-manager's
// directory of its first agent. An organization write in mode commit after
// that agent's merge creates no kustomization.yaml there, so Flux goes on
// building agent-manager's directory beside the new file; one of the write's
// own file alone would drop the agent (giantswarm/agent-manager#498).
func TestAnOrganizationWriteAfterItsFirstAgentKeepsTheAgent(t *testing.T) {
chartSource := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "source.toolkit.fluxcd.io/v1", "kind": "OCIRepository",
"metadata": map[string]any{"name": "agent", "namespace": orgNS},
"spec": map[string]any{"interval": "30m", "url": agents.DefaultChartOCIURL, "ref": map[string]any{"semver": agents.DefaultChartSemver}},
}}
f, fake := commitFixture(t, nil, ownModel(), chartSource)
svc := agents.New(f.provider, embeddedChart{}, nil, agents.InProcessPinner(pinner{}), agents.Config{
DefaultNamespace: "kagent", Version: "test", Tags: tagstest.Rule(), Tenants: f.cfg.Namespaces,
OrganizationContent: f.orgs.ContentLocation,
GitHub: func(string) (agents.GitHubRemote, error) { return fake, nil },
GitHubUser: f.cfg.Commit.User,
}, nil)
f.srv = NewMCPServer(svc, "test", WithOrganizations(f.orgs), WithLifecycle(t.Context()))

text, isErr := f.call(t, ToolCreateAgent, map[string]any{"organization": "payments", "name": "sre", "modelConfig": "own", "toolset": []string{"preset:read-only"}, "mode": "commit"})
require.False(t, isErr, text)
require.Len(t, fake.PullRequests(), 1)
require.NoError(t, fake.Merge(t.Context(), fake.PullRequests()[0].PullRequest))

merged := fake.Files(mcRepo, "main")
require.Contains(t, slices.Collect(maps.Keys(merged)), paymentsPath+"/agent-manager/kustomization.yaml")
require.NotContains(t, slices.Collect(maps.Keys(merged)), contentKustomization, "Flux generates the content path's kustomization")

text, isErr = f.call(t, ToolSetOrganizationEgress, map[string]any{"organization": "payments", "name": "github", "destinations": []any{map[string]any{"origin": "https://api.github.com"}}, "mode": "commit"})
require.False(t, isErr, text)
require.Len(t, fake.PullRequests(), 2)
assert.NotContains(t, commitFiles(t, text), contentKustomization)
head := fake.Files(mcRepo, fake.PullRequests()[1].Head)
assert.NotContains(t, slices.Collect(maps.Keys(head)), contentKustomization, "Flux goes on generating the content path's kustomization")
assert.Contains(t, slices.Collect(maps.Keys(head)), paymentsPath+"/egresspolicy-github.yaml")
for p, content := range merged {
if strings.HasPrefix(p, paymentsPath+"/agent-manager/") {
assert.Equal(t, string(content), string(head[p]), "the agent stays as merged")
}
}
}

// A content path without a kustomization.yaml whose agent an older
// agent-manager merged: every organization write in mode commit leaves it to
// Flux's generated kustomization. A dry run names no content-path
// kustomization.yaml, a write that only removes a file creates none, a
// content path with a kustomization.yml gets no second kustomization file,
// which Kustomize refuses, and a kustomization above the content path does
// not list it, nor loses its entry.
func TestOrganizationWritesLeaveAContentPathWithoutKustomizationToFlux(t *testing.T) {
const above = "agent-platform/organizations/kustomization.yaml"
claude := model("claude", true)
claude.SetLabels(fromGitLabels(orgNS))
claudeFile := model("claude", true)
claudeFile.SetNamespace("")
claudeYAML, err := yaml.Marshal(claudeFile.Object)
require.NoError(t, err)
agent := []byte("apiVersion: helm.toolkit.fluxcd.io/v2\nkind: HelmRelease\nmetadata:\n name: sre\n")
egress := map[string]any{"organization": "payments", "name": "github", "destinations": []any{map[string]any{"origin": "https://api.github.com"}}, "mode": "commit"}
for _, tc := range []struct {
name string
more map[string][]byte
tool string
args map[string]any
}{
{"a dry run", nil, ToolSetOrganizationEgress, map[string]any{"organization": "payments", "name": "github", "destinations": egress["destinations"], "mode": "commit", "dryRun": true}},
{"a write that only removes a file", nil, ToolDeleteOrganizationObject, map[string]any{"organization": "payments", "kind": "model", "name": "claude", "mode": "commit"}},
{"a content path with a kustomization.yml", map[string][]byte{paymentsPath + "/kustomization.yml": []byte("resources:\n - agent-manager\n - modelconfig-claude.yaml\n")}, ToolSetOrganizationEgress, egress},
{"a kustomization above that does not list it", map[string][]byte{above: []byte("resources:\n - billing\n")}, ToolSetOrganizationEgress, egress},
{"a removal under a kustomization above that lists it", map[string][]byte{above: []byte("resources:\n - payments\n")}, ToolDeleteOrganizationObject, map[string]any{"organization": "payments", "kind": "model", "name": "claude", "mode": "commit"}},
} {
t.Run(tc.name, func(t *testing.T) {
base := map[string][]byte{
paymentsPath + "/agent-manager/kustomization.yaml": []byte("resources:\n - sre.yaml\n"),
paymentsPath + "/agent-manager/sre.yaml": agent,
paymentsPath + "/modelconfig-claude.yaml": claudeYAML,
}
maps.Copy(base, tc.more)
f, fake := commitFixture(t, base, claude.DeepCopy())
text, isErr := f.call(t, tc.tool, tc.args)
require.False(t, isErr, text)
assert.NotContains(t, commitFiles(t, text), contentKustomization)
for _, pr := range fake.PullRequests() {
head := fake.Files(mcRepo, pr.Head)
assert.NotContains(t, slices.Collect(maps.Keys(head)), contentKustomization)
assert.Equal(t, agent, head[paymentsPath+"/agent-manager/sre.yaml"])
assert.Equal(t, string(base[above]), string(head[above]), "the kustomization above the content path stays")
}
})
}
}

// A .sops.yaml rule that makes a plain object's file secret is refused:
Expand Down
70 changes: 62 additions & 8 deletions internal/organizations/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -317,10 +317,12 @@ type fileChange struct {
// add are files added beside layout.Build, which takes object files
// only: the empty kustomization.yaml of a new content path.
add map[string][]byte
// keep keeps the directory's own kustomization.yaml, with an empty
// list, when its last object goes: a Flux Kustomization builds the
// directory, and would fail on a path that does not exist.
keep bool
// content marks an organization's content path. Its own
// kustomization.yaml stays, with an empty list, when its last object
// goes: a Flux Kustomization builds the directory, and would fail on a
// path that does not exist. A content path without one is left to Flux's
// generated kustomization (leaveToFlux).
content bool
// objects marks the objects path: it is kept, and the kustomization
// above it, outside the objects path, is never changed.
objects bool
Expand All @@ -347,21 +349,27 @@ func (c *orgCommit) open(ctx context.Context, changes []fileChange, object, titl
if err != nil {
return nil, commitError(c.gh, err)
}
for _, f := range plan.Files {
change = plan.Change()
files := plan.Files
if ch.content {
if files, err = c.leaveToFlux(ctx, ch.dir, &change, files); err != nil {
return nil, err
}
}
for _, f := range files {
file := agents.CommitFile{Path: f.Path, Action: string(f.Action)}
if dryRun {
file.Content = string(f.Content)
}
out.Files = append(out.Files, file)
}
change = plan.Change()
}
if ch.objects {
above := path.Join(ch.dir.Directory, layout.KustomizationFile)
delete(change.Files, above)
out.Files = slices.DeleteFunc(out.Files, func(f agents.CommitFile) bool { return f.Path == above })
}
if ch.keep || ch.objects {
if ch.content || ch.objects {
if err := c.keepKustomization(ctx, ch.dir, &change, out, dryRun); err != nil {
return nil, err
}
Expand Down Expand Up @@ -467,6 +475,52 @@ func (c *orgCommit) keepKustomization(ctx context.Context, dir layout.Directory,
return nil
}

// leaveToFlux takes out of change, the plan layout.Build made for dir, an
// organization's content path, the content path's kustomization.yaml that
// the plan creates, and returns files, the plan's files, without it. Without
// a kustomization.yaml on the base branch, Flux generates the content path's
// kustomization from its files: agent-manager's directory of the agent tools
// and every other file (giantswarm/agent-manager#498). A kustomization.yaml
// of the write's own files would leave them out, and the organization's
// Kustomization would prune them. A content path with a kustomization.yml
// or Kustomization gets no second kustomization file either, which Kustomize
// refuses. Build decides the directory's kustomization.yaml on every write,
// so a plan that does not create it either changes the one the base carries,
// which stays as planned, or finds none and writes none. With no
// kustomization.yaml in the content path, the kustomization above it does
// not list the directory either. A write that removes a file adds the
// content path's keepFile when the base has none: git keeps no empty
// directory, and the organization's Kustomization, which builds the path,
// would fail on a path that does not exist and prune nothing. Flux's
// generator lists YAML files only, so the marker changes nothing of what it
// builds.
func (c *orgCommit) leaveToFlux(ctx context.Context, dir layout.Directory, change *commit.Change, files []layout.File) ([]layout.File, error) {
own := path.Join(dir.Path(), layout.KustomizationFile)
if i := slices.IndexFunc(files, func(f layout.File) bool { return f.Path == own }); i >= 0 && files[i].Action != layout.Add {
return files, nil
}
above := path.Join(dir.Directory, layout.KustomizationFile)
delete(change.Files, own)
delete(change.Files, above)
files = slices.DeleteFunc(slices.Clone(files), func(f layout.File) bool { return f.Path == own || f.Path == above })
if !slices.ContainsFunc(files, func(f layout.File) bool { return f.Action == layout.Remove }) {
return files, nil
}
marker := path.Join(dir.Path(), keepFile)
if has, err := c.exists(ctx, marker); err != nil || has {
return files, err
}
change.Files[marker] = keepContent
return append(files, layout.File{Path: marker, Action: layout.Add, Content: keepContent}), nil
}

// keepFile keeps a content path without kustomization.yaml in git when a
// write removes its last file (leaveToFlux).
const keepFile = ".gitkeep"

// keepContent says why keepFile is there.
var keepContent = []byte("# Keeps this organization's content path in git when it has no other file: Flux generates its kustomization and prunes what left it.\n")

// land is commit.Open for the one repository and base of c, with the files
// creates must still be absent from the base once the branch is cut: a file
// another commit added to the base after the plan was decided, and so before
Expand Down Expand Up @@ -823,7 +877,7 @@ func (w *contentWriter) land(ctx context.Context, s *Service, writes []write, dr
if err != nil {
return nil, err
}
ch := fileChange{dir: w.dir, write: map[string][]byte{}, keep: w.org.Scope != scopePlatform}
ch := fileChange{dir: w.dir, write: map[string][]byte{}, content: w.org.Scope != scopePlatform}
for _, wr := range writes {
if err := segment(wr.kind+" name", wr.name); err != nil {
return nil, err
Expand Down
Loading
Loading