feat(gateway): chat sessions belong to one org

Sessions carry an org; listing, reading and writing a session, its
messages and its turns are limited to the caller's org. Another org's
session reads as not found and cannot be overwritten or appended to.
Sessions from before orgs belong to the system org.
This commit is contained in:
sam committed 2026-10-10 18:57:26 +11:00
1 parent 9cd52dd9aa
commit 0fcf792db3
6 files changed
+241 -29

No files matched your search

+84 -4
View File
@@ -14,6 +14,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
@@ -40,7 +41,7 @@ func (s *postgresSessionStore) Close() error {
func (s *postgresSessionStore) Save(ctx context.Context, sc SessionContext) error {
q := postgresdb.New(s.pool)
err := q.SaveSession(ctx, postgresdb.SaveSessionParams{
saved, err := q.SaveSession(ctx, postgresdb.SaveSessionParams{
SessionID: sc.SessionID,
Platform: sc.Source.Platform,
BotUser: sc.Source.BotUser,
@@ -51,16 +52,20 @@ func (s *postgresSessionStore) Save(ctx context.Context, sc SessionContext) erro
BranchName: sc.BranchName,
CreatedAt: sc.CreatedAt.UnixMilli(),
LastActiveAt: sc.LastActiveAt.UnixMilli(),
OrgID: callerOrg(ctx),
})
if err != nil {
return fmt.Errorf("sessionstore: save: %w", err)
}
if saved == 0 {
return ErrSessionNotFound
}
return nil
}
func (s *postgresSessionStore) Get(ctx context.Context, sessionID string) (*SessionContext, error) {
q := postgresdb.New(s.pool)
row, err := q.SessionByID(ctx, sessionID)
row, err := q.SessionByID(ctx, postgresdb.SessionByIDParams{SessionID: sessionID, OrgID: callerOrg(ctx)})
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
@@ -74,7 +79,7 @@ func (s *postgresSessionStore) Get(ctx context.Context, sessionID string) (*Sess
func (s *postgresSessionStore) GetByChannel(ctx context.Context, platform, channelID string) ([]SessionContext, error) {
q := postgresdb.New(s.pool)
rows, err := q.SessionsByChannel(ctx, postgresdb.SessionsByChannelParams{
Platform: platform, ChannelID: channelID,
Platform: platform, ChannelID: channelID, OrgID: callerOrg(ctx),
})
if err != nil {
return nil, fmt.Errorf("sessionstore: get by channel: %w", err)
@@ -83,6 +88,9 @@ func (s *postgresSessionStore) GetByChannel(ctx context.Context, platform, chann
}
func (s *postgresSessionStore) Delete(ctx context.Context, sessionID string) error {
if err := s.mayWrite(ctx, sessionID); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("sessionstore: delete: begin: %w", err)
@@ -106,6 +114,9 @@ func (s *postgresSessionStore) Delete(ctx context.Context, sessionID string) err
}
func (s *postgresSessionStore) Touch(ctx context.Context, sessionID string) error {
if err := s.mayWrite(ctx, sessionID); err != nil {
return err
}
q := postgresdb.New(s.pool)
err := q.TouchSession(ctx, postgresdb.TouchSessionParams{
SessionID: sessionID, LastActiveAt: time.Now().UTC().UnixMilli(),
@@ -118,7 +129,7 @@ func (s *postgresSessionStore) Touch(ctx context.Context, sessionID string) erro
func (s *postgresSessionStore) List(ctx context.Context) ([]SessionContext, error) {
q := postgresdb.New(s.pool)
rows, err := q.ListSessions(ctx)
rows, err := q.ListSessions(ctx, callerOrg(ctx))
if err != nil {
return nil, fmt.Errorf("sessionstore: list: %w", err)
}
@@ -148,6 +159,9 @@ func sessionsFromRows(rows []postgresdb.Session) []SessionContext {
// ── Messages ────────────────────────────────────────────────────────────────
func (s *postgresSessionStore) SaveMessage(ctx context.Context, sessionID string, msg messaging.Message) error {
if err := s.mayWrite(ctx, sessionID); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("sessionstore: save message: begin: %w", err)
@@ -168,6 +182,9 @@ func (s *postgresSessionStore) SaveMessage(ctx context.Context, sessionID string
}
func (s *postgresSessionStore) SaveMessages(ctx context.Context, sessionID string, msgs []messaging.Message) error {
if err := s.mayWrite(ctx, sessionID); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("sessionstore: save messages: begin: %w", err)
@@ -270,6 +287,9 @@ func (s *postgresSessionStore) ReplaceMessages(
msgs []messaging.Message,
superseded []string,
) error {
if err := s.mayWrite(ctx, sessionID); err != nil {
return err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
return fmt.Errorf("sessionstore: replace messages: begin: %w", err)
@@ -309,6 +329,9 @@ func (s *postgresSessionStore) ReplaceMessages(
}
func (s *postgresSessionStore) FindPriorReply(ctx context.Context, sessionID, sourceID, identity string) (string, error) {
if err := s.mayRead(ctx, sessionID); err != nil {
return "", err
}
if sourceID == "" {
return "", nil
}
@@ -341,6 +364,9 @@ func (s *postgresSessionStore) FindPriorReply(ctx context.Context, sessionID, so
}
func (s *postgresSessionStore) RecentMessages(ctx context.Context, sessionID string, n int) ([]messaging.Message, error) {
if err := s.mayRead(ctx, sessionID); err != nil {
return nil, err
}
if n <= 0 {
return nil, nil
}
@@ -358,6 +384,9 @@ func (s *postgresSessionStore) RecentMessages(ctx context.Context, sessionID str
}
func (s *postgresSessionStore) DeleteRecentMessages(ctx context.Context, sessionID string, n int) (int, error) {
if err := s.mayWrite(ctx, sessionID); err != nil {
return 0, err
}
if n <= 0 {
return 0, nil
}
@@ -375,6 +404,9 @@ func (s *postgresSessionStore) DeleteRecentMessages(ctx context.Context, session
}
func (s *postgresSessionStore) MessageCount(ctx context.Context, sessionID string) (int, error) {
if err := s.mayRead(ctx, sessionID); err != nil {
return 0, err
}
q := postgresdb.New(s.pool)
n, err := q.CountMessages(ctx, sessionID)
if err != nil {
@@ -456,6 +488,9 @@ func rowMessage(base messaging.Message, mediaRaw string) messaging.Message {
// SearchMessages full-text searches a session's message text and sender with
// plainto_tsquery. Truncated is always false.
func (s *postgresSessionStore) SearchMessages(ctx context.Context, sessionID string, q MessageQuery) (MessagePage, error) {
if err := s.mayRead(ctx, sessionID); err != nil {
return MessagePage{}, err
}
query := strings.TrimSpace(q.Query)
if query == "" {
return MessagePage{}, nil
@@ -523,6 +558,9 @@ func (s *postgresSessionStore) ClaimTurn(ctx context.Context, initial TurnRecord
if err != nil {
return TurnRecord{}, "", err
}
if err := s.mayWrite(ctx, initial.SessionID); err != nil {
return TurnRecord{}, "", err
}
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -666,10 +704,18 @@ func (s *postgresSessionStore) GetTurn(ctx context.Context, turnID string) (Turn
if err != nil {
return TurnRecord{}, false, err
}
if err := s.mayRead(ctx, record.SessionID); errors.Is(err, ErrSessionNotFound) {
return TurnRecord{}, false, nil
} else if err != nil {
return TurnRecord{}, false, err
}
return record, true, nil
}
func (s *postgresSessionStore) RecentTurns(ctx context.Context, sessionID string, n int) ([]TurnRecord, error) {
if err := s.mayRead(ctx, sessionID); err != nil {
return nil, err
}
if n <= 0 {
return []TurnRecord{}, nil
}
@@ -699,6 +745,9 @@ func (s *postgresSessionStore) SaveTurn(ctx context.Context, turn TurnRecord) er
if turn.TurnID == "" {
return fmt.Errorf("sessionstore: turn ID is required")
}
if err := s.mayWrite(ctx, turn.SessionID); err != nil {
return err
}
q := postgresdb.New(s.pool)
current, err := q.TurnAttemptOwner(ctx, turn.TurnID)
if errors.Is(err, pgx.ErrNoRows) {
@@ -781,3 +830,34 @@ func turnFromRow(row postgresdb.Turn) (TurnRecord, error) {
UpdatedAt: time.UnixMilli(row.UpdatedAt).UTC(),
}, nil
}
// ErrSessionNotFound is a session the caller's org does not own. Another
// org's session is indistinguishable from one that does not exist.
var ErrSessionNotFound = errors.New("sessionstore: session not found")
func callerOrg(ctx context.Context) string { return string(org.OrgFromContext(ctx)) }
// mayRead allows a read of sessionID when the caller's org owns it. Messages
// with no session row predate orgs and belong to the system org.
func (s *postgresSessionStore) mayRead(ctx context.Context, sessionID string) error {
owner, err := postgresdb.New(s.pool).SessionOrg(ctx, sessionID)
if errors.Is(err, pgx.ErrNoRows) {
owner = string(org.DefaultOrgID)
} else if err != nil {
return fmt.Errorf("sessionstore: session org: %w", err)
}
if owner != callerOrg(ctx) {
return ErrSessionNotFound
}
return nil
}
// mayWrite allows a write to sessionID when the caller's org owns it, making
// the caller's org the owner of a session nobody has written yet.
func (s *postgresSessionStore) mayWrite(ctx context.Context, sessionID string) error {
q := postgresdb.New(s.pool)
if err := q.ClaimSession(ctx, postgresdb.ClaimSessionParams{SessionID: sessionID, OrgID: callerOrg(ctx)}); err != nil {
return fmt.Errorf("sessionstore: claim session: %w", err)
}
return s.mayRead(ctx, sessionID)
}
@@ -0,0 +1,12 @@
-- A chat session belongs to one org; its messages and turns are reached only
-- through it. Sessions from before orgs belong to the system org.
-- +goose Up
ALTER TABLE sessions ADD COLUMN org_id text NOT NULL DEFAULT 'org-sys';
CREATE INDEX idx_sessions_org ON sessions (org_id);
-- +goose Down
DROP INDEX idx_sessions_org;
ALTER TABLE sessions DROP COLUMN org_id;
@@ -9,6 +9,22 @@ import (
"context"
)
const claimSession = `-- name: ClaimSession :exec
INSERT INTO sessions (session_id, org_id) VALUES ($1, $2)
ON CONFLICT (session_id) DO NOTHING
`
type ClaimSessionParams struct {
SessionID string
OrgID string
}
// A write to a session no row names yet makes the writing org its owner.
func (q *Queries) ClaimSession(ctx context.Context, arg ClaimSessionParams) error {
_, err := q.db.Exec(ctx, claimSession, arg.SessionID, arg.OrgID)
return err
}
const countMessages = `-- name: CountMessages :one
SELECT COUNT(*) FROM messages WHERE session_id = $1
`
@@ -280,13 +296,14 @@ func (q *Queries) ListRecoverableTurns(ctx context.Context) ([]Turn, error) {
const listSessions = `-- name: ListSessions :many
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions
WHERE org_id = $1
ORDER BY GREATEST(last_active_at, created_at) DESC
`
func (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {
rows, err := q.db.Query(ctx, listSessions)
func (q *Queries) ListSessions(ctx context.Context, orgID string) ([]Session, error) {
rows, err := q.db.Query(ctx, listSessions, orgID)
if err != nil {
return nil, err
}
@@ -305,6 +322,7 @@ func (q *Queries) ListSessions(ctx context.Context) ([]Session, error) {
&i.BranchName,
&i.CreatedAt,
&i.LastActiveAt,
&i.OrgID,
); err != nil {
return nil, err
}
@@ -523,12 +541,12 @@ func (q *Queries) RetryTurn(ctx context.Context, arg RetryTurnParams) (int64, er
return result.RowsAffected(), nil
}
const saveSession = `-- name: SaveSession :exec
const saveSession = `-- name: SaveSession :execrows
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
title, parent_session_id, branch_name, created_at, last_active_at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (session_id) DO UPDATE SET
platform = EXCLUDED.platform,
bot_user = EXCLUDED.bot_user,
@@ -539,6 +557,7 @@ ON CONFLICT (session_id) DO UPDATE SET
branch_name = EXCLUDED.branch_name,
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id
`
type SaveSessionParams struct {
@@ -552,13 +571,16 @@ type SaveSessionParams struct {
BranchName string
CreatedAt int64
LastActiveAt int64
OrgID string
}
// Gateway conversation queries: sessions, messages, turns, full-text search.
// These back internal/gateway's PostgreSQL SessionStore.
// ── Sessions ────────────────────────────────────────────────────────────────
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) error {
_, err := q.db.Exec(ctx, saveSession,
// Updates only a session the writing org owns: another org's session of the
// same id is left untouched and the zero row count refuses the write.
func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) (int64, error) {
result, err := q.db.Exec(ctx, saveSession,
arg.SessionID,
arg.Platform,
arg.BotUser,
@@ -569,8 +591,12 @@ func (q *Queries) SaveSession(ctx context.Context, arg SaveSessionParams) error
arg.BranchName,
arg.CreatedAt,
arg.LastActiveAt,
arg.OrgID,
)
return err
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const saveTurn = `-- name: SaveTurn :execrows
@@ -706,12 +732,17 @@ func (q *Queries) SearchMessagesPage(ctx context.Context, arg SearchMessagesPage
const sessionByID = `-- name: SessionByID :one
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
FROM sessions WHERE session_id = $1
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions WHERE session_id = $1 AND org_id = $2
`
func (q *Queries) SessionByID(ctx context.Context, sessionID string) (Session, error) {
row := q.db.QueryRow(ctx, sessionByID, sessionID)
type SessionByIDParams struct {
SessionID string
OrgID string
}
func (q *Queries) SessionByID(ctx context.Context, arg SessionByIDParams) (Session, error) {
row := q.db.QueryRow(ctx, sessionByID, arg.SessionID, arg.OrgID)
var i Session
err := row.Scan(
&i.SessionID,
@@ -724,25 +755,38 @@ func (q *Queries) SessionByID(ctx context.Context, sessionID string) (Session, e
&i.BranchName,
&i.CreatedAt,
&i.LastActiveAt,
&i.OrgID,
)
return i, err
}
const sessionOrg = `-- name: SessionOrg :one
SELECT org_id FROM sessions WHERE session_id = $1
`
func (q *Queries) SessionOrg(ctx context.Context, sessionID string) (string, error) {
row := q.db.QueryRow(ctx, sessionOrg, sessionID)
var org_id string
err := row.Scan(&org_id)
return org_id, err
}
const sessionsByChannel = `-- name: SessionsByChannel :many
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions
WHERE platform = $1 AND channel_id = $2
WHERE platform = $1 AND channel_id = $2 AND org_id = $3
ORDER BY GREATEST(last_active_at, created_at) DESC
`
type SessionsByChannelParams struct {
Platform string
ChannelID string
OrgID string
}
func (q *Queries) SessionsByChannel(ctx context.Context, arg SessionsByChannelParams) ([]Session, error) {
rows, err := q.db.Query(ctx, sessionsByChannel, arg.Platform, arg.ChannelID)
rows, err := q.db.Query(ctx, sessionsByChannel, arg.Platform, arg.ChannelID, arg.OrgID)
if err != nil {
return nil, err
}
@@ -761,6 +805,7 @@ func (q *Queries) SessionsByChannel(ctx context.Context, arg SessionsByChannelPa
&i.BranchName,
&i.CreatedAt,
&i.LastActiveAt,
&i.OrgID,
); err != nil {
return nil, err
}
@@ -354,6 +354,7 @@ type Session struct {
BranchName string
CreatedAt int64
LastActiveAt int64
OrgID string
}
type Source struct {
@@ -3,10 +3,12 @@
-- ── Sessions ────────────────────────────────────────────────────────────────
-- name: SaveSession :exec
-- name: SaveSession :execrows
-- Updates only a session the writing org owns: another org's session of the
-- same id is left untouched and the zero row count refuses the write.
INSERT INTO sessions (session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
title, parent_session_id, branch_name, created_at, last_active_at, org_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
ON CONFLICT (session_id) DO UPDATE SET
platform = EXCLUDED.platform,
bot_user = EXCLUDED.bot_user,
@@ -16,24 +18,34 @@ ON CONFLICT (session_id) DO UPDATE SET
parent_session_id = EXCLUDED.parent_session_id,
branch_name = EXCLUDED.branch_name,
created_at = EXCLUDED.created_at,
last_active_at = EXCLUDED.last_active_at;
last_active_at = EXCLUDED.last_active_at
WHERE sessions.org_id = EXCLUDED.org_id;
-- name: ClaimSession :exec
-- A write to a session no row names yet makes the writing org its owner.
INSERT INTO sessions (session_id, org_id) VALUES ($1, $2)
ON CONFLICT (session_id) DO NOTHING;
-- name: SessionOrg :one
SELECT org_id FROM sessions WHERE session_id = $1;
-- name: SessionByID :one
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
FROM sessions WHERE session_id = $1;
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions WHERE session_id = $1 AND org_id = $2;
-- name: SessionsByChannel :many
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions
WHERE platform = $1 AND channel_id = $2
WHERE platform = $1 AND channel_id = $2 AND org_id = $3
ORDER BY GREATEST(last_active_at, created_at) DESC;
-- name: ListSessions :many
SELECT session_id, platform, bot_user, channel_id, thread_id,
title, parent_session_id, branch_name, created_at, last_active_at
title, parent_session_id, branch_name, created_at, last_active_at, org_id
FROM sessions
WHERE org_id = $1
ORDER BY GREATEST(last_active_at, created_at) DESC;
-- name: DeleteSessionMessages :exec
@@ -0,0 +1,62 @@
package postgres_test
import (
"context"
"errors"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgstore"
)
// One org's chat sessions and messages are invisible to another, which can
// neither read nor overwrite them.
func TestChatSessionsStayInTheirOrg(t *testing.T) {
acme := org.WithOrg(t.Context(), "acme")
other := org.WithOrg(t.Context(), "other")
store := gateway.NewPostgresSessionStore(pgstore.Pool(t))
now := time.Now().UTC()
if err := store.Save(acme, gateway.SessionContext{SessionID: "s1", Title: "acme plans", CreatedAt: now, LastActiveAt: now}); err != nil {
t.Fatal(err)
}
if err := store.SaveMessage(acme, "s1", messaging.Message{ID: "m1", Role: messaging.RoleUser, Text: "secret"}); err != nil {
t.Fatal(err)
}
for _, tt := range []struct {
name string
ctx func() context.Context //nolint:containedctx // table input, not stored state
sees bool
}{
{"the owning org", func() context.Context { return acme }, true},
{"another org", func() context.Context { return other }, false},
} {
t.Run(tt.name, func(t *testing.T) {
ctx := tt.ctx()
listed, err := store.List(ctx)
if err != nil {
t.Fatal(err)
}
got, err := store.Get(ctx, "s1")
if err != nil {
t.Fatal(err)
}
messages, readErr := store.RecentMessages(ctx, "s1", 10)
if sees := len(listed) == 1 && got != nil && readErr == nil && len(messages) == 1; sees != tt.sees {
t.Fatalf("listed %d, got %v, messages %d (%v); want visible %v", len(listed), got != nil, len(messages), readErr, tt.sees)
}
if tt.sees {
return
}
if err := store.Save(ctx, gateway.SessionContext{SessionID: "s1", Title: "taken"}); !errors.Is(err, gateway.ErrSessionNotFound) {
t.Fatalf("overwrite err = %v, want ErrSessionNotFound", err)
}
if err := store.SaveMessage(ctx, "s1", messaging.Message{ID: "m2", Role: messaging.RoleUser, Text: "injected"}); !errors.Is(err, gateway.ErrSessionNotFound) {
t.Fatalf("append err = %v, want ErrSessionNotFound", err)
}
})
}
}