diff --git a/README.md b/README.md index 8fc5933..a642684 100644 --- a/README.md +++ b/README.md @@ -52,3 +52,9 @@ If creating the session itself fails ambiguously (a lost response, say), it may Both operators must be installed; this library depends on neither and only handles the objects as unstructured. The tunnel exposes the agent's Service, not one session, so it gives no per-session isolation. + +## Trying it on a cluster + +`examples/smoke` is a small program that exposes one session and prints the URL, and +`docs/smoke-test.md` is the checklist for running both operators and this client together for the +first time. diff --git a/docs/smoke-test.md b/docs/smoke-test.md new file mode 100644 index 0000000..0fd9201 --- /dev/null +++ b/docs/smoke-test.md @@ -0,0 +1,89 @@ +# Smoke test: both operators and the client on a real cluster + +Nothing in these three repositories has yet been run end to end. This is the checklist for the first +run. It is written from the repositories' Makefiles and READMEs, not from a run, so fix it where the +real behaviour differs. + +You need a cluster, `kubectl`, the `kustomize` CLI, a container registry, and a Cloudflare account +with a zone you control (API token with Tunnel, DNS and Access edit permissions). + +## 1. Install the operators + +**ai-agent-edge-tunnel** (see its README for the namespace-scoped variant): + +```bash +kubectl create namespace edge-tunnel-system +kubectl -n edge-tunnel-system create secret generic edge-tunnel-cloudflare \ + --from-literal=account-id=... --from-literal=api-token=... +kubectl -n edge-tunnel-system create configmap edge-tunnel-config \ + --from-literal=EDGE_BASE_DOMAIN=agents.example.com \ + --from-literal=CONNECTOR_IMAGE= +make docker-build IMG=/ai-agent-edge-tunnel: # push it too +make deploy IMG=/ai-agent-edge-tunnel: +``` + +**agentops-operator**: + +```bash +make docker-build IMG=/agentops-operator: # push it too +make install # CRDs +make deploy IMG=/agentops-operator: +``` + +Then create an agent the sessions can bind to (`make docker-build-agent` builds a reference echo +agent). Use the AgentRuntime, AgentService and AgentPool samples in `config/samples/`; the pool's +selector label is `agents.steadyinfra.com/pool`. Check the pool has a ready replica before going on. + +## 2. Expose a session + +```bash +go run ./examples/smoke -namespace -name smoke -pool \ + -zone-id -email you@example.com +``` + +The command blocks and keeps the session open. Leave it running in this terminal and run the checks +below from a second one. Press Ctrl-C in the first terminal only after they finish: it completes the +session and starts tunnel teardown. + +If the endpoint is not ready within `-timeout` (default 3 minutes) the command ends the session and +exits with an error. Delete any leftover `agentsession` and `agentedgetunnel` named `smoke`, then rerun +with a longer `-timeout` (for example `-timeout 10m`). `-keep` leaves the session running on exit. + +Expected, in order: + +1. The program prints the session UID. +2. `kubectl -n get agentsession smoke -o yaml` reaches `Bound` and has `status.endpoint`. +3. `kubectl -n get agentedgetunnel smoke -o yaml` shows `status.sessionUID` and `status.sessionEndpoint` + recorded, then `phase: Active` and a connector that is ready. +4. The program prints `https://smoke.`. Opening it asks for a Cloudflare Access + login; only the allowed email gets through. The reference echo agent does not serve `GET /`, so + a 404 after login is expected. To see the agent answer, send `POST /v1/chat` with + `{"message": "hello"}` as the logged-in user, for example with `fetch` from the browser console + on that page. + +## 3. Things worth checking on purpose + +- **Ending the session ends the tunnel.** Press Ctrl-C (or `kubectl -n patch agentsession smoke --type + merge -p '{"spec":{"completed":true}}'`). Within about 10 seconds plus reconcile time the tunnel + goes `Terminated`, and the connector Deployment, DNS record, Access application and Cloudflare tunnel + are gone. Look in the Cloudflare dashboard, not only in the cluster. +- **Fresh exposure per destructive check.** Once a tunnel is `Terminated` it stays terminated. Before + each of the next two checks, repeat the command in section 2 with a new `-name` (it is also the + subdomain), wait for the tunnel to be `Active`, and do not press Ctrl-C. +- **Deleting the session** does the same, and the tunnel also has an ownerReference to it. +- **Order independence.** Apply the tunnel before the session (with `kubectl`, not the client); it + should wait, not fail. +- **Public by omission is refused.** An `AgentEdgeTunnel` with neither `allowedEmails` nor + `allowPublic` must be rejected by the API server. +- **Re-binding terminates.** If the session's `status.endpoint` changes, the tunnel ends instead of + being re-pointed. +- **Leaks.** After all of the above, list tunnels, DNS records and Access applications in Cloudflare + and confirm nothing from the test remains. Known gap: a crash between creating a Cloudflare resource + and recording its ID can orphan it (edge-tunnel issue #4). + +## 4. Clean up + +```bash +kubectl -n delete agentsession smoke --ignore-not-found +make undeploy # in each operator repository; the edge one also removes its AgentEdgeTunnels +``` diff --git a/examples/smoke/main.go b/examples/smoke/main.go new file mode 100644 index 0000000..304ddb6 --- /dev/null +++ b/examples/smoke/main.go @@ -0,0 +1,91 @@ +// Command smoke exposes one agent session through Cloudflare and prints the +// URL, for checking both operators together on a real cluster. See +// docs/smoke-test.md. It ends the session on exit unless -keep is set. +package main + +import ( + "context" + "errors" + "flag" + "fmt" + "os" + "os/signal" + "strings" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "sigs.k8s.io/controller-runtime/pkg/client" + "sigs.k8s.io/controller-runtime/pkg/client/config" + + agentops "github.com/SteadyInfraTech/agentops-client" +) + +func main() { + var ( + ns = flag.String("namespace", "default", "namespace for both objects") + name = flag.String("name", "smoke", "name of the session and tunnel, also used as the subdomain") + pool = flag.String("pool", "", "AgentPool name (set exactly one of -pool and -agent-service)") + svc = flag.String("agent-service", "", "AgentService name") + zone = flag.String("zone-id", "", "Cloudflare zone ID") + email = flag.String("email", "", "email allowed through Cloudflare Access") + timeout = flag.Duration("timeout", 3*time.Minute, "how long to wait for the endpoint") + keep = flag.Bool("keep", false, "leave the session running on exit") + ) + flag.Parse() + if *email == "" || *zone == "" { + fmt.Fprintln(os.Stderr, "error: -email and -zone-id are required") + os.Exit(2) + } + if err := run(*ns, *name, *pool, *svc, *zone, *email, *timeout, *keep); err != nil { + fmt.Fprintln(os.Stderr, "error:", err) + os.Exit(1) + } +} + +// run exposes the session, waits for the endpoint and, unless keep is set, +// ends the session when interrupted. +func run(ns, name, pool, svc, zone, email string, timeout time.Duration, keep bool) error { + cfg, err := config.GetConfig() + if err != nil { + return err + } + c, err := client.New(cfg, client.Options{Scheme: runtime.NewScheme()}) + if err != nil { + return err + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt) + defer stop() + + ex, err := agentops.Expose(ctx, c, agentops.ExposeRequest{ + Namespace: ns, Name: name, PoolName: pool, AgentServiceName: svc, + ZoneID: zone, Subdomain: strings.ToLower(name), AllowedEmails: []string{email}, + }) + if err != nil { + return err + } + fmt.Printf("created session and tunnel %s/%s (session uid %s)\n", ns, name, ex.SessionUID) + + cleanup := func(cause error) error { + if keep { + return cause + } + cctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 15*time.Second) + defer cancel() + if cerr := agentops.Complete(cctx, c, ex); cerr != nil { + return errors.Join(cause, fmt.Errorf("completing session %s (uid %s): %w", name, ex.SessionUID, cerr)) + } + return cause + } + + ep, err := agentops.Wait(ctx, c, ex, agentops.WaitOptions{Timeout: timeout}) + if err != nil { + return cleanup(err) + } + fmt.Println("endpoint:", ep.URL) + if keep { + return nil + } + fmt.Println("press Ctrl-C to end the session") + <-ctx.Done() + return cleanup(nil) +} diff --git a/go.mod b/go.mod index 3b56522..b66b787 100644 --- a/go.mod +++ b/go.mod @@ -21,6 +21,7 @@ require ( github.com/google/gnostic-models v0.6.8 // indirect github.com/google/gofuzz v1.2.0 // indirect github.com/google/uuid v1.3.0 // indirect + github.com/imdario/mergo v0.3.6 // indirect github.com/josharian/intern v1.0.0 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/mailru/easyjson v0.7.7 // indirect @@ -28,6 +29,7 @@ require ( github.com/modern-go/reflect2 v1.0.2 // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/spf13/pflag v1.0.5 // indirect github.com/stretchr/testify v1.10.0 // indirect golang.org/x/net v0.34.0 // indirect golang.org/x/oauth2 v0.12.0 // indirect