diff --git a/internal/app/archie/run.go b/internal/app/archie/run.go index 69d495f8f..30f42303e 100644 --- a/internal/app/archie/run.go +++ b/internal/app/archie/run.go @@ -111,7 +111,11 @@ func Run(ctx context.Context, configPath string) error { if err := useWorkflows(ctx, engine, runs.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Notifier: tell, Memory: remember}); err != nil { return err } - talk.Use(chat.Deps{Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Memory: remember, Runs: engine, Notifier: tell}) + access, err := startAccess(ctx, log, settings) + if err != nil { + return err + } + talk.Use(chat.Deps{People: settings, Access: access, Settings: settings, Toolbox: conns, Judge: judge, Approver: allow, Memory: remember, Runs: engine, Notifier: tell}) apiModules{ settings: settings, conns: conns, system: sys, tell: tell, allow: allow, classes: classes, policies: policies, hear: hear, judge: judge, engine: engine, chat: talk, drafts: drafts.NewModule(db, log.With("module", "drafts"), orgID, hear, engine, policies), @@ -186,6 +190,15 @@ func newJudgement(db *sqlx.DB, log *slog.Logger, conns *connectors.Module, class return judge } +// startAccess seeds the operating org's shipped role policies and returns the +// access policy chain, kept current as policies change. +func startAccess(ctx context.Context, log *slog.Logger, settings *governance.Module) (*governance.Live, error) { + if err := settings.EnsureShippedOrgPolicies(ctx, governance.DefaultOrgID); err != nil { + return nil, fmt.Errorf("seed the role policies: %w", err) + } + return governance.StartLive(ctx, settings.ListPolicies, settings.PoliciesVersion, log.With("module", "governance")), nil +} + // orgID is the one organisation until hosting is multi-tenant. const orgID = "default" diff --git a/internal/platform/pg/migrations/00038_chat_session_owner.sql b/internal/platform/pg/migrations/00038_chat_session_owner.sql new file mode 100644 index 000000000..c5b8fa9ad --- /dev/null +++ b/internal/platform/pg/migrations/00038_chat_session_owner.sql @@ -0,0 +1,15 @@ +-- +goose Up +-- A conversation belongs to the person who started it, and its turns act with +-- that person's access. Conversations from before ownership were the shared +-- administrator's, so they go to the system identity the admin token acts as. +ALTER TABLE chat.sessions ADD COLUMN owner_id text; +UPDATE chat.sessions SET owner_id = '00000000-0000-5000-8000-000000000001'; +ALTER TABLE chat.sessions ALTER COLUMN owner_id SET NOT NULL; + +DROP INDEX chat.sessions_by_org; +CREATE INDEX sessions_by_owner ON chat.sessions (org_id, owner_id, updated_at DESC); + +-- +goose Down +DROP INDEX chat.sessions_by_owner; +CREATE INDEX sessions_by_org ON chat.sessions (org_id, updated_at DESC); +ALTER TABLE chat.sessions DROP COLUMN owner_id; diff --git a/modules/chat/access_test.go b/modules/chat/access_test.go new file mode 100644 index 000000000..a43628f1e --- /dev/null +++ b/modules/chat/access_test.go @@ -0,0 +1,307 @@ +package chat + +import ( + "context" + "encoding/json/jsontext" + "errors" + "io" + "log/slog" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/google/uuid" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/internal/platform/hub" + "github.com/samcharles93/archie-core/modules/chat/internal/store" + "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/governance" + "github.com/samcharles93/archie-core/modules/judgement" + "github.com/samcharles93/archie-core/modules/memory" +) + +const ( + alice = "alice" + bob = "bob" +) + +// person is a principal holding role in the operating org. +func person(id string, role governance.Role) governance.Principal { + return governance.Principal{ + IdentityID: governance.IdentityID(id), Org: governance.DefaultOrgID, + Memberships: []governance.Membership{{IdentityID: governance.IdentityID(id), OrgID: governance.DefaultOrgID, Role: role}}, + } +} + +// TestConversationsBelongToTheirOwner guards the chat API's ownership +// boundary: a person reads and continues their own conversations, and every +// chat route answers anyone else as if the conversation did not exist. +func TestConversationsBelongToTheirOwner(t *testing.T) { + session, turn := uuid.New(), uuid.New() + cases := []struct { + name, method, path, body string + ok int + }{ + {"rename", http.MethodPatch, "/api/chat/sessions/" + session.String(), `{"title":"mine"}`, http.StatusOK}, + {"list turns", http.MethodGet, "/api/chat/sessions/" + session.String() + "/turns", "", http.StatusOK}, + {"send", http.MethodPost, "/api/chat/sessions/" + session.String() + "/turns", `{"text":"hello"}`, http.StatusAccepted}, + {"get turn", http.MethodGet, "/api/chat/turns/" + turn.String(), "", http.StatusOK}, + {"cancel", http.MethodPost, "/api/chat/turns/" + turn.String() + "/cancel", "", http.StatusOK}, + {"stream", http.MethodGet, "/api/chat/turns/" + turn.String() + "/events", "", http.StatusOK}, + {"delete", http.MethodDelete, "/api/chat/sessions/" + session.String(), "", http.StatusNoContent}, + } + for _, tc := range cases { + for _, as := range []string{alice, bob} { + t.Run(tc.name+" as "+as, func(t *testing.T) { + srv := chatServer(t, session, turn) + want := tc.ok + if as != alice { + want = http.StatusNotFound + } + if got, _ := call(t, srv, as, tc.method, tc.path, tc.body); got != want { + t.Fatalf("%s %s as %s = %d, want %d", tc.method, tc.path, as, got, want) + } + }) + } + } + t.Run("list sessions", func(t *testing.T) { + srv := chatServer(t, session, turn) + for as, sees := range map[string]bool{alice: true, bob: false} { + code, body := call(t, srv, as, http.MethodGet, "/api/chat/sessions", "") + if code != http.StatusOK || strings.Contains(body, session.String()) != sees { + t.Fatalf("list as %s = %d %s, want it to show the conversation: %v", as, code, body, sees) + } + } + }) +} + +// TestTurnActsWithItsOwnersAccess guards the tool boundary: the same tool +// call runs in an administrator's conversation and is refused in a viewer's, +// so the agent never reaches further than the person chatting. +func TestTurnActsWithItsOwnersAccess(t *testing.T) { + people := fakePeople{alice: person(alice, governance.RoleAdmin), bob: person(bob, governance.RoleViewer)} + d := Deps{ + People: people, Access: governance.NewEngine(governance.ShippedOrgPolicies(governance.DefaultOrgID)), + Toolbox: fakeToolbox{}, Judge: fakeJudge{}, Memory: fakeMemory{}, + } + m := &Module{orgID: "default", log: slog.New(slog.DiscardHandler), hub: hub.New()} + action := connectors.Declaration{Connector: "pager", Kind: connectors.KindAction, Name: "page"} + lookup := connectors.Declaration{Connector: "pager", Kind: connectors.KindLookup, Name: "who"} + cases := []struct { + name, owner string + run func(context.Context) error + allowed bool + }{ + {"admin runs an action", alice, callTool(m, d, action), true}, + {"viewer can't run an action", bob, callTool(m, d, action), false}, + {"viewer looks up", bob, callTool(m, d, lookup), true}, + {"admin saves a memory", alice, builtin(m, d, "memory_save"), true}, + {"viewer can't save a memory", bob, builtin(m, d, "memory_save"), false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + ctx, err := m.actingAs(t.Context(), d, tc.owner) + if err != nil { + t.Fatal(err) + } + if err := tc.run(ctx); (err == nil) != tc.allowed { + t.Fatalf("allowed = %v (err %v), want %v", err == nil, err, tc.allowed) + } + }) + } +} + +func callTool(m *Module, d Deps, decl connectors.Declaration) func(context.Context) error { + return func(ctx context.Context) error { + _, err := m.call(ctx, d, store.Turn{ID: uuid.New()}, decl, jsontext.Value(`{}`)) + return err + } +} + +func builtin(m *Module, d Deps, name string) func(context.Context) error { + return func(ctx context.Context) error { + for _, tool := range m.builtins(d, store.Turn{ID: uuid.New()}) { + if tool.Name == name { + _, err := tool.Execute(ctx, `{"text":"a fact"}`) + return err + } + } + return errors.New("no tool " + name) + } +} + +// chatServer serves the chat API over a store holding one finished turn in a +// conversation alice owns. The X-As header names who calls. +func chatServer(t *testing.T, session, turn uuid.UUID) *httptest.Server { + t.Helper() + fs := &fakeStore{ + sessions: map[uuid.UUID]store.Session{session: {ID: session, Owner: alice}}, + turns: map[uuid.UUID]store.Turn{turn: {ID: turn, SessionID: session, Owner: alice, State: stateSucceeded}}, + events: map[uuid.UUID][]store.Event{turn: {{Seq: 1, TurnID: turn, Kind: kindDone, Data: jsontext.Value(`{}`)}}}, + } + m := &Module{ + orgID: "default", store: fs, log: slog.New(slog.DiscardHandler), hub: hub.New(), + wake: make(chan struct{}, 1), running: map[uuid.UUID]context.CancelFunc{}, + } + mux := http.NewServeMux() + m.Register(httpapi.New(mux, "test", headerAuth{})) + srv := httptest.NewServer(mux) + t.Cleanup(srv.Close) + return srv +} + +func call(t *testing.T, srv *httptest.Server, as, method, path, body string) (int, string) { + t.Helper() + req, err := http.NewRequestWithContext(t.Context(), method, srv.URL+path, strings.NewReader(body)) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-As", as) + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = res.Body.Close() }() + out, _ := io.ReadAll(res.Body) + return res.StatusCode, string(out) +} + +// headerAuth signs in whoever the X-As header names, as a viewer. +type headerAuth struct{} + +func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) { + as := r.Header.Get("X-As") + if as == "" { + return nil, false, httpapi.ErrUnauthenticated + } + return governance.WithPrincipal(ctx, person(as, governance.RoleViewer)), false, nil +} + +type fakePeople map[string]governance.Principal + +func (f fakePeople) PrincipalFor(_ context.Context, id governance.IdentityID) (governance.Principal, error) { + p, ok := f[string(id)] + if !ok { + return governance.Principal{}, errors.New("no such person") + } + return p, nil +} + +type fakeToolbox struct{ Toolbox } + +func (fakeToolbox) Tool(string) (connectors.Tool, bool) { return fakeTool{}, true } + +type fakeTool struct{ connectors.Tool } + +func (fakeTool) Lookup(context.Context, string, jsontext.Value) (string, bool, error) { + return "someone", true, nil +} + +type fakeJudge struct{ Judge } + +func (fakeJudge) Assess(_ context.Context, req judgement.Request) (judgement.Decision, error) { + return judgement.Decision{Key: req.Key, Level: judgement.ActQuietly}, nil +} + +func (fakeJudge) Execute(context.Context, judgement.Decision, jsontext.Value, string) (string, error) { + return "ran", nil +} + +type fakeMemory struct{ Memory } + +func (fakeMemory) Remember(context.Context, string) (memory.Note, error) { return memory.Note{}, nil } + +// fakeStore keeps conversations in memory with the store's ownership rule: +// a read or change for an owner finds only that owner's conversations. +type fakeStore struct { + conversations + sessions map[uuid.UUID]store.Session + turns map[uuid.UUID]store.Turn + events map[uuid.UUID][]store.Event +} + +func (f *fakeStore) Sessions(_ context.Context, _, owner string, _ int) ([]store.Session, error) { + var out []store.Session + for _, s := range f.sessions { + if s.Owner == owner { + out = append(out, s) + } + } + return out, nil +} + +func (f *fakeStore) Session(_ context.Context, _, owner string, id uuid.UUID) (store.Session, error) { + s, ok := f.sessions[id] + if !ok || s.Owner != owner { + return store.Session{}, store.ErrNotFound + } + return s, nil +} + +func (f *fakeStore) Rename(ctx context.Context, org, owner string, id uuid.UUID, title string) error { + s, err := f.Session(ctx, org, owner, id) + if err == nil { + s.Title = title + f.sessions[id] = s + } + return err +} + +func (f *fakeStore) DeleteSession(ctx context.Context, org, owner string, id uuid.UUID) error { + if _, err := f.Session(ctx, org, owner, id); err != nil { + return err + } + delete(f.sessions, id) + return nil +} + +func (f *fakeStore) AddTurn(ctx context.Context, org, owner string, t store.Turn) (store.Turn, error) { + if _, err := f.Session(ctx, org, owner, t.SessionID); err != nil { + return store.Turn{}, err + } + t.Owner, t.State = owner, stateQueued + f.turns[t.ID] = t + return t, nil +} + +func (f *fakeStore) Turns(_ context.Context, _, owner string, session uuid.UUID) ([]store.Turn, error) { + var out []store.Turn + for _, t := range f.turns { + if t.SessionID == session && t.Owner == owner { + out = append(out, t) + } + } + return out, nil +} + +func (f *fakeStore) Turn(_ context.Context, _, owner string, id uuid.UUID) (store.Turn, error) { + t, ok := f.turns[id] + if !ok || t.Owner != owner { + return store.Turn{}, store.ErrNotFound + } + return t, nil +} + +func (f *fakeStore) RequestCancel(ctx context.Context, org, owner string, id uuid.UUID) (bool, error) { + _, err := f.Turn(ctx, org, owner, id) + return false, err +} + +func (f *fakeStore) Events(_ context.Context, turn uuid.UUID, after int64) ([]store.Event, error) { + var out []store.Event + for _, e := range f.events[turn] { + if e.Seq > after { + out = append(out, e) + } + } + return out, nil +} + +func (f *fakeStore) EventsOf(context.Context, uuid.UUID, []string) ([]store.Event, error) { + return nil, nil +} diff --git a/modules/chat/actions.go b/modules/chat/actions.go index b80c80331..5817f8426 100644 --- a/modules/chat/actions.go +++ b/modules/chat/actions.go @@ -36,7 +36,7 @@ const ( // run waiting on it. The answer is stored before anything runs; the work loop // runs an approved action once. func (m *Module) Signal(ctx context.Context, id uuid.UUID, key string, payload jsontext.Value) (bool, error) { - ours, err := m.store.IsTurn(ctx, id) + owner, ours, err := m.store.TurnOwner(ctx, id) if err != nil || !ours { return false, err } @@ -54,7 +54,7 @@ func (m *Module) Signal(ctx context.Context, id uuid.UUID, key string, payload j } if !answer.Approved { m.record(ctx, id, kindAction, ActionDone{RequestID: answer.RequestID, State: actionDenied}) - m.hub.Publish(hub.Note{Topic: sessionTopic}) + m.hub.Publish(hub.Note{Topic: OwnerTopic(owner)}) } m.poke() return true, nil @@ -128,6 +128,16 @@ func (m *Module) runApproved(ctx context.Context, d Deps, a store.Action) error if err := json.Unmarshal(a.Answer, &answer); err != nil { return fmt.Errorf("decode answer: %w", err) } + ctx, err := m.actingAs(ctx, d, a.Owner) + if err != nil { + return err + } + if err := m.allowed(ctx, d, governance.ActionRun, governance.KindConnector, held.Action.Connector); err != nil { + if derr := d.Approver.Discard(ctx, a.RequestID, err.Error()); derr != nil { + return derr + } + return m.settled(ctx, d, a, actionApproved, actionFailed, err.Error()) + } fresh, err := d.Judge.Assess(ctx, judgement.Request{ RunID: a.TurnID, Key: held.Key + ":again", Connector: held.Action.Connector, Action: held.Action.Name, Input: held.Action.Input, Workflow: principal, @@ -192,7 +202,7 @@ func (m *Module) settled(ctx context.Context, d Deps, a store.Action, from, to, } done := ActionDone{RequestID: a.RequestID, State: to, Result: truncateRunes(result, outputMaxRunes)} m.record(ctx, a.TurnID, kindAction, done) - m.hub.Publish(hub.Note{Topic: sessionTopic}) + m.hub.Publish(hub.Note{Topic: OwnerTopic(a.Owner)}) var held judgement.Decision _ = json.Unmarshal(a.Decision, &held) return d.Notifier.Notify(ctx, deliveries.Notification{ diff --git a/modules/chat/api.go b/modules/chat/api.go index 5905b4b7a..9a73b1043 100644 --- a/modules/chat/api.go +++ b/modules/chat/api.go @@ -16,6 +16,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/hub" "github.com/samcharles93/archie-core/modules/chat/internal/store" + "github.com/samcharles93/archie-core/modules/governance" ) const ( @@ -27,40 +28,40 @@ const ( // Register adds the chat API. func (m *Module) Register(api huma.API) { tags := []string{"Chat"} - huma.Register(api, huma.Operation{ + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "list-chat-sessions", Method: http.MethodGet, Path: "/api/chat/sessions", Summary: "List conversations, most recently active first, with the model that answers", Tags: tags, - }, m.listSessions) - huma.Register(api, huma.Operation{ + }), m.listSessions) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "create-chat-session", Method: http.MethodPost, Path: "/api/chat/sessions", Summary: "Start a conversation", Tags: tags, DefaultStatus: http.StatusCreated, - }, m.createSession) - huma.Register(api, huma.Operation{ + }), m.createSession) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "rename-chat-session", Method: http.MethodPatch, Path: "/api/chat/sessions/{id}", Summary: "Rename a conversation", Tags: tags, - }, m.renameSession) - huma.Register(api, huma.Operation{ + }), m.renameSession) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "delete-chat-session", Method: http.MethodDelete, Path: "/api/chat/sessions/{id}", Summary: "Delete a conversation and its turns", Tags: tags, DefaultStatus: http.StatusNoContent, - }, m.deleteSession) - huma.Register(api, huma.Operation{ + }), m.deleteSession) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "list-chat-turns", Method: http.MethodGet, Path: "/api/chat/sessions/{id}/turns", Summary: "List a conversation's turns with what each did", Tags: tags, - }, m.listTurns) - huma.Register(api, huma.Operation{ + }), m.listTurns) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "send-chat-turn", Method: http.MethodPost, Path: "/api/chat/sessions/{id}/turns", Summary: "Send a message; it is stored, then answered after the turns before it", Tags: tags, DefaultStatus: http.StatusAccepted, - }, m.sendTurn) - huma.Register(api, huma.Operation{ + }), m.sendTurn) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "get-chat-turn", Method: http.MethodGet, Path: "/api/chat/turns/{id}", Summary: "Get one turn with what it did", Tags: tags, - }, m.getTurn) - huma.Register(api, huma.Operation{ + }), m.getTurn) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "cancel-chat-turn", Method: http.MethodPost, Path: "/api/chat/turns/{id}/cancel", Summary: "Stop a turn that is queued or running", Tags: tags, - }, m.cancelTurn) - huma.Register(api, huma.Operation{ + }), m.cancelTurn) + huma.Register(api, httpapi.SignedIn(huma.Operation{ OperationID: "stream-chat-turn", Method: http.MethodGet, Path: "/api/chat/turns/{id}/events", Summary: "Stream what a turn records, from a cursor, until it ends", Tags: tags, Responses: map[string]*huma.Response{"200": { @@ -69,7 +70,7 @@ func (m *Module) Register(api huma.API) { "the stream ends after done, error or cancelled.", Content: map[string]*huma.MediaType{"text/event-stream": {Schema: &huma.Schema{Type: huma.TypeString}}}, }}, - }, m.streamTurn) + }), m.streamTurn) } // Sessions is the conversation list with the model that answers turns. @@ -79,8 +80,22 @@ type Sessions struct { ModelError string `json:"model_error,omitzero"` } +// caller is the identity a request acts as: the owner of the conversations +// it may see. A conversation of anyone else is not found. +func caller(ctx context.Context) (string, error) { + p, ok := governance.PrincipalFromContext(ctx) + if !ok || p.IdentityID == "" { + return "", huma.NewError(http.StatusUnauthorized, httpapi.ErrUnauthenticated.Error()) + } + return string(p.IdentityID), nil +} + func (m *Module) listSessions(ctx context.Context, _ *struct{}) (*httpapi.Reply[Sessions], error) { - rows, err := m.store.Sessions(ctx, m.orgID, sessionPage) + owner, err := caller(ctx) + if err != nil { + return nil, err + } + rows, err := m.store.Sessions(ctx, m.orgID, owner, sessionPage) if err != nil { m.log.ErrorContext(ctx, "list chat sessions", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't list conversations") @@ -100,7 +115,11 @@ func (m *Module) listSessions(ctx context.Context, _ *struct{}) (*httpapi.Reply[ } func (m *Module) createSession(ctx context.Context, _ *struct{}) (*httpapi.Reply[Session], error) { - s, err := m.store.CreateSession(ctx, m.orgID, uuid.New()) + owner, err := caller(ctx) + if err != nil { + return nil, err + } + s, err := m.store.CreateSession(ctx, m.orgID, owner, uuid.New()) if err != nil { m.log.ErrorContext(ctx, "create chat session", "error", err) return nil, huma.NewError(http.StatusInternalServerError, "couldn't start a conversation") @@ -124,10 +143,14 @@ func (m *Module) renameSession(ctx context.Context, in *renameInput) (*httpapi.R if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id") } - if err := m.store.Rename(ctx, m.orgID, id, strings.TrimSpace(in.Body.Title)); err != nil { + owner, err := caller(ctx) + if err != nil { + return nil, err + } + if err := m.store.Rename(ctx, m.orgID, owner, id, strings.TrimSpace(in.Body.Title)); err != nil { return nil, m.failed(ctx, err, "rename the conversation") } - s, err := m.store.Session(ctx, m.orgID, id) + s, err := m.store.Session(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "read the conversation") } @@ -139,7 +162,11 @@ func (m *Module) deleteSession(ctx context.Context, in *idInput) (*struct{}, err if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id") } - turns, err := m.store.Turns(ctx, m.orgID, id) + owner, err := caller(ctx) + if err != nil { + return nil, err + } + turns, err := m.store.Turns(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "read the conversation") } @@ -148,7 +175,7 @@ func (m *Module) deleteSession(ctx context.Context, in *idInput) (*struct{}, err return nil, huma.NewError(http.StatusConflict, "stop the conversation's turns before deleting it") } } - if err := m.store.DeleteSession(ctx, m.orgID, id); err != nil { + if err := m.store.DeleteSession(ctx, m.orgID, owner, id); err != nil { return nil, m.failed(ctx, err, "delete the conversation") } return nil, nil @@ -159,10 +186,14 @@ func (m *Module) listTurns(ctx context.Context, in *idInput) (*httpapi.Reply[[]T if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id") } - if _, err := m.store.Session(ctx, m.orgID, id); err != nil { + owner, err := caller(ctx) + if err != nil { + return nil, err + } + if _, err := m.store.Session(ctx, m.orgID, owner, id); err != nil { return nil, m.failed(ctx, err, "read the conversation") } - rows, err := m.store.Turns(ctx, m.orgID, id) + rows, err := m.store.Turns(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "list the conversation's turns") } @@ -186,7 +217,11 @@ func (m *Module) getTurn(ctx context.Context, in *idInput) (*httpapi.Reply[Turn] if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a turn id") } - t, err := m.store.Turn(ctx, m.orgID, id) + owner, err := caller(ctx) + if err != nil { + return nil, err + } + t, err := m.store.Turn(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "read the turn") } @@ -251,6 +286,10 @@ func (m *Module) sendTurn(ctx context.Context, in *sendInput) (*httpapi.Reply[Tu if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a conversation id") } + owner, err := caller(ctx) + if err != nil { + return nil, err + } text := strings.TrimSpace(in.Body.Text) switch { case text == "": @@ -258,7 +297,7 @@ func (m *Module) sendTurn(ctx context.Context, in *sendInput) (*httpapi.Reply[Tu case utf8.RuneCountInString(text) > maxTextRunes: return nil, huma.NewError(http.StatusBadRequest, fmt.Sprintf("a message is at most %d characters", maxTextRunes)) } - t, err := m.store.AddTurn(ctx, m.orgID, store.Turn{ + t, err := m.store.AddTurn(ctx, m.orgID, owner, store.Turn{ ID: uuid.New(), SessionID: id, Text: text, Page: in.Body.Page, PageLabel: in.Body.PageLabel, }) if err != nil { @@ -273,7 +312,11 @@ func (m *Module) cancelTurn(ctx context.Context, in *idInput) (*httpapi.Reply[Tu if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a turn id") } - wasQueued, err := m.store.RequestCancel(ctx, m.orgID, id) + owner, err := caller(ctx) + if err != nil { + return nil, err + } + wasQueued, err := m.store.RequestCancel(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "stop the turn") } @@ -286,7 +329,7 @@ func (m *Module) cancelTurn(ctx context.Context, in *idInput) (*httpapi.Reply[Tu if stop != nil { stop() } - t, err := m.store.Turn(ctx, m.orgID, id) + t, err := m.store.Turn(ctx, m.orgID, owner, id) if err != nil { return nil, m.failed(ctx, err, "read the turn") } @@ -301,7 +344,7 @@ type streamInput struct { // streamTurn replays a turn's recorded events after the cursor, then follows // new ones until the turn ends. A reader that reconnects passes its last seq // and misses nothing. -func (m *Module) streamTurn(_ context.Context, in *streamInput) (*huma.StreamResponse, error) { +func (m *Module) streamTurn(ctx context.Context, in *streamInput) (*huma.StreamResponse, error) { id, err := uuid.Parse(in.ID) if err != nil { return nil, huma.NewError(http.StatusBadRequest, "id is a turn id") @@ -312,6 +355,13 @@ func (m *Module) streamTurn(_ context.Context, in *streamInput) (*huma.StreamRes return nil, huma.NewError(http.StatusBadRequest, "after is an event seq") } } + owner, err := caller(ctx) + if err != nil { + return nil, err + } + if _, err := m.store.Turn(ctx, m.orgID, owner, id); err != nil { + return nil, m.failed(ctx, err, "read the turn") + } return &huma.StreamResponse{Body: func(hc huma.Context) { m.serveEvents(hc, id, after) }}, nil //nolint:contextcheck // a stream takes its context from the response it writes, which ends with the request } @@ -324,15 +374,6 @@ func (m *Module) serveEvents(hc huma.Context, id uuid.UUID, after int64) { hc.SetStatus(http.StatusInternalServerError) return } - switch _, err := m.store.Turn(ctx, m.orgID, id); { - case errors.Is(err, store.ErrNotFound): - hc.SetStatus(http.StatusNotFound) - return - case err != nil: - m.log.ErrorContext(ctx, "chat: read the turn", "error", err) - hc.SetStatus(http.StatusInternalServerError) - return - } notes, stop := m.hub.Subscribe(topic(id)) defer stop() hc.SetHeader("Content-Type", "text/event-stream") diff --git a/modules/chat/chat.go b/modules/chat/chat.go index b9e556c61..a9cc959e8 100644 --- a/modules/chat/chat.go +++ b/modules/chat/chat.go @@ -77,8 +77,12 @@ type Notifier interface { Notify(ctx context.Context, n deliveries.Notification) error } -// Deps is what a turn's agent uses. +// Deps is what a turn's agent uses. People gives the principal a turn acts +// as, its conversation's owner, and Access decides what that principal may +// do through a tool. type Deps struct { + People governance.PrincipalSource + Access governance.Authorizer Settings Settings Toolbox Toolbox Judge Judge @@ -88,10 +92,55 @@ type Deps struct { Notifier Notifier } +// conversations is the chat store: every conversation, turn and held action. +// A read or change made for a person names them as owner, and finds only +// their own conversations. +type conversations interface { + sessionStore + turnStore + eventStore + actionStore +} + +type sessionStore interface { + CreateSession(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Session, error) + Sessions(ctx context.Context, orgID, owner string, limit int) ([]store.Session, error) + Session(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Session, error) + Rename(ctx context.Context, orgID, owner string, id uuid.UUID, title string) error + TitleIfUntitled(ctx context.Context, orgID string, id uuid.UUID, title string) error + DeleteSession(ctx context.Context, orgID, owner string, id uuid.UUID) error +} + +type turnStore interface { + AddTurn(ctx context.Context, orgID, owner string, t store.Turn) (store.Turn, error) + Turns(ctx context.Context, orgID, owner string, sessionID uuid.UUID) ([]store.Turn, error) + Turn(ctx context.Context, orgID, owner string, id uuid.UUID) (store.Turn, error) + TurnOwner(ctx context.Context, id uuid.UUID) (string, bool, error) + Claim(ctx context.Context) (store.Turn, bool, error) + Finish(ctx context.Context, id uuid.UUID, state, reply, reasoning, failure string) error + RequestCancel(ctx context.Context, orgID, owner string, id uuid.UUID) (bool, error) + Interrupted(ctx context.Context, reason string) ([]uuid.UUID, error) +} + +type eventStore interface { + History(ctx context.Context, sessionID uuid.UUID, before int64, limit int) ([]store.Turn, error) + AddEvent(ctx context.Context, turnID uuid.UUID, kind string, data jsontext.Value) (int64, error) + Events(ctx context.Context, turnID uuid.UUID, after int64) ([]store.Event, error) + EventsOf(ctx context.Context, sessionID uuid.UUID, kinds []string) ([]store.Event, error) +} + +type actionStore interface { + PutAction(ctx context.Context, orgID string, a store.Action) (store.Action, error) + Answer(ctx context.Context, turnID uuid.UUID, key, state string, answer []byte) (bool, error) + Open(ctx context.Context) ([]store.Action, error) + Move(ctx context.Context, id uuid.UUID, from, to, result string) (bool, error) + Escalated(ctx context.Context, id uuid.UUID, step int, due time.Time) error +} + // Module owns one organisation's conversations. type Module struct { orgID string - store *store.Store + store conversations log *slog.Logger hub *hub.Hub wake chan struct{} @@ -222,6 +271,6 @@ func finished(state string) bool { // topic is the hub topic a turn's live readers follow. func topic(turnID uuid.UUID) string { return "chat:" + turnID.String() } -// sessionTopic is the hub topic a conversation's readers follow for actions -// settled after its turns ended. -const sessionTopic = "chat" +// OwnerTopic is the hub topic an owner's readers follow for actions settled +// in their conversations after the turn that held them ended. +func OwnerTopic(owner string) string { return "chat-owner:" + owner } diff --git a/modules/chat/internal/store/store.go b/modules/chat/internal/store/store.go index a79ecb881..c6e1d5ca4 100644 --- a/modules/chat/internal/store/store.go +++ b/modules/chat/internal/store/store.go @@ -20,6 +20,7 @@ var ErrNotFound = errors.New("not found") // Session is one conversation. type Session struct { ID uuid.UUID `db:"id"` + Owner string `db:"owner_id"` Title string `db:"title"` CreatedAt time.Time `db:"created_at"` UpdatedAt time.Time `db:"updated_at"` @@ -30,6 +31,7 @@ type Turn struct { Seq int64 `db:"seq"` ID uuid.UUID `db:"id"` SessionID uuid.UUID `db:"session_id"` + Owner string `db:"owner_id"` State string `db:"state"` Text string `db:"text"` Page string `db:"page"` @@ -56,6 +58,7 @@ type Event struct { type Action struct { ID uuid.UUID `db:"id"` TurnID uuid.UUID `db:"turn_id"` + Owner string `db:"owner_id"` Key string `db:"key"` Decision jsontext.Value `db:"decision"` RequestID uuid.UUID `db:"request_id"` @@ -75,35 +78,41 @@ type Store struct { // New returns a store on db. func New(db *sqlx.DB) *Store { return &Store{db: db} } -const turnColumns = `seq, id, session_id, state, text, page, page_label, reply, reasoning, error, cancel, created_at, started_at, finished_at` +const turnColumns = `seq, id, session_id, state, text, page, page_label, reply, reasoning, error, cancel, created_at, started_at, finished_at, + (SELECT s.owner_id FROM chat.sessions s WHERE s.id = chat.turns.session_id) AS owner_id` -// CreateSession stores a new conversation. -func (s *Store) CreateSession(ctx context.Context, orgID string, id uuid.UUID) (Session, error) { +const sessionColumns = `id, owner_id, title, created_at, updated_at` + +// owned limits a turn query to the turns of owner's conversations in org. +const owned = `session_id IN (SELECT s.id FROM chat.sessions s WHERE s.org_id = $1 AND s.owner_id = $2)` + +// CreateSession stores a new conversation owned by owner. +func (s *Store) CreateSession(ctx context.Context, orgID, owner string, id uuid.UUID) (Session, error) { var out Session if err := s.db.GetContext(ctx, &out, ` - INSERT INTO chat.sessions (id, org_id) VALUES ($1, $2) - RETURNING id, title, created_at, updated_at`, id, orgID); err != nil { + INSERT INTO chat.sessions (id, org_id, owner_id) VALUES ($1, $2, $3) + RETURNING `+sessionColumns, id, orgID, owner); err != nil { return Session{}, fmt.Errorf("create session: %w", err) } return out, nil } -// Sessions lists the conversations, most recently active first. -func (s *Store) Sessions(ctx context.Context, orgID string, limit int) ([]Session, error) { +// Sessions lists owner's conversations, most recently active first. +func (s *Store) Sessions(ctx context.Context, orgID, owner string, limit int) ([]Session, error) { var out []Session if err := s.db.SelectContext(ctx, &out, ` - SELECT id, title, created_at, updated_at FROM chat.sessions - WHERE org_id = $1 ORDER BY updated_at DESC LIMIT $2`, orgID, limit); err != nil { + SELECT `+sessionColumns+` FROM chat.sessions + WHERE org_id = $1 AND owner_id = $2 ORDER BY updated_at DESC LIMIT $3`, orgID, owner, limit); err != nil { return nil, fmt.Errorf("list sessions: %w", err) } return out, nil } -// Session returns one conversation. -func (s *Store) Session(ctx context.Context, orgID string, id uuid.UUID) (Session, error) { +// Session returns one of owner's conversations. +func (s *Store) Session(ctx context.Context, orgID, owner string, id uuid.UUID) (Session, error) { var out Session err := s.db.GetContext(ctx, &out, ` - SELECT id, title, created_at, updated_at FROM chat.sessions WHERE org_id = $1 AND id = $2`, orgID, id) + SELECT `+sessionColumns+` FROM chat.sessions WHERE org_id = $1 AND owner_id = $2 AND id = $3`, orgID, owner, id) if errors.Is(err, sql.ErrNoRows) { return Session{}, ErrNotFound } @@ -113,9 +122,10 @@ func (s *Store) Session(ctx context.Context, orgID string, id uuid.UUID) (Sessio return out, nil } -// Rename sets a conversation's title. -func (s *Store) Rename(ctx context.Context, orgID string, id uuid.UUID, title string) error { - res, err := s.db.ExecContext(ctx, `UPDATE chat.sessions SET title = $3 WHERE org_id = $1 AND id = $2`, orgID, id, title) +// Rename sets the title of one of owner's conversations. +func (s *Store) Rename(ctx context.Context, orgID, owner string, id uuid.UUID, title string) error { + res, err := s.db.ExecContext(ctx, ` + UPDATE chat.sessions SET title = $4 WHERE org_id = $1 AND owner_id = $2 AND id = $3`, orgID, owner, id, title) return affected(res, err, "rename session") } @@ -129,20 +139,23 @@ func (s *Store) TitleIfUntitled(ctx context.Context, orgID string, id uuid.UUID, return nil } -// DeleteSession removes a conversation with its turns. -func (s *Store) DeleteSession(ctx context.Context, orgID string, id uuid.UUID) error { - res, err := s.db.ExecContext(ctx, `DELETE FROM chat.sessions WHERE org_id = $1 AND id = $2`, orgID, id) +// DeleteSession removes one of owner's conversations with its turns. +func (s *Store) DeleteSession(ctx context.Context, orgID, owner string, id uuid.UUID) error { + res, err := s.db.ExecContext(ctx, ` + DELETE FROM chat.sessions WHERE org_id = $1 AND owner_id = $2 AND id = $3`, orgID, owner, id) return affected(res, err, "delete session") } -// AddTurn stores a turn as queued and marks its conversation active. -func (s *Store) AddTurn(ctx context.Context, orgID string, t Turn) (Turn, error) { +// AddTurn stores a turn as queued in one of owner's conversations and marks +// the conversation active. +func (s *Store) AddTurn(ctx context.Context, orgID, owner string, t Turn) (Turn, error) { tx, err := s.db.BeginTxx(ctx, nil) if err != nil { return Turn{}, fmt.Errorf("begin: %w", err) } defer func() { _ = tx.Rollback() }() - res, err := tx.ExecContext(ctx, `UPDATE chat.sessions SET updated_at = now() WHERE org_id = $1 AND id = $2`, orgID, t.SessionID) + res, err := tx.ExecContext(ctx, ` + UPDATE chat.sessions SET updated_at = now() WHERE org_id = $1 AND owner_id = $2 AND id = $3`, orgID, owner, t.SessionID) if err := affected(res, err, "touch session"); err != nil { return Turn{}, err } @@ -159,20 +172,20 @@ func (s *Store) AddTurn(ctx context.Context, orgID string, t Turn) (Turn, error) return out, nil } -// Turns returns a conversation's turns, oldest first. -func (s *Store) Turns(ctx context.Context, orgID string, sessionID uuid.UUID) ([]Turn, error) { +// Turns returns the turns of one of owner's conversations, oldest first. +func (s *Store) Turns(ctx context.Context, orgID, owner string, sessionID uuid.UUID) ([]Turn, error) { var out []Turn if err := s.db.SelectContext(ctx, &out, ` - SELECT `+turnColumns+` FROM chat.turns WHERE org_id = $1 AND session_id = $2 ORDER BY seq`, orgID, sessionID); err != nil { + SELECT `+turnColumns+` FROM chat.turns WHERE `+owned+` AND session_id = $3 ORDER BY seq`, orgID, owner, sessionID); err != nil { return nil, fmt.Errorf("list turns: %w", err) } return out, nil } -// Turn returns one turn. -func (s *Store) Turn(ctx context.Context, orgID string, id uuid.UUID) (Turn, error) { +// Turn returns one turn of owner's conversations. +func (s *Store) Turn(ctx context.Context, orgID, owner string, id uuid.UUID) (Turn, error) { var out Turn - err := s.db.GetContext(ctx, &out, `SELECT `+turnColumns+` FROM chat.turns WHERE org_id = $1 AND id = $2`, orgID, id) + err := s.db.GetContext(ctx, &out, `SELECT `+turnColumns+` FROM chat.turns WHERE `+owned+` AND id = $3`, orgID, owner, id) if errors.Is(err, sql.ErrNoRows) { return Turn{}, ErrNotFound } @@ -182,13 +195,19 @@ func (s *Store) Turn(ctx context.Context, orgID string, id uuid.UUID) (Turn, err return out, nil } -// IsTurn reports whether id is a chat turn. -func (s *Store) IsTurn(ctx context.Context, id uuid.UUID) (bool, error) { - var ok bool - if err := s.db.GetContext(ctx, &ok, `SELECT EXISTS (SELECT 1 FROM chat.turns WHERE id = $1)`, id); err != nil { - return false, fmt.Errorf("find turn: %w", err) +// TurnOwner returns the owner of the conversation turn id is in, and false +// when id is not a chat turn. +func (s *Store) TurnOwner(ctx context.Context, id uuid.UUID) (string, bool, error) { + var owner string + err := s.db.GetContext(ctx, &owner, ` + SELECT s.owner_id FROM chat.turns t JOIN chat.sessions s ON s.id = t.session_id WHERE t.id = $1`, id) + if errors.Is(err, sql.ErrNoRows) { + return "", false, nil } - return ok, nil + if err != nil { + return "", false, fmt.Errorf("find turn: %w", err) + } + return owner, true, nil } // Claim starts the oldest queued turn of a conversation with no turn running, @@ -224,15 +243,16 @@ func (s *Store) Finish(ctx context.Context, id uuid.UUID, state, reply, reasonin return nil } -// RequestCancel asks a turn to stop. A queued turn is cancelled at once and -// reported true; a running one stops when its worker sees the request. -func (s *Store) RequestCancel(ctx context.Context, orgID string, id uuid.UUID) (bool, error) { +// RequestCancel asks one of owner's turns to stop. A queued turn is cancelled +// at once and reported true; a running one stops when its worker sees the +// request. +func (s *Store) RequestCancel(ctx context.Context, orgID, owner string, id uuid.UUID) (bool, error) { var state string err := s.db.GetContext(ctx, &state, ` UPDATE chat.turns SET cancel = true, state = CASE WHEN state = 'queued' THEN 'cancelled' ELSE state END, finished_at = CASE WHEN state = 'queued' THEN now() ELSE finished_at END - WHERE org_id = $1 AND id = $2 RETURNING state`, orgID, id) + WHERE `+owned+` AND id = $3 RETURNING state`, orgID, owner, id) if errors.Is(err, sql.ErrNoRows) { return false, ErrNotFound } @@ -320,7 +340,8 @@ func (s *Store) PutAction(ctx context.Context, orgID string, a Action) (Action, return s.actionBy(ctx, `turn_id = $1 AND key = $2`, a.TurnID, a.Key) } -const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result` +const actionColumns = `id, turn_id, key, decision, request_id, path, step, step_due, state, answer, result, + (SELECT s.owner_id FROM chat.turns t JOIN chat.sessions s ON s.id = t.session_id WHERE t.id = chat.actions.turn_id) AS owner_id` func (s *Store) actionBy(ctx context.Context, where string, args ...any) (Action, error) { var out Action diff --git a/modules/chat/tools.go b/modules/chat/tools.go index a53ea49a3..0d1f193e7 100644 --- a/modules/chat/tools.go +++ b/modules/chat/tools.go @@ -16,12 +16,58 @@ import ( "github.com/samcharles93/archie-core/internal/platform/prompts" "github.com/samcharles93/archie-core/modules/chat/internal/store" "github.com/samcharles93/archie-core/modules/connectors" + "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) // principal is who hard rules see acting when the chat agent calls an action. const principal = "chat" +// actingAs is ctx carrying the principal of owner, the person whose +// conversation it is, as a request they made would carry it. It is read from +// the owner's current memberships, so a turn never acts with access its owner +// has since lost. +func (m *Module) actingAs(ctx context.Context, d Deps, owner string) (context.Context, error) { + if owner == "" { + return nil, errors.New("the conversation has no owner to act as") + } + p, err := d.People.PrincipalFor(ctx, governance.IdentityID(owner)) + if err != nil { + return nil, fmt.Errorf("read who the conversation acts as: %w", err) + } + return governance.WithActor(governance.WithOrg(governance.WithPrincipal(ctx, p), p.Org), owner), nil +} + +// allowed refuses what the principal in ctx may not do through the +// dashboard, so a tool never reaches further than the person chatting. +func (m *Module) allowed(ctx context.Context, d Deps, action governance.Action, kind governance.ResourceKind, id string) error { + p, ok := governance.PrincipalFromContext(ctx) + if !ok { + return errors.New("no one to act as") + } + decision := d.Access.Authorize(ctx, p, action, governance.Resource{Kind: kind, ID: id, Org: p.Org}, governance.AccessContext{}) + switch { + case decision.Allowed: + return nil + case errors.Is(decision.Err, governance.ErrChainUnavailable): + return errors.New("access policies are unavailable; try again shortly") + } + return fmt.Errorf("you may not %s %s %s", action, kind, id) +} + +// guarded is tool with its run refused unless the principal may take action +// on a resource of kind. +func (m *Module) guarded(d Deps, action governance.Action, kind governance.ResourceKind, tool *core.Tool) *core.Tool { + run := tool.Execute + tool.Execute = func(ctx context.Context, input string) (string, error) { + if err := m.allowed(ctx, d, action, kind, ""); err != nil { + return "", err + } + return run(ctx, input) + } + return tool +} + // unsafeToolChars are those a model API refuses in a tool name. var unsafeToolChars = regexp.MustCompile(`[^a-zA-Z0-9_-]`) @@ -61,6 +107,13 @@ func toolSummaries(set core.ToolSet) []prompts.ChatTool { // action judgement holds is put to people and comes back to the agent as // waiting for approval rather than as a failure. func (m *Module) call(ctx context.Context, d Deps, t store.Turn, decl connectors.Declaration, input jsontext.Value) (string, error) { + need := governance.ActionRun + if decl.Kind == connectors.KindLookup { + need = governance.ActionRead + } + if err := m.allowed(ctx, d, need, governance.KindConnector, decl.Connector); err != nil { + return "", err + } tool, ok := d.Toolbox.Tool(decl.Connector) if !ok { return "", fmt.Errorf("%q isn't running", decl.Connector) @@ -152,7 +205,7 @@ func waitKey(key string) string { return "approval:" + key } // approvals, what it remembers, and opening a page for the operator. func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { return []*core.Tool{ - typedTool("run_list", "List the most recent workflow runs, newest first, with their state and error.", + m.guarded(d, governance.ActionRead, governance.KindRun, typedTool("run_list", "List the most recent workflow runs, newest first, with their state and error.", `{"type":"object","properties":{"limit":{"type":"integer","minimum":1,"maximum":100}}}`, func(ctx context.Context, in struct { Limit int `json:"limit"` @@ -162,8 +215,8 @@ func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { in.Limit = 20 } return d.Runs.Recent(ctx, m.orgID, in.Limit) - }), - typedTool("run_get", "Read one workflow run with its result.", + })), + m.guarded(d, governance.ActionRead, governance.KindRun, typedTool("run_get", "Read one workflow run with its result.", `{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`, func(ctx context.Context, in struct { ID uuid.UUID `json:"id"` @@ -174,8 +227,8 @@ func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { return "no such run", err } return run, nil - }), - typedTool("approval_list", "List the approval requests waiting for an answer.", `{"type":"object","properties":{}}`, + })), + m.guarded(d, governance.ActionRead, governance.KindApproval, typedTool("approval_list", "List the approval requests waiting for an answer.", `{"type":"object","properties":{}}`, func(ctx context.Context, _ struct{}) (any, error) { pending, err := d.Approver.Pending(ctx) views := make([]any, 0, len(pending)) @@ -183,10 +236,10 @@ func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { views = append(views, p.View()) } return views, err - }), - typedTool("memory_list", "List the facts you remember across conversations, with their ids.", `{"type":"object","properties":{}}`, - func(ctx context.Context, _ struct{}) (any, error) { return d.Memory.Notes(ctx) }), - typedTool("memory_save", "Remember a durable fact the operator told you, for later conversations. One fact per call, in a sentence.", + })), + m.guarded(d, governance.ActionRead, governance.KindSettings, typedTool("memory_list", "List the facts you remember across conversations, with their ids.", `{"type":"object","properties":{}}`, + func(ctx context.Context, _ struct{}) (any, error) { return d.Memory.Notes(ctx) })), + m.guarded(d, governance.ActionUpdate, governance.KindSettings, typedTool("memory_save", "Remember a durable fact the operator told you, for later conversations. One fact per call, in a sentence.", `{"type":"object","properties":{"text":{"type":"string"}},"required":["text"]}`, func(ctx context.Context, in struct { Text string `json:"text"` @@ -194,8 +247,8 @@ func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { ) (any, error) { n, err := d.Memory.Remember(ctx, in.Text) return "remembered as " + n.ID.String(), err - }), - typedTool("memory_forget", "Forget a remembered fact by its id.", + })), + m.guarded(d, governance.ActionUpdate, governance.KindSettings, typedTool("memory_forget", "Forget a remembered fact by its id.", `{"type":"object","properties":{"id":{"type":"string","format":"uuid"}},"required":["id"]}`, func(ctx context.Context, in struct { ID uuid.UUID `json:"id"` @@ -206,7 +259,7 @@ func (m *Module) builtins(d Deps, t store.Turn) []*core.Tool { return "nothing is remembered under that id", err } return "forgotten", err - }), + })), typedTool("dashboard_navigate", "Offer the operator a link to a dashboard page, such as /runs/ID or /classes.", `{"type":"object","properties":{"path":{"type":"string"},"label":{"type":"string"}},"required":["path"]}`, func(ctx context.Context, in Navigation) (any, error) { diff --git a/modules/chat/turn.go b/modules/chat/turn.go index 6a56da1e8..750c3e738 100644 --- a/modules/chat/turn.go +++ b/modules/chat/turn.go @@ -129,7 +129,7 @@ func (m *Module) answer(parent context.Context, t store.Turn) { reply, reasoning, err := m.generate(ctx, t) done := context.WithoutCancel(ctx) - cur, rerr := m.store.Turn(done, m.orgID, t.ID) + cur, rerr := m.store.Turn(done, m.orgID, t.Owner, t.ID) stopped := rerr == nil && cur.Cancel switch { case stopped: @@ -171,6 +171,10 @@ func (m *Module) generate(ctx context.Context, t store.Turn) (string, string, er if !ok { return "", "", errors.New("chat isn't ready yet") } + ctx, err := m.actingAs(ctx, d, t.Owner) + if err != nil { + return "", "", err + } model, err := d.Settings.AgentModelForAlias(ctx, "") if err != nil { return "", "", fmt.Errorf("no agent model is configured: %w", err) @@ -348,7 +352,7 @@ func toolCall(r *core.ToolResult, call pendingCall) ToolCall { // title names an untitled conversation after its first answered exchange. // It is a proposal: a failure leaves the conversation untitled. func (m *Module) title(ctx context.Context, t store.Turn, reply string) { - s, err := m.store.Session(ctx, m.orgID, t.SessionID) + s, err := m.store.Session(ctx, m.orgID, t.Owner, t.SessionID) if err != nil || s.Title != "" { return } diff --git a/modules/dashboard/stream.go b/modules/dashboard/stream.go index 6a1829b8b..27f24ebb9 100644 --- a/modules/dashboard/stream.go +++ b/modules/dashboard/stream.go @@ -10,6 +10,7 @@ import ( "github.com/samcharles93/archie-core/internal/platform/httpapi" "github.com/samcharles93/archie-core/internal/platform/hub" + chatpkg "github.com/samcharles93/archie-core/modules/chat" "github.com/samcharles93/archie-core/modules/governance" ) @@ -17,10 +18,6 @@ import ( // the connection open and the browser notices one that died. const keepalive = 25 * time.Second -// chatTopic is the hub topic the chat module publishes when an action a -// conversation held settles after its turn ended. -const chatTopic = "chat" - // chatOutcome is the frame the dashboard re-reads the open conversation on. const chatOutcome = `data: {"topic":"tasks","data":{"kind":"chat_outcome"}}` + "\n\n" @@ -38,11 +35,11 @@ func Register(api huma.API, h *hub.Hub) { Content: map[string]*huma.MediaType{"text/event-stream": {Schema: &huma.Schema{Type: huma.TypeString}}}, }}, }), func(ctx context.Context, _ *struct{}) (*huma.StreamResponse, error) { - // Chat is an administrator's; nobody else hears that it changed. + // A conversation is its owner's; nobody else hears that it changed. var chat <-chan hub.Note stop := func() {} - if p, _ := governance.PrincipalFromContext(ctx); p.InstanceAdmin() { - chat, stop = h.Subscribe(chatTopic) + if p, ok := governance.PrincipalFromContext(ctx); ok && p.IdentityID != "" { + chat, stop = h.Subscribe(chatpkg.OwnerTopic(string(p.IdentityID))) } return &huma.StreamResponse{Body: func(hc huma.Context) { defer stop() diff --git a/modules/dashboard/stream_test.go b/modules/dashboard/stream_test.go new file mode 100644 index 000000000..3dddb5718 --- /dev/null +++ b/modules/dashboard/stream_test.go @@ -0,0 +1,77 @@ +package dashboard + +import ( + "bufio" + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/samcharles93/archie-core/internal/platform/httpapi" + "github.com/samcharles93/archie-core/internal/platform/hub" + "github.com/samcharles93/archie-core/modules/chat" + "github.com/samcharles93/archie-core/modules/governance" +) + +// TestStreamTellsOnlyTheConversationsOwner guards the live stream's chat +// boundary: an action settled in a conversation is announced to its owner +// and to nobody else, administrators included. +func TestStreamTellsOnlyTheConversationsOwner(t *testing.T) { + for _, tc := range []struct { + reader string + hears bool + }{ + {"alice", true}, + {"bob", false}, + {string(governance.SystemID), false}, + } { + t.Run(tc.reader, func(t *testing.T) { + h := hub.New() + mux := http.NewServeMux() + Register(httpapi.New(mux, "test", headerAuth{}), h) + srv := httptest.NewServer(mux) + defer srv.Close() + + ctx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond) + defer cancel() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, srv.URL+"/api/stream", nil) + if err != nil { + t.Fatal(err) + } + req.Header.Set("X-As", tc.reader) + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer func() { _ = res.Body.Close() }() + h.Publish(hub.Note{Topic: chat.OwnerTopic("alice")}) + + heard := false + lines := bufio.NewScanner(res.Body) + for lines.Scan() { + if strings.Contains(lines.Text(), "chat_outcome") { + heard = true + break + } + } + if heard != tc.hears { + t.Fatalf("%s heard the update: %v, want %v", tc.reader, heard, tc.hears) + } + }) + } +} + +// headerAuth signs in whoever the X-As header names; the system identity is +// the instance administrator. +type headerAuth struct{} + +func (headerAuth) Authenticate(ctx context.Context, r *http.Request) (context.Context, bool, error) { + id := governance.IdentityID(r.Header.Get("X-As")) + p := governance.Principal{IdentityID: id, Org: governance.DefaultOrgID} + if id == governance.SystemID { + p = governance.SharedTokenOwner() + } + return governance.WithPrincipal(ctx, p), p.InstanceAdmin(), nil +} diff --git a/modules/governance/accounts_api.go b/modules/governance/accounts_api.go index 2a106b343..0a556e5a4 100644 --- a/modules/governance/accounts_api.go +++ b/modules/governance/accounts_api.go @@ -602,15 +602,16 @@ type capabilitiesBody struct { Sections map[string]bool `json:"sections"` } -// capabilities reports the dashboard sections this binary serves. Every -// served section's operations need an instance administrator, so each is -// reported as the caller's administrator standing; the dashboard hides the -// rest, whose pages call operations this binary does not have. +// capabilities reports the dashboard sections this binary serves. Chat is +// every signed-in person's, acting with their own access; every other served +// section's operations need an instance administrator, so each is reported as +// the caller's administrator standing. The dashboard hides the rest, whose +// pages call operations this binary does not have. func (m *Module) capabilities(ctx context.Context, _ *struct{}) (*httpapi.Reply[capabilitiesBody], error) { - p, _ := PrincipalFromContext(ctx) - sections := map[string]bool{} + p, signedIn := PrincipalFromContext(ctx) + sections := map[string]bool{"chat": signedIn} for _, name := range []string{ - "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", "chat", + "settings", "events", "workflows", "runs", "credentials", "extensions", "secret_engines", "models", "controls", } { sections[name] = p.InstanceAdmin() } diff --git a/ui/src/accounts/AccountEntry.vue b/ui/src/accounts/AccountEntry.vue index 7163410a9..23a1cdf5d 100644 --- a/ui/src/accounts/AccountEntry.vue +++ b/ui/src/accounts/AccountEntry.vue @@ -19,7 +19,7 @@ async function submit(){ if(setup.value&&step.value===1&&!recovery.value){step.value=2;return} busy.value=true;error.value="";notice.value=""; try{ - if(recovery.value){await api.recoverAccount(email.value,recoveryCode.value,password.value);recovery.value=false;password.value="";notice.value="Password changed. Sign in with your new password.";return} + if(recovery.value){await api.recoverAccount(email.value,recoveryCode.value,password.value);recovery.value=false;password.value="";notice.value="Password changed.";return} if(setup.value)await api.setupAccount({organisation_name:organisation.value,workspace_name:workspace.value,public_url:publicURL.value.replace(/\/$/,""),display_name:name.value,email:email.value,password:password.value}); else await api.signIn(email.value,password.value); password.value=""; @@ -33,13 +33,13 @@ async function signInPasskey(){busy.value=true;error.value="";try{await usePassk
-

{{setup?(step===1?'Set up your organisation':'Create your admin account'):recovery?'Recover your account':'Sign in'}}

+

{{setup?(step===1?'Set up your organisation':'Create your account'):recovery?'Recover your account':'Sign in'}}

{{error}} {{notice}} -
+