feat(webui): the dashboard reads harness bindings and opens the setup terminal

The harness page lists each credential binding with its captured OAuth
state (expiry, scopes, capture time; never the tokens), and the setup
terminal route upgrades to a WebSocket and bridges it to a harness
session. The session is a narrow webui-owned HarnessTerminal seam: the
container, sandbox network and egress path belong to the daemon, so the
dashboard process cannot implement it and answers 503 until a transport
is wired (archie-core-egkf.7). Opening the terminal authorizes as the
update action on the secret, per the PRD.
This commit is contained in:
sam committed 2026-10-02 09:38:09 +10:00
1 parent c84d0520c8
commit 751d7afb60
6 files changed
+561

No files matched your search

+9
View File
@@ -113,6 +113,15 @@ func compose(d deps) *webui.Server {
if bindings, ok := d.Store.(storecontract.BindingStore); ok {
srv.Bindings = bindings
}
// Harness OAuth token sets are a ratified State Store contract, and the
// same client already carries them. Withholding it would leave the
// harness page answering 503 on a deployment that has the store
// (archie-core-egkf.7). The setup terminal itself is not wired here: its
// implementation owns a container, which this process must not link, so
// the route stays a documented 503 until a daemon-side contract exists.
if secrets, ok := d.Store.(storecontract.HarnessSecretStore); ok {
srv.HarnessSecrets = secrets
}
if eventTypes, ok := d.Store.(storecontract.EventTypeStore); ok {
srv.EventTypes = eventTypes
}
@@ -105,6 +105,19 @@ func TestRoutesWithoutAContractDegradeExplicitly(t *testing.T) {
name: "capture inspector", method: http.MethodGet, path: "/api/captures",
want: http.StatusOK, emptyJSON: `"enabled":true`,
},
{
// The harness page's two routes: the bindings read needs the
// control-plane resource and the setup terminal needs a transport
// this process cannot own. In this composition neither is wired,
// so both degrade explicitly rather than rendering an empty page
// (archie-core-egkf.7).
name: "harness bindings", method: http.MethodGet, path: "/api/harness/bindings",
want: http.StatusServiceUnavailable,
},
{
name: "harness setup terminal", method: http.MethodGet, path: "/api/harness/terminal?profile=claude-kit",
want: http.StatusServiceUnavailable,
},
{
// The browser reads this to decide which sections to show at
// all, so it is the one route that must answer here.
+218
View File
@@ -0,0 +1,218 @@
package webui
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"sort"
"strings"
"time"
"golang.org/x/net/websocket"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
)
// The control-plane resources the harness page reads. The kinds are spelled
// here rather than imported from internal/app/controlplane so the dashboard
// package stays a leaf: api_workflow_enablement.go does the same for
// "workflow-enablement".
const (
harnessBindingsKind = "credential-bindings"
harnessProfilesKind = "agent-profiles"
)
// harnessBindingDoc is the part of one credential-bindings entry
// (controlplane.credentialBinding) this page reads: the service it binds.
// The secret reference is decoded too so a malformed document is rejected
// rather than silently read as service-only, but it is never resolved here.
type harnessBindingDoc struct {
Service string `json:"service"`
Org string `json:"org,omitempty"`
Secret struct {
Engine string `json:"engine,omitempty"`
Key string `json:"key,omitempty"`
} `json:"secret"`
}
// harnessProfileDoc is the part of one agent-profiles entry
// (controlplane.agentProfile) this page reads: the Kit a setup terminal can
// be opened for.
type harnessProfileDoc struct {
Kit string `json:"kit"`
}
// HarnessTerminal opens an ephemeral setup session for one Kit profile: a
// duplex byte stream to the container's PTY, on the same egress path a Kit
// task runs on (docs/prds/external-agent-harness.md, "Setup terminal").
//
// It is a seam, not an implementation. The container, the sandbox network
// and the egress session belong to the daemon, and the dashboard process is
// forbidden from linking them (cmd/archie-ui/architecture_test.go bans
// internal/container, internal/app/archied and internal/agentexec). A
// composition wires whichever transport carries the session; nil answers the
// route 503 rather than pretending a terminal exists. The interface's
// method types are stdlib only, so a future transport that implements it
// cannot drag a banned package into the UI binary.
type HarnessTerminal interface {
Open(ctx context.Context, orgID, profile string) (io.ReadWriteCloser, error)
}
// harnessBindingView is one credential binding as the page renders it: the
// service, whether an OAuth token set has been captured, and that set's
// expiry, scopes and capture time. Access and refresh tokens are never in
// the shape -- the page reports capture state, not credentials.
type harnessBindingView struct {
Service string `json:"service"`
Captured bool `json:"captured"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
UpdatedAt *time.Time `json:"updated_at,omitempty"`
Scopes []string `json:"scopes,omitempty"`
}
// harnessView is the page's whole read: the bindings, the Kit profiles a
// setup terminal can target, and whether this process can open one.
type harnessView struct {
Terminal bool `json:"terminal"`
Bindings []harnessBindingView `json:"bindings"`
Profiles []string `json:"profiles"`
}
// handleHarnessBindings lists the org's credential bindings joined with
// their captured OAuth state. It requires both contracts the join reads: an
// unconfigured process answers 503 rather than rendering a page that claims
// the org has no bindings, which it cannot know.
func (s *Server) handleHarnessBindings(w http.ResponseWriter, r *http.Request) {
if s.ControlPlane == nil || s.HarnessSecrets == nil {
http.Error(w, "harness bindings not configured", http.StatusServiceUnavailable)
return
}
orgID := string(org.OrgFromContext(r.Context()))
bindings, err := s.harnessBindings(r.Context(), orgID)
if err != nil {
s.logf("list harness bindings", "err", err)
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
return
}
profiles, err := s.harnessProfiles(r.Context())
if err != nil {
s.logf("list harness profiles", "err", err)
http.Error(w, "list harness bindings failed", http.StatusBadGateway)
return
}
writeJSON(w, harnessView{Terminal: s.HarnessTerminal != nil, Bindings: bindings, Profiles: profiles})
}
// harnessBindings reads the credential-bindings document and each service's
// captured token state. A service with no captured set is not an error: it
// is exactly the state the setup terminal exists to change.
func (s *Server) harnessBindings(ctx context.Context, orgID string) ([]harnessBindingView, error) {
response, err := s.ControlPlane.Query(ctx, controlplanerpc.QueryRequest(ctx, harnessBindingsKind))
if err != nil {
return nil, err
}
var docs []harnessBindingDoc
if response.Resource != nil && len(response.Resource.ValueJson) > 0 {
if err := json.Unmarshal(response.Resource.ValueJson, &docs); err != nil {
return nil, err
}
}
views := make([]harnessBindingView, 0, len(docs))
for _, doc := range docs {
if strings.TrimSpace(doc.Service) == "" {
continue
}
view := harnessBindingView{Service: doc.Service}
secret, err := s.HarnessSecrets.GetHarnessSecret(ctx, orgID, doc.Service)
switch {
case err == nil:
view.Captured = true
if !secret.ExpiresAt.IsZero() {
expires := secret.ExpiresAt
view.ExpiresAt = &expires
}
if !secret.UpdatedAt.IsZero() {
updated := secret.UpdatedAt
view.UpdatedAt = &updated
}
view.Scopes = secret.Scopes
case errors.Is(err, storecontract.ErrHarnessSecretNotFound):
// Not captured yet: the page shows the binding as unconfigured.
default:
return nil, err
}
views = append(views, view)
}
return views, nil
}
// harnessProfiles returns the agent profiles that name a Kit, sorted so the
// page's list does not depend on Go's map iteration order.
func (s *Server) harnessProfiles(ctx context.Context) ([]string, error) {
response, err := s.ControlPlane.Query(ctx, controlplanerpc.QueryRequest(ctx, harnessProfilesKind))
if err != nil {
return nil, err
}
var docs map[string]harnessProfileDoc
if response.Resource != nil && len(response.Resource.ValueJson) > 0 {
if err := json.Unmarshal(response.Resource.ValueJson, &docs); err != nil {
return nil, err
}
}
profiles := make([]string, 0, len(docs))
for name, doc := range docs {
if strings.TrimSpace(doc.Kit) != "" {
profiles = append(profiles, name)
}
}
sort.Strings(profiles)
return profiles, nil
}
// handleHarnessTerminal upgrades the request to a WebSocket and bridges it to
// a setup session opened for the named Kit profile. Opening the terminal is
// the update action on the secret, decided by the authorizer before this
// handler runs (authorize.go's route override).
func (s *Server) handleHarnessTerminal(w http.ResponseWriter, r *http.Request) {
if s.HarnessTerminal == nil {
http.Error(w, "setup terminal not configured", http.StatusServiceUnavailable)
return
}
if !strings.EqualFold(r.Header.Get("Upgrade"), "websocket") {
http.Error(w, "websocket upgrade required", http.StatusUpgradeRequired)
return
}
profile := strings.TrimSpace(r.URL.Query().Get("profile"))
if profile == "" {
http.Error(w, "profile is required", http.StatusBadRequest)
return
}
session, err := s.HarnessTerminal.Open(r.Context(), string(org.OrgFromContext(r.Context())), profile)
if err != nil {
s.logf("open setup terminal", "err", err, "profile", profile)
http.Error(w, "setup terminal failed", http.StatusBadGateway)
return
}
defer func() { _ = session.Close() }()
websocket.Handler(func(ws *websocket.Conn) {
defer func() { _ = ws.Close() }()
bridgeTerminal(ws, session)
}).ServeHTTP(w, r)
}
// bridgeTerminal pumps bytes between the dashboard WebSocket and the setup
// session until either side closes, then closes both so the surviving copy
// unblocks. It is a free function so a test can drive it without a listener.
func bridgeTerminal(ws *websocket.Conn, session io.ReadWriteCloser) {
done := make(chan struct{}, 2)
go func() { _, _ = io.Copy(session, ws); done <- struct{}{} }()
go func() { _, _ = io.Copy(ws, session); done <- struct{}{} }()
<-done
_ = ws.Close()
_ = session.Close()
<-done
}
+291
View File
@@ -0,0 +1,291 @@
package webui
import (
"context"
"encoding/json"
"errors"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"golang.org/x/net/websocket"
controlpb "github.com/samcharles93/archie-core/internal/contracts/controlplane/v1"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/harnesssecret"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// harnessSecretStub answers the harness store's two methods from a fixed
// map keyed "org/service".
type harnessSecretStub struct {
secrets map[string]harnesssecret.Secret
err error
}
func (s *harnessSecretStub) GetHarnessSecret(_ context.Context, orgID, service string) (harnesssecret.Secret, error) {
if s.err != nil {
return harnesssecret.Secret{}, s.err
}
if secret, ok := s.secrets[orgID+"/"+service]; ok {
return secret, nil
}
return harnesssecret.Secret{}, storecontract.ErrHarnessSecretNotFound
}
func (s *harnessSecretStub) PutHarnessSecret(context.Context, harnesssecret.Secret) error {
return nil
}
// pipeTerminal hands the test the far end of a net.Pipe for every session it
// opens, so the bridge test can drive both directions without a container.
type pipeTerminal struct {
peers chan net.Conn
}
func newPipeTerminal() *pipeTerminal { return &pipeTerminal{peers: make(chan net.Conn, 1)} }
func (p *pipeTerminal) Open(context.Context, string, string) (io.ReadWriteCloser, error) {
client, peer := net.Pipe()
p.peers <- peer
return client, nil
}
type failingTerminal struct{ err error }
func (f failingTerminal) Open(context.Context, string, string) (io.ReadWriteCloser, error) {
return nil, f.err
}
func harnessResources() map[string]*controlpb.Resource {
return map[string]*controlpb.Resource{
harnessBindingsKind: {Kind: harnessBindingsKind, ValueJson: []byte(
`[{"service":"github","secret":{"engine":"env","key":"GH"}},{"service":"linear"}]`,
)},
harnessProfilesKind: {Kind: harnessProfilesKind, ValueJson: []byte(
`{"claude-kit":{"kit":"ghcr.io/x/y@sha256:abc"},"plain":{"image":"x"}}`,
)},
}
}
// TestHarnessBindingsJoinsCaptureState: the page lists every binding and the
// capture state of the ones with a stored token set, and it never carries the
// token itself.
func TestHarnessBindingsJoinsCaptureState(t *testing.T) {
expires := time.Date(2026, 10, 2, 12, 0, 0, 0, time.UTC)
updated := expires.Add(-time.Hour)
secrets := &harnessSecretStub{secrets: map[string]harnesssecret.Secret{
string(org.DefaultOrgID) + "/github": {
Org: string(org.DefaultOrgID), Service: "github", AccessToken: "secret-token",
ExpiresAt: expires, UpdatedAt: updated, Scopes: []string{"repo", "read:org"},
},
}}
srv := &Server{
Log: slog.New(slog.DiscardHandler),
ControlPlane: &controlPlaneClientStub{resources: harnessResources()},
HarnessSecrets: secrets,
}
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/bindings", nil)
response := httptest.NewRecorder()
srv.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, body = %q", response.Code, response.Body.String())
}
var got harnessView
if err := json.Unmarshal(response.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
if got.Terminal {
t.Error("terminal reported available with no HarnessTerminal wired")
}
if len(got.Profiles) != 1 || got.Profiles[0] != "claude-kit" {
t.Fatalf("profiles = %v, want the Kit profile only", got.Profiles)
}
if len(got.Bindings) != 2 {
t.Fatalf("bindings = %+v", got.Bindings)
}
github := got.Bindings[0]
if github.Service != "github" || !github.Captured || github.ExpiresAt == nil || !github.ExpiresAt.Equal(expires) {
t.Fatalf("github binding = %+v", github)
}
if len(github.Scopes) != 2 || github.Scopes[0] != "repo" {
t.Fatalf("scopes = %v", github.Scopes)
}
if linear := got.Bindings[1]; linear.Service != "linear" || linear.Captured {
t.Fatalf("linear binding = %+v, want listed but uncaptured", linear)
}
// The token must not cross the wire in any form.
if body := response.Body.String(); strings.Contains(body, "secret-token") {
t.Fatalf("response leaked the access token: %s", body)
}
}
// TestHarnessBindingsUnavailableWithoutItsContracts: the page needs both the
// control-plane resource and the token store; either missing is a 503, never
// an empty page that reads as "this org has no bindings".
func TestHarnessBindingsUnavailableWithoutItsContracts(t *testing.T) {
cases := []struct {
name string
srv *Server
}{
{"no control plane", &Server{Log: slog.New(slog.DiscardHandler), HarnessSecrets: &harnessSecretStub{}}},
{"no secret store", &Server{Log: slog.New(slog.DiscardHandler), ControlPlane: &controlPlaneClientStub{resources: harnessResources()}}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/bindings", nil)
response := httptest.NewRecorder()
tc.srv.Handler().ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", response.Code)
}
})
}
}
// TestHarnessTerminalUnwiredDegrades503 is the lane's required degrade path:
// with no transport for the session, the route answers 503 and the page can
// say the terminal is unavailable rather than failing a browser upgrade.
func TestHarnessTerminalUnwiredDegrades503(t *testing.T) {
srv := &Server{Log: slog.New(slog.DiscardHandler)}
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/terminal?profile=claude-kit", nil)
request.Header.Set("Upgrade", "websocket")
response := httptest.NewRecorder()
srv.Handler().ServeHTTP(response, request)
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503", response.Code)
}
}
func TestHarnessTerminalRejectsNonUpgradeAndMissingProfile(t *testing.T) {
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: newPipeTerminal()}
cases := []struct {
name string
path string
upgrade bool
want int
}{
{"no upgrade", "/api/harness/terminal?profile=claude-kit", false, http.StatusUpgradeRequired},
{"no profile", "/api/harness/terminal", true, http.StatusBadRequest},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, tc.path, nil)
if tc.upgrade {
request.Header.Set("Upgrade", "websocket")
}
response := httptest.NewRecorder()
srv.Handler().ServeHTTP(response, request)
if response.Code != tc.want {
t.Fatalf("status = %d, want %d", response.Code, tc.want)
}
})
}
}
func TestHarnessTerminalOpenFailureIsBadGateway(t *testing.T) {
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: failingTerminal{err: errors.New("no daemon")}}
request := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/api/harness/terminal?profile=claude-kit", nil)
request.Header.Set("Upgrade", "websocket")
response := httptest.NewRecorder()
srv.Handler().ServeHTTP(response, request)
if response.Code != http.StatusBadGateway {
t.Fatalf("status = %d, want 502", response.Code)
}
}
// TestHarnessTerminalBridgesWebSocketToSession proves the upgrade path moves
// bytes both ways: the WebSocket is a PTY, so what the browser types reaches
// the session and what the session prints reaches the browser.
func TestHarnessTerminalBridgesWebSocketToSession(t *testing.T) {
terminal := newPipeTerminal()
srv := &Server{Log: slog.New(slog.DiscardHandler), HarnessTerminal: terminal}
ts := httptest.NewServer(srv.Handler())
t.Cleanup(ts.Close)
wsURL := "ws" + strings.TrimPrefix(ts.URL, "http") + "/api/harness/terminal?profile=claude-kit"
ws, err := websocket.Dial(wsURL, "", ts.URL)
if err != nil {
t.Fatalf("dial: %v", err)
}
t.Cleanup(func() { _ = ws.Close() })
var peer net.Conn
select {
case peer = <-terminal.peers:
case <-time.After(5 * time.Second):
t.Fatal("the handler never opened a session")
}
t.Cleanup(func() { _ = peer.Close() })
// Session to browser.
go func() { _, _ = peer.Write([]byte("from-session")) }()
got := make([]byte, len("from-session"))
_ = ws.SetReadDeadline(time.Now().Add(5 * time.Second))
if _, err := io.ReadFull(ws, got); err != nil {
t.Fatalf("read from websocket: %v", err)
}
if string(got) != "from-session" {
t.Fatalf("websocket read %q", got)
}
// Browser to session.
typed := make(chan string, 1)
go func() {
buf := make([]byte, len("from-browser"))
if _, err := io.ReadFull(peer, buf); err != nil {
typed <- "ERR:" + err.Error()
return
}
typed <- string(buf)
}()
if _, err := ws.Write([]byte("from-browser")); err != nil {
t.Fatalf("write to websocket: %v", err)
}
select {
case got := <-typed:
if got != "from-browser" {
t.Fatalf("session read %q", got)
}
case <-time.After(5 * time.Second):
t.Fatal("the session never received the browser's input")
}
}
// TestHarnessRoutesAuthorizeAsSecretUpdate pins the route mapping the PRD
// names: opening the terminal is the update action on the secret, and the
// bindings read is a secret read.
func TestHarnessRoutesAuthorizeAsSecretUpdate(t *testing.T) {
cases := []struct {
path string
method string
want access.Action
kind access.ResourceKind
}{
{"/api/harness/terminal", http.MethodGet, access.ActionUpdate, access.KindSecret},
{"/api/harness/bindings", http.MethodGet, access.ActionRead, access.KindSecret},
}
for _, tc := range cases {
request := httptest.NewRequestWithContext(t.Context(), tc.method, tc.path, nil)
action, kind, _ := accessRequest(request)
if action != tc.want || kind != tc.kind {
t.Errorf("%s: got %s/%s, want %s/%s", tc.path, action, kind, tc.want, tc.kind)
}
}
}
+9
View File
@@ -172,6 +172,15 @@ func routeOverride(action access.Action, path string) (access.Action, access.Res
return access.ActionRead, access.KindDashboard, "", true
case matchSegment(path, "/api/sources/", "/secret"):
return access.ActionUpdate, access.KindSecret, segmentValue(path, 2), true
case matchPrefix(path, "/api/harness/terminal"):
// Opening the setup terminal captures the binding's OAuth tokens, so
// it is the update action on the secret
// (docs/prds/external-agent-harness.md, "Setup terminal"). The shipped
// org-owner and org-admin policies grant it; the terminal is
// admin-only.
return access.ActionUpdate, access.KindSecret, "", true
case matchPrefix(path, "/api/harness/bindings"):
return access.ActionRead, access.KindSecret, "", true
case matchPrefix(path, "/api/channels/"):
return actionManage(action), access.KindDashboard, segmentValue(path, 2), true
case matchPrefix(path, "/api/config"), matchPrefix(path, "/api/logs"):
+21
View File
@@ -175,6 +175,21 @@ type Server struct {
// /api/sources route answer 503 and marks no binding unsigned.
Sources storecontract.SourceStore
// HarnessSecrets reads each credential binding's captured OAuth token
// set, so the harness page can report whether a binding is configured,
// when it expires and which scopes it carries
// (docs/prds/external-agent-harness.md, Credentials). The token values
// themselves never reach the browser. Optional: nil answers
// /api/harness/bindings 503 rather than claiming the org has none.
HarnessSecrets storecontract.HarnessSecretStore
// HarnessTerminal opens the setup terminal, a duplex PTY session in an
// ephemeral Kit container (docs/prds/external-agent-harness.md, "Setup
// terminal"). Optional: nil answers /api/harness/terminal 503. The
// implementation belongs to a process that owns containers; the
// dashboard consumes it over a contract and never links one.
HarnessTerminal HarnessTerminal
// TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard-
// initiated update use the same post-restart notification route as a
// Telegram-initiated update. The web UI has no durable chat identity, so
@@ -294,6 +309,11 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
}
func (s *Server) registerHarnessRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/harness/bindings", s.handleHarnessBindings)
mux.HandleFunc("GET /api/harness/terminal", s.handleHarnessTerminal)
}
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/control-plane/catalog", s.handleControlPlaneCatalog)
mux.HandleFunc("GET /api/control-plane/apply-status", s.handleApplyStatus)
@@ -330,6 +350,7 @@ func (s *Server) Handler() http.Handler {
s.registerCoreRoutes(mux)
s.registerTaskRoutes(mux)
s.registerMappingAndBindingRoutes(mux)
s.registerHarnessRoutes(mux)
s.registerConfigAndLogRoutes(mux)
s.registerChatRoutes(mux)