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
3 changes: 1 addition & 2 deletions cmd/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import (

apov1alpha1 "github.com/giantswarm/agent-platform-operator/api/v1alpha1"
"github.com/giantswarm/gitops-commit/commit"
"github.com/giantswarm/gitops-commit/provenance"
"github.com/giantswarm/mcp-oauth/oauthconfig"
"github.com/giantswarm/mcp-oauth/requeststate"
"github.com/giantswarm/mcp-toolkit/metrics"
Expand Down Expand Up @@ -647,7 +646,7 @@ func tenantSetOrNil(r *organizations.Namespaces) agents.TenantSet {

// organizationContentOrNil is the content path finder of the organization
// tools, nil without them.
func organizationContentOrNil(orgs *organizations.Service) func(context.Context, string) (provenance.Location, bool, error) {
func organizationContentOrNil(orgs *organizations.Service) func(context.Context, string) (agents.OrganizationNamespace, bool, error) {
if orgs == nil {
return nil
}
Expand Down
9 changes: 9 additions & 0 deletions docs/organizations-commit-mode.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,15 @@ Secret. Commits, over MCP and REST, use the configured RFC 8693 manager App gran
agent chart source is never a file there: the organization's Kustomization cannot
apply an `OCIRepository`, and agent-platform-operator keeps one in each organization
namespace. Until it exists, `create_agent` refuses.
- An organization's members may not read the organization Namespace, which is
cluster-scoped. When the caller's read of it is refused, `create_agent` uses the Flux
labels that agent-manager's ServiceAccount reads on the Namespace, and no other label:
labels to a Kustomization give that Kustomization's target, read as the caller, as
for a caller who can read the Namespace. A caller who may not read that Kustomization
gets an error that names it, not the content path, unless it is the organization's own
Kustomization (see the next item). A Namespace without the labels
leaves the target to the content path. A read of the Namespace that fails for another
reason is an error.
- Once the first agent is merged, its release carries the Flux labels of the
organization's own Kustomization. agent-platform-operator keeps that Kustomization in
its Flux namespace and names it after the organization namespace, and an organization's
Expand Down
97 changes: 78 additions & 19 deletions internal/agents/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,16 +226,14 @@ func (s *Service) ownerLocation(ctx context.Context, st *site, obj *unstructured

// namespaceLocation is where a new agent of the site goes: the caller's target, else
// the repository that owns the namespace's agents — the shared chart source,
// then any agent release applied from git, then the Namespace itself, each
// followed by ownerLocation — else, in an organization namespace, the
// organization's content path.
// then any agent release applied from git, each followed by ownerLocation —
// else the Namespace's (namespaceTarget).
func (s *Service) namespaceLocation(ctx context.Context, st *site, w WriteOptions) (commitLocation, error) {
if w.Repository != "" {
return explicitLocation(w)
}
dyn, ns := st.flux, st.fluxNS
var candidates []*unstructured.Unstructured
if src, err := s.getObject(ctx, dyn, s.ociRepositoryGVR(), ns, s.cfg.Compose.ChartName, "ocirepository"); err != nil {
if src, err := s.getObject(ctx, st.flux, s.ociRepositoryGVR(), st.fluxNS, s.cfg.Compose.ChartName, "ocirepository"); err != nil {
return commitLocation{}, err
} else if src != nil {
candidates = append(candidates, src)
Expand All @@ -247,38 +245,99 @@ func (s *Service) namespaceLocation(ctx context.Context, st *site, w WriteOption
for _, name := range sortedKeys(hrs) {
candidates = append(candidates, hrs[name])
}
if nsObj, err := dyn.Resource(namespaceGVR).Get(ctx, ns, metav1.GetOptions{}); err == nil {
candidates = append(candidates, nsObj)
}
for _, obj := range candidates {
loc, err := s.ownerLocation(ctx, st, obj)
if errors.Is(err, errNotFromGit) {
continue
}
return loc, err
}
if loc, ok, err := s.organizationContent(ctx, st); err != nil || ok {
return loc, err
return s.namespaceTarget(ctx, st)
}

// namespaceTarget is where a new agent of the site goes when no agent object
// of the namespace names a target: the target of the Kustomization the
// Namespace's Flux labels name (ownerLocation), else, in an organization
// namespace, the organization's content path.
//
// The Namespace is read as the caller. It is cluster-scoped, and an
// organization's members may not get it. In an organization namespace a
// forbidden read then follows the Flux labels that agent-manager's own
// ServiceAccount reads on it (OrganizationNamespace), so the content path never
// takes the place of the target those labels name; the Kustomization and its
// source are still read as the caller. A read that fails there for another
// reason is an error. Elsewhere a failed read leaves the Namespace out.
func (s *Service) namespaceTarget(ctx context.Context, st *site) (commitLocation, error) {
nsObj, readErr := st.flux.Resource(namespaceGVR).Get(ctx, st.fluxNS, metav1.GetOptions{})
if readErr == nil {
if loc, err := s.ownerLocation(ctx, st, nsObj); !errors.Is(err, errNotFromGit) {
return loc, err
}
}
org, ok, err := s.organizationNamespace(ctx, st)
if err != nil {
return commitLocation{}, err
}
if !ok {
return commitLocation{}, invalidf("no Flux Kustomization owns the agents of namespace %s (neither its agent chart source, an agent release nor the Namespace carries %s): name the target with repository, branch and path, or use mode apply", st.fluxNS, KustomizationNameLabel)
}
switch {
case readErr == nil, apierrors.IsNotFound(readErr):
case apierrors.IsForbidden(readErr):
labelled := &unstructured.Unstructured{}
labelled.SetAPIVersion("v1")
labelled.SetKind("Namespace")
labelled.SetName(st.fluxNS)
labelled.SetLabels(org.NamespaceLabels)
if loc, err := s.ownerLocation(ctx, st, labelled); !errors.Is(err, errNotFromGit) {
return loc, err
}
default:
return commitLocation{}, wrapKube(readErr, "get Namespace "+st.fluxNS)
}
return commitLocation{}, invalidf("no Flux Kustomization owns the agents of namespace %s (neither its agent chart source, an agent release nor the Namespace carries %s): name the target with repository, branch and path, or use mode apply", ns, KustomizationNameLabel)
return contentLocation(org), nil
}

// OrganizationNamespace is an organization namespace as agent-manager's own
// ServiceAccount reads it (Config.OrganizationContent).
type OrganizationNamespace struct {
// Content is where the organization tools commit the organization's
// contents: the organizations repository, its branch and the
// organization's content path.
Content provenance.Location
// NamespaceLabels are the Flux Kustomization labels of the Namespace
// (KustomizationNameLabel and KustomizationNamespaceLabel), nil when it
// carries none. Commit mode follows them when the caller may not read the
// Namespace; it reads no other label of it this way.
NamespaceLabels map[string]string
}

// organizationNamespace is the organization namespace the site is, as
// agent-manager's ServiceAccount reads it. None on a workload cluster: the
// site's namespace there holds the organization's clusters, not its contents.
func (s *Service) organizationNamespace(ctx context.Context, st *site) (OrganizationNamespace, bool, error) {
if st.loc.IsSet() || s.cfg.OrganizationContent == nil {
return OrganizationNamespace{}, false, nil
}
return s.cfg.OrganizationContent(ctx, st.fluxNS)
}

// organizationContent is the content path of the organization whose
// namespace the site is, where the organization tools commit its contents:
// the target of its first agent, which no Flux object of the namespace names
// yet. The organization's Kustomization applies the content path into the
// namespace, and the agent's directory beside its other files. None on a
// workload cluster: the site's namespace there holds the organization's
// clusters, not its contents.
// namespace, and the agent's directory beside its other files.
func (s *Service) organizationContent(ctx context.Context, st *site) (commitLocation, bool, error) {
if st.loc.IsSet() || s.cfg.OrganizationContent == nil {
return commitLocation{}, false, nil
}
loc, ok, err := s.cfg.OrganizationContent(ctx, st.fluxNS)
org, ok, err := s.organizationNamespace(ctx, st)
if err != nil || !ok {
return commitLocation{}, false, err
}
return commitLocation{Location: loc, liveChartSource: true}, true, nil
return contentLocation(org), true, nil
}

// contentLocation is the commit target of org's content path.
func contentLocation(org OrganizationNamespace) commitLocation {
return commitLocation{Location: org.Content, liveChartSource: true}
}

// releaseLocation is where an existing agent's release of the site lives in
Expand Down
4 changes: 2 additions & 2 deletions internal/agents/commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,8 +229,8 @@ func organizationFixture(t *testing.T) (*fixture, *commit.Fake, context.Context)
f, fake, ctx := gitOpsFixture(t, true)
withTenants(f, &fakeTenants{namespaces: []string{orgNS}, owners: map[string]string{orgNS: "pay"}})
mustCreate(t, f, mcGVR, modelConfig(orgNS, "own", "Anthropic", "claude-sonnet-4-6"))
f.svc.cfg.OrganizationContent = func(_ context.Context, ns string) (provenance.Location, bool, error) {
return provenance.Location{Repository: orgRepo, Branch: "main", Directory: orgContent}, ns == orgNS, nil
f.svc.cfg.OrganizationContent = func(_ context.Context, ns string) (OrganizationNamespace, bool, error) {
return OrganizationNamespace{Content: provenance.Location{Repository: orgRepo, Branch: "main", Directory: orgContent}}, ns == orgNS, nil
}
return f, fake, ctx
}
Expand Down
12 changes: 6 additions & 6 deletions internal/agents/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import (
"strings"
"time"

"github.com/giantswarm/gitops-commit/provenance"
"golang.org/x/sync/errgroup"
authenticationv1 "k8s.io/api/authentication/v1"
authorizationv1 "k8s.io/api/authorization/v1"
Expand Down Expand Up @@ -95,11 +94,12 @@ type Config struct {
Tenants TenantSet
// OrganizationContent is where the organization tools commit the
// contents of the organization whose namespace ns is: the organizations
// repository, its branch and the organization's content path. Commit
// mode writes an organization's first agent there, when no Flux object of
// its namespace names a target. Nil, or ok false: no such target (no
// organizations commit mode, or ns is no organization namespace).
OrganizationContent func(ctx context.Context, ns string) (loc provenance.Location, ok bool, err error)
// repository, its branch and the organization's content path, with the
// Flux labels of the Namespace. Commit mode writes an organization's first
// agent there, when no Flux object of its namespace names a target. Nil,
// or ok false: no such target (no organizations commit mode, or ns is no
// organization namespace).
OrganizationContent func(ctx context.Context, ns string) (org OrganizationNamespace, ok bool, err error)
// Tags is the agent chart's tag rule, loaded from the embedded chart
// (chart.EmbeddedSchema().Tags). Nil: the chart takes no tags; agents
// are read without them and capabilities.tags is false.
Expand Down
112 changes: 99 additions & 13 deletions internal/api/organizations_commit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1127,19 +1127,8 @@ func commitFiles(t *testing.T, text string) []string {
// 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()))
f, fake := commitFixture(t, nil, ownModel(), orgChartSource())
withCommittingAgentTools(t, f, fake)

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)
Expand All @@ -1164,6 +1153,103 @@ func TestAnOrganizationWriteAfterItsFirstAgentKeepsTheAgent(t *testing.T) {
}
}

// orgChartSource is the agent chart source agent-platform-operator keeps live
// in the organization namespace, applied from no git.
func orgChartSource() *unstructured.Unstructured {
return &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}},
}}
}

// withCommittingAgentTools serves the agent tools beside the organization
// tools, with mode commit over fake and the organizations commit mode's
// content paths.
func withCommittingAgentTools(t *testing.T, f *orgFixture, fake *commit.Fake) {
t.Helper()
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()))
}

// An organization Namespace that a Flux Kustomization applies carries its
// labels, and that Kustomization's target is where the namespace's agents go
// when no agent object names one. The caller here may not get the Namespace,
// which is cluster-scoped, as an organization's members may not: commit mode
// follows the labels that agent-manager's ServiceAccount reads on it, and reads
// the Kustomization as the caller. A caller who may not read it gets an error,
// not the content path; when the labels name the organization's own
// Kustomization, the content path, as for an agent release. A Namespace without
// the labels leaves the first agent to the content path, and a read of the
// Namespace that fails otherwise is an error (giantswarm/agent-manager#498).
func TestCommitFollowsTheFluxLabelsOfAnOrganizationNamespaceTheCallerCannotRead(t *testing.T) {
fleet := commit.Repository{Owner: "giantswarm", Name: "fleet"}
tenants := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "kustomize.toolkit.fluxcd.io/v1", "kind": "Kustomization",
"metadata": map[string]any{"name": "tenants", "namespace": "flux-giantswarm"},
"spec": map[string]any{"path": "./tenants/payments", "prune": true, "sourceRef": map[string]any{"kind": "GitRepository", "name": "fleet"}},
}}
source := &unstructured.Unstructured{Object: map[string]any{
"apiVersion": "source.toolkit.fluxcd.io/v1", "kind": "GitRepository",
"metadata": map[string]any{"name": "fleet", "namespace": "flux-giantswarm"},
"spec": map[string]any{"url": "https://github.com/giantswarm/fleet", "ref": map[string]any{"branch": "main"}},
}}
f, fake := commitFixture(t, nil, ownModel(), orgChartSource(), tenants, source)
fake.AddBranch(fleet, "main", map[string][]byte{"tenants/payments/kustomization.yaml": []byte("resources: []\n")})
withCommittingAgentTools(t, f, fake)
refuseGet := func(resource string, err error) {
f.dyn.PrependReactor("get", resource, func(k8stesting.Action) (bool, runtime.Object, error) { return true, nil, err })
}
refuseGet("namespaces", apierrors.NewForbidden(schema.GroupResource{Resource: "namespaces"}, orgNS, errors.New("RBAC: access denied")))
labelNamespace := func(labels map[string]string) {
ns, err := f.sa.CoreV1().Namespaces().Get(t.Context(), orgNS, metav1.GetOptions{})
require.NoError(t, err)
maps.Copy(ns.Labels, labels)
_, err = f.sa.CoreV1().Namespaces().Update(t.Context(), ns, metav1.UpdateOptions{})
require.NoError(t, err)
}
create := func() (string, bool) {
return f.call(t, ToolCreateAgent, map[string]any{"organization": "payments", "name": "sre", "modelConfig": "own", "toolset": []string{"preset:read-only"}, "mode": "commit", "dryRun": true})
}
target := func() map[string]any {
t.Helper()
text, isErr := create()
require.False(t, isErr, text)
return decode(t, text)["commit"].(map[string]any)
}

got := target()
assert.Equal(t, mcRepo.String(), got["repository"], "a Namespace without Flux labels leaves the first agent to the content path")
assert.Equal(t, paymentsPath+"/agent-manager", got["directory"])

labelNamespace(fromGitLabels("tenants"))
got = target()
assert.Equal(t, fleet.String(), got["repository"])
assert.Equal(t, "tenants/payments/agent-manager", got["directory"])
assert.Equal(t, "flux-giantswarm/tenants", got["kustomization"])

refuseGet("kustomizations", apierrors.NewForbidden(schema.GroupResource{Group: "kustomize.toolkit.fluxcd.io", Resource: "kustomizations"}, "tenants", errors.New("RBAC: access denied")))
text, isErr := create()
require.True(t, isErr, text)
assert.True(t, strings.HasPrefix(text, "forbidden: get Kustomization flux-giantswarm/tenants"), text)

labelNamespace(fromGitLabels(orgNS))
got = target()
assert.Equal(t, mcRepo.String(), got["repository"], "the organization's own Kustomization, which its members may not read, builds the content path")
assert.Equal(t, paymentsPath+"/agent-manager", got["directory"])

refuseGet("namespaces", apierrors.NewInternalError(errors.New("etcd unavailable")))
text, isErr = create()
require.True(t, isErr, text)
assert.Contains(t, text, "get Namespace "+orgNS)
assert.Contains(t, text, "etcd unavailable")
}

// 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
Expand Down
17 changes: 9 additions & 8 deletions internal/organizations/commit.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,22 +227,23 @@ func (c *CommitConfig) contentDir(name string) layout.Directory {
// ContentLocation is where commit mode writes the contents of the
// organization whose namespace ns is: the installation's repository, its
// branch and the organization's content path, as the organization tools
// write them. ok is false without the organizations commit mode, and for a
// namespace that is no organization namespace or does not name its
// organization. The agent tools write an organization's first agent there
// (agents.Config.OrganizationContent).
func (s *Service) ContentLocation(ctx context.Context, ns string) (provenance.Location, bool, error) {
// write them, with the Flux labels of the Namespace, read with
// agent-manager's ServiceAccount. ok is false without the organizations
// commit mode, and for a namespace that is no organization namespace or does
// not name its organization. The agent tools write an organization's first
// agent there (agents.Config.OrganizationContent).
func (s *Service) ContentLocation(ctx context.Context, ns string) (agents.OrganizationNamespace, bool, error) {
if s.cfg.Commit == nil || s.cfg.Namespaces == nil {
return provenance.Location{}, false, nil
return agents.OrganizationNamespace{}, false, nil
}
org, ok, err := s.cfg.Namespaces.Get(ctx, ns)
if err != nil || !ok || org.Organization == "" {
return provenance.Location{}, false, err
return agents.OrganizationNamespace{}, false, err
}
dir := s.cfg.Commit.contentDir(org.Organization)
loc := dir.Location
loc.Directory = dir.Path()
return loc, true, nil
return agents.OrganizationNamespace{Content: loc, NamespaceLabels: org.fluxLabels}, true, nil
}

// contentFile is an object's file in a content path: a Secret in a secret
Expand Down
Loading
Loading