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
39 changes: 33 additions & 6 deletions .github/workflows/mainloop-fork-ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,13 @@ jobs:
env:
GOFLAGS: -p=2
GOMAXPROCS: "2"
SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
KUBECONFIG: /dev/null
steps:
- name: Checkout event source
# Keep the event default: PR merge candidate, push SHA, or dispatch SHA.
- name: Checkout exact source
uses: actions/checkout@v6
with:
ref: ${{ env.SOURCE_SHA }}
persist-credentials: false
- name: Record tested source
env:
Expand All @@ -35,11 +37,11 @@ jobs:
EVENT_SHA: ${{ github.sha }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
run: |
checkout_sha=$(git rev-parse HEAD)
printf 'Event: %s\nRef: %s\nEvent SHA: %s\nCheckout SHA: %s\nPR head SHA: %s\n' \
"$EVENT_NAME" "$SOURCE_REF" "$EVENT_SHA" "$checkout_sha" "$PR_HEAD_SHA" \
checkout_sha=$(git rev-parse --verify HEAD)
test "$checkout_sha" = "$SOURCE_SHA"
printf 'Event: %s\nRef: %s\nSelected source SHA: %s\nCheckout SHA: %s\nEvent SHA: %s\nPR head SHA: %s\n' \
"$EVENT_NAME" "$SOURCE_REF" "$SOURCE_SHA" "$checkout_sha" "$EVENT_SHA" "$PR_HEAD_SHA" \
| tee -a "$GITHUB_STEP_SUMMARY"
test "$checkout_sha" = "$EVENT_SHA"
- name: Set up Go
uses: actions/setup-go@v7
with:
Expand All @@ -49,3 +51,28 @@ jobs:
run: go test ./core/internal/controller/chatgptrefresh -count=1 -timeout=180s
- name: Vet refresh package
run: go vet ./core/internal/controller/chatgptrefresh
- name: Record bounded offline scope
run: |
printf '%s\n' \
'Runtime tests use isolated testcontainers PostgreSQL and fake Actor/gateway/native effects.' \
'Deferred: TestSandboxTemplateCatalog requires local Kubernetes envtest assets; handler/control/runtime tests still run.' \
'Deferred: TestPinnedCodexAcceptsGeneratedConfiguration launches the real Codex CLI/app-server; fake native consumer tests still run.' \
'No provider credentials, native agents, cluster operations, image publication or rollout.' \
| tee -a "$GITHUB_STEP_SUMMARY"
- name: Test runtime capability and policy fixtures
run: go test -count=1 ./adk/pkg/taskstore ./core/internal/egress ./core/internal/substrate ./core/internal/service/taskstore
- name: Test PostgreSQL lifecycle, callbacks and control authentication
# No -short: migration Up/Down, inline SQL, issuance and revocation must run.
# Exclude only the unrelated envtest catalog, never runtime identity tests.
run: >-
go test -race -count=1 -skip '^TestSandboxTemplateCatalog$'
./core/internal/database ./core/pkg/migrations
./core/internal/service/session ./core/internal/service/checkpoint
./core/internal/grpcserver ./core/internal/httpserver/auth ./core/pkg/auth
- name: Test fake native consumers
# The explicit real-CLI deferral is recorded above; no native agent starts.
run: >-
go test -count=1 -skip '^TestPinnedCodexAcceptsGeneratedConfiguration$'
./harness/runtime/workspace ./harness/claude/... ./harness/codex/...
- name: Build controller and native consumers
run: go build ./core/pkg/app ./harness/claude/cmd ./harness/codex/cmd
96 changes: 96 additions & 0 deletions docs/architecture/runtime-generation-identity.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
# Runtime generation capability identity

TaskStore authenticates a hidden per-generation capability, independent of the
control service bearer. The actor sends `x-kagent-runtime-token:
gateway-injection-required`; the trusted gateway replaces that placeholder with
a 256-bit random token from an immutable Kubernetes Secret. Projected name/UID
files are routing hints, never authentication. All six RPCs require one canonical
64-character lowercase hexadecimal header, an active server-side digest binding,
a fresh uncached Substrate Actor read with matching name/atespace/UID and RUNNING
state, and request Session/task ownership. Control credentials and unsigned actor
metadata are refused. Runtime headers cannot authorize control APIs.

## Durable identity and creation

New Session inserts mark generation eligibility. Migration leaves existing rows
ineligible; a current UID lookup cannot enroll them. No legacy names are accepted
by the SDK. The private ledger permanently reserves a random generation actor
name (`session-<Session UUID>-<16 random hex characters>`) and immutable credential
URI before external effects. Records have no cascading Session foreign key.
Revocation retains names, URIs and digests; garbage collection must never remove
these reservations. Ledger backups and restore/reconciliation are security state.

Creation proceeds through allocated, secret-issued, actor-issued, bound and
active phases. Secret plaintext exists transiently in the trusted controller and
private immutable Secret, never actor environment/files, revision payloads,
public Session responses or snapshots. Only the original allocation can create
its Secret. A lost Secret reply is reconciled by uncached lookup, immutable flag,
generation labels and original digest. Missing original material holds issuance;
retries never rotate identity or overwrite/adopt a foreign Secret.

Actor issuance is recorded before CreateActor/CreateActorFromTag. Creation is
suspended, and only a successful response carrying the exact identity and DATA
snapshot (when applicable) can pin its first UID. An unknown Actor creation
outcome remains held as actor-issued. Even a matching current name/template is
insufficient for adoption. Policy installation precedes active authority. A
retry of a bound generation requires its pinned UID; policy equality is checked
by the existing immutable-policy mechanism. First creation remains suspended,
as before; same-UID lifecycle resume verifies private credential availability
and the exact immutable policy plus active database binding before applying
runtime effects. Actor UID changes or missing Actors hold the
original generation; no replacement token is issued under its old name.

The controller revokes database authority before managed Actor deletion, then
cleans up the Secret. Substrate owns policy cleanup with Actor deletion. A
post-cutover DATA fork creates a new Session and ledger-issued name/URI/token;
source authority is never inherited. A fresh eligible Session deleted before
ledger allocation can complete database-only deletion; it has issued no runtime
effects. Unledgered pre-cutover rows have no such provenance. Resume preserves the same UID/generation.
There is no automatic same-Session Actor replacement, old-session migration,
legacy enrollment or Full process-memory restore. Quiescence/checkpoint creation
requires DATA state. An uncertain original issuance is deliberately unavailable
until separately reviewed reconciliation; source preparation does not add an
operator recovery/adoption API.

## Callback transaction and policy boundary

The owning service observes Substrate before any database transaction. The store
then locks Session followed by generation, verifies the current active binding,
and runs database-only callback operations in that same transaction. Nested task
operations use savepoints and cannot escape to a pool. Revocation takes the same
lock order. No external call occurs under these locks. A request already admitted
can finish concurrently with external Substrate deletion; this is not atomic
cross-system deletion or process-activation attestation. Every later request
performs another fresh fail-closed UID/state read.

User egress credentials cannot select the reserved header or `kagent-runtime-`
Secret reference class, including URL-encoded references. The trusted policy
builder reserves the callback hostname exclusively for runtime injection and
refuses alternate ports/schemes or any user credentials on it. Its only injection
rule uses the controller's exact existing callback origin. Both native Claude
and Codex already use the shared Go TaskStore adapter for boot GetWorkspace and
subsequent callbacks, so the adapter supplies the mandatory placeholder to both.

## Installation and qualification

Ephemeral runtime injection Secrets use the controller resource namespace and
labels `kagent.dev/runtime-injection=true` and
`kagent.dev/runtime-generation=<generation UUID>`. The chart adds a namespaced
get/create/delete Secret Role for the controller. Kubernetes RBAC cannot express
label-based Secret authorization; existing broader grants are not narrowed here.
Installation must separately constrain credential-provider namespace/labels,
remove overlapping grants and exclude actor access to provider/mint/Kubernetes
APIs. Ephemeral Secrets must remain outside GitOps managed inventory. No live
Secret creation, image publication, pins or cluster qualification is performed
by this source change.

The callback remains the existing HTTP controller origin on port 8083. This
slice does not separate listeners or claim an encrypted gateway-to-controller
hop; it retains the trusted-cluster transport assumption pending listener/TLS
cutover. The controller must own this hostname and expose no credential reflection
or arbitrary forwarding receiver. Reserved-origin source checks and fakes do not
prove deployed isolation, cache/tunnel behavior or controller/network exclusivity.
The old Python TaskStore adapter is not migrated by this native-harness slice and
cannot use unsigned authentication. It needs a separately scoped consumer update
before it can operate against this admission contract. The optional unsigned
Python callback probe is removed from the Go gRPC fixture accordingly.
2 changes: 1 addition & 1 deletion go/adk/pkg/taskstore/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ func TestSettlementFlushesFinalSaveAndSettlement(t *testing.T) {
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, client.Close()) })
dir := t.TempDir()
for field, value := range map[string]string{"name": "session-" + uuid.NewString(), "atespace": "team-a", "uid": "actor-uid"} {
for field, value := range map[string]string{"name": "session-" + uuid.NewString() + "-0123456789abcdef", "atespace": "team-a", "uid": "actor-uid"} {
require.NoError(t, os.WriteFile(filepath.Join(dir, field), []byte(value), 0o600))
}
store := New(client, filepath.Join(dir, "name"))
Expand Down
52 changes: 52 additions & 0 deletions go/adk/pkg/taskstore/identity_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package taskstore

import (
"os"
"path/filepath"
"testing"

"github.com/google/uuid"
"github.com/kagent-dev/kagent/go/adk/pkg/controllerclient"
"github.com/stretchr/testify/require"
"google.golang.org/grpc/metadata"
)

func TestGenerationRoutingHintRejectsLegacyAndMalformedNames(t *testing.T) {
id := uuid.NewString()
for _, test := range []struct {
name string
valid bool
}{
{"session-" + id + "-0123456789abcdef", true},
{"session-" + id, false}, {"session-" + id + "-0123456789abcdeg", false},
{"session-" + id + "-0123456789ABCDEF", false}, {"session-invalid-0123456789abcdef", false},
} {
t.Run(test.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "name")
require.NoError(t, os.WriteFile(path, []byte(test.name), 0600))
got, err := New(nil, path).sessionID()
if test.valid {
require.NoError(t, err)
require.Equal(t, id, got)
} else {
require.Error(t, err)
}
})
}
}

func TestCallbackContextRequiresNonsecretGatewayPlaceholder(t *testing.T) {
controller, err := controllerclient.New(controllerclient.Config{APIURL: "http://controller.invalid"})
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, controller.Close()) })
// No projection fields or token files are read by the callback contract.
store := New(controller, filepath.Join(t.TempDir(), "missing-name"))
parent := metadata.NewOutgoingContext(t.Context(), metadata.Pairs("authorization", "Bearer control", "x-kagent-runtime-token", "forged", "x-kagent-insecure-runtime-identity", "forged"))
ctx, cancel, err := store.callContext(parent)
require.NoError(t, err)
defer cancel()
md, _ := metadata.FromOutgoingContext(ctx)
require.Equal(t, []string{RuntimeTokenPlaceholder}, md.Get(RuntimeTokenHeader))
require.Empty(t, md.Get("authorization"))
require.Empty(t, md.Get("x-kagent-insecure-runtime-identity"))
}
37 changes: 19 additions & 18 deletions go/adk/pkg/taskstore/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ package taskstore

import (
"context"
"encoding/hex"
"fmt"
"os"
"path/filepath"
"strings"
"time"

Expand All @@ -22,6 +22,9 @@ import (
"google.golang.org/grpc/status"
)

const RuntimeTokenHeader = "x-kagent-runtime-token"
const RuntimeTokenPlaceholder = "gateway-injection-required"

type Store struct {
client *controllerclient.Client
identityPath string
Expand All @@ -38,12 +41,18 @@ func (s *Store) sessionID() (string, error) {
if err != nil {
return "", fmt.Errorf("read runtime identity: %w", err)
}
id, ok := strings.CutPrefix(strings.TrimSpace(string(identity)), "session-")
if !ok {
return "", fmt.Errorf("unexpected runtime actor name")
name := strings.TrimSpace(string(identity))
if len(name) != 61 || !strings.HasPrefix(name, "session-") || name[44] != '-' {
return "", fmt.Errorf("unexpected runtime generation name")
}
id := name[8:44]
parsed, err := uuid.Parse(id)
if err != nil || parsed.String() != id {
return "", fmt.Errorf("invalid runtime session hint")
}
if _, err := uuid.Parse(id); err != nil {
return "", fmt.Errorf("invalid runtime session identity: %w", err)
suffix, err := hex.DecodeString(name[45:])
if err != nil || len(suffix) != 8 || hex.EncodeToString(suffix) != name[45:] {
return "", fmt.Errorf("invalid runtime generation hint")
}
return id, nil
}
Expand All @@ -56,18 +65,10 @@ func (s *Store) callContext(ctx context.Context) (context.Context, context.Cance
md.Delete("x-user-id")
md.Delete("x-agent-name")
md.Delete("x-share-token")
// Temporary identity transport until Substrate injects actor credentials (#1660).
// Reread on every call because restore rebinds these files to the new actor.
var identity []string
for _, field := range []string{"atespace", "name", "uid"} {
value, err := os.ReadFile(filepath.Join(filepath.Dir(s.identityPath), field))
if err != nil {
cancel()
return nil, nil, fmt.Errorf("read runtime identity %s: %w", field, err)
}
identity = append(identity, strings.TrimSpace(string(value)))
}
md.Set(apia2a.InsecureRuntimeIdentityHeader, strings.Join(identity, "/"))
// The gateway replaces this nonsecret placeholder. Unsigned projection
// files supply routing hints only and are never proof of runtime authority.
md.Delete(apia2a.InsecureRuntimeIdentityHeader)
md.Set(RuntimeTokenHeader, RuntimeTokenPlaceholder)
return metadata.NewOutgoingContext(ctx, md), cancel, nil
}

Expand Down
8 changes: 7 additions & 1 deletion go/core/internal/database/client_postgres.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,13 @@ import (
// Client persists control-plane state in PostgreSQL. Callers define the narrow
// interfaces they need; SQL rows and protobuf encoding stay inside the store.
type Client struct {
db *pgxpool.Pool
db transactionalDB
}

type transactionalDB interface {
dbExecutor
Begin(context.Context) (pgx.Tx, error)
BeginTx(context.Context, pgx.TxOptions) (pgx.Tx, error)
}

// NewClient wraps an existing PostgreSQL pool without connecting or migrating. The caller
Expand Down
Loading
Loading