Cookies took Secure from r.TLS, which is nil behind a proxy that terminates TLS, so sign-in cookies went out without it. Every dashboard cookie now goes through one builder that reads the scheme the way the origin check does. The worktree reset and the agent worker's chown walk use os.Root, so a symlink swapped in mid-walk can't point them outside the worktree. gosec runs in golangci-lint, tests included. G104, G115, G204 and G304 are excluded in config; each remaining finding is fixed or suppressed at the site with its reason.
328 lines
12 KiB
Go
328 lines
12 KiB
Go
package archiemessaging
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/samcharles93/archie-core/internal/channels"
|
|
"github.com/samcharles93/archie-core/internal/domain/access"
|
|
"github.com/samcharles93/archie-core/internal/domain/identity"
|
|
"github.com/samcharles93/archie-core/internal/domain/messaging"
|
|
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
|
"github.com/samcharles93/archie-core/internal/domain/taskactions"
|
|
"github.com/samcharles93/archie-core/internal/infrastructure/controlplanerpc"
|
|
"github.com/samcharles93/archie-core/internal/secret"
|
|
"github.com/samcharles93/archie-core/internal/taskstate"
|
|
)
|
|
|
|
// telegramCredential is the credential binding service an org's Telegram bot
|
|
// token is bound under.
|
|
const telegramCredential = "telegram"
|
|
|
|
// credentialBindingsKind is the control-plane resource holding the bindings.
|
|
const credentialBindingsKind = "credential-bindings" //nolint:gosec // G101: a credential service name, not a credential.
|
|
|
|
// orgChannelSource is where the Messaging Service learns which orgs run a
|
|
// channel and how they are bound. *controlplanerpc.Client satisfies the first
|
|
// two; the principals come from the State Store's access contract.
|
|
type orgChannelSource interface {
|
|
ChannelOrgs(ctx context.Context) ([]controlplanerpc.OrgChannel, error)
|
|
Query(ctx context.Context, kind string, decode func([]byte) error) (int64, bool, error)
|
|
}
|
|
|
|
// orgChannelDeps is everything an org's channels need beyond the instance's.
|
|
type orgChannelDeps struct {
|
|
Source orgChannelSource
|
|
Principals access.PrincipalSource
|
|
}
|
|
|
|
// orgChannelPlan is one org's channel as its settings, binding and agent
|
|
// currently resolve.
|
|
type orgChannelPlan struct {
|
|
org string
|
|
binding secret.SecretRef
|
|
allowed []int64
|
|
show bool
|
|
agent access.Principal
|
|
}
|
|
|
|
// same reports whether next needs no rebuild of the running channel.
|
|
func (p orgChannelPlan) same(next orgChannelPlan) bool {
|
|
return p.binding == next.binding && slices.Equal(p.allowed, next.allowed) && p.agent.IdentityID == next.agent.IdentityID
|
|
}
|
|
|
|
// orgChannelLoop keeps one channel per org that has settings, a bound bot token
|
|
// and an agent of its own, until ctx ends.
|
|
func (s *Service) orgChannelLoop(ctx context.Context) {
|
|
ticker := time.NewTicker(s.reconcileInterval)
|
|
defer ticker.Stop()
|
|
for {
|
|
if err := s.syncOrgChannels(ctx); err != nil {
|
|
s.log.WarnContext(ctx, "org channels not synced", "err", err)
|
|
}
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
}
|
|
}
|
|
|
|
// syncOrgChannels builds, replaces or stops each org's channel to match what
|
|
// the orgs currently hold. A channel that no longer resolves is stopped: an org
|
|
// whose binding or agent went away must not keep a bot running.
|
|
func (s *Service) syncOrgChannels(ctx context.Context) error {
|
|
orgs, err := s.orgs.Source.ChannelOrgs(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
bindings, err := s.telegramBindings(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
wanted := map[string]orgChannelPlan{}
|
|
for _, entry := range orgs {
|
|
plan, err := s.planOrgChannel(ctx, entry, bindings[entry.Org])
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "org channel not run", "org", entry.Org, "reason", err)
|
|
continue
|
|
}
|
|
wanted[entry.Org] = plan
|
|
}
|
|
for owner, plan := range wanted {
|
|
s.applyOrgChannel(ctx, owner, plan)
|
|
}
|
|
for _, instance := range s.instances() {
|
|
if _, still := wanted[instance.owner]; instance.owner != storecontract.DefaultOrgID && !still {
|
|
if err := s.setChannelState(instance, nil); err != nil {
|
|
s.log.WarnContext(ctx, "org channel not stopped", "org", instance.owner, "err", err)
|
|
}
|
|
s.status.Declare(instance.name, false, false)
|
|
}
|
|
}
|
|
s.signalPublish()
|
|
return nil
|
|
}
|
|
|
|
// planOrgChannel resolves one org's settings to a channel it may run. The
|
|
// agent must belong to the org: the settings are the org's to write, so the
|
|
// identity they name is checked here rather than trusted.
|
|
func (s *Service) planOrgChannel(ctx context.Context, entry controlplanerpc.OrgChannel, binding secret.SecretRef) (orgChannelPlan, error) {
|
|
settings := entry.Settings
|
|
switch {
|
|
case settings.Agent == "":
|
|
return orgChannelPlan{}, errors.New("no agent named")
|
|
case len(settings.AllowedUserIDs) == 0:
|
|
return orgChannelPlan{}, errors.New("no allowed telegram users")
|
|
case binding == (secret.SecretRef{}):
|
|
return orgChannelPlan{}, fmt.Errorf("no credential binding %q", telegramCredential)
|
|
}
|
|
principal, err := s.orgs.Principals.PrincipalFor(ctx, identity.IdentityID(settings.Agent))
|
|
if err != nil {
|
|
return orgChannelPlan{}, fmt.Errorf("resolve agent: %w", err)
|
|
}
|
|
if string(principal.Org) != entry.Org || !principal.Kind.Agent() {
|
|
return orgChannelPlan{}, errors.New("agent is not an agent of this org")
|
|
}
|
|
return orgChannelPlan{org: entry.Org, binding: binding, allowed: settings.AllowedUserIDs, show: settings.ShowToolCalls, agent: principal}, nil
|
|
}
|
|
|
|
// telegramBindings maps each org to the secret its Telegram bot token is bound
|
|
// to. Bindings are the instance's to grant, so they are read from the system
|
|
// org's document.
|
|
func (s *Service) telegramBindings(ctx context.Context) (map[string]secret.SecretRef, error) {
|
|
var documents []struct {
|
|
Service string `json:"service"`
|
|
Org string `json:"org"`
|
|
Secret struct {
|
|
Engine string `json:"engine"`
|
|
Key string `json:"key"`
|
|
} `json:"secret"`
|
|
}
|
|
if _, _, err := s.orgs.Source.Query(ctx, credentialBindingsKind, func(value []byte) error { return json.Unmarshal(value, &documents) }); err != nil {
|
|
return nil, err
|
|
}
|
|
out := map[string]secret.SecretRef{}
|
|
for _, document := range documents {
|
|
if document.Service == telegramCredential {
|
|
out[document.Org] = secret.SecretRef{Engine: document.Secret.Engine, Key: document.Secret.Key}
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// applyOrgChannel starts owner's channel, or replaces it when its plan changed.
|
|
func (s *Service) applyOrgChannel(ctx context.Context, owner string, plan orgChannelPlan) {
|
|
if instance := s.orgInstance(owner); instance != nil {
|
|
s.applyExistingOrgChannel(ctx, instance, plan)
|
|
return
|
|
}
|
|
ch, err := s.buildOrgChannel(ctx, plan)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "org channel not built", "org", plan.org, "err", err)
|
|
return
|
|
}
|
|
instance := &channelInstance{
|
|
name: owner + "/" + telegramCredential, kind: telegramCredential, owner: owner,
|
|
chat: actingChat{ChatContract: s.chat, as: plan.agent}, plan: &plan,
|
|
channel: ch, notify: make(chan struct{}, 1),
|
|
}
|
|
s.addChannel(ctx, instance)
|
|
}
|
|
|
|
func (s *Service) applyExistingOrgChannel(ctx context.Context, instance *channelInstance, plan orgChannelPlan) {
|
|
previous := instance.currentPlan()
|
|
instance.mu.Lock()
|
|
running := instance.channel != nil
|
|
instance.mu.Unlock()
|
|
if running && previous.same(plan) {
|
|
if previous.show != plan.show {
|
|
s.setOrgShowToolCalls(instance, plan.show)
|
|
instance.setPlan(plan, s.chat)
|
|
}
|
|
return
|
|
}
|
|
ch, err := s.buildOrgChannel(ctx, plan)
|
|
if err != nil {
|
|
s.log.WarnContext(ctx, "org channel not rebuilt", "org", plan.org, "err", err)
|
|
return
|
|
}
|
|
instance.setPlan(plan, s.chat)
|
|
if err := s.setChannelState(instance, ch); err != nil {
|
|
s.log.WarnContext(ctx, "org channel not restarted", "org", plan.org, "err", err)
|
|
return
|
|
}
|
|
s.status.Declare(instance.name, true, false)
|
|
}
|
|
|
|
func (s *Service) setOrgShowToolCalls(instance *channelInstance, show bool) {
|
|
if g, ok := instance.current().(channels.ShowToolCallsSetter); ok {
|
|
g.SetShowToolCalls(show)
|
|
}
|
|
}
|
|
|
|
// buildOrgChannel builds an org's bot as an instance of the telegram channel
|
|
// extension, bound to the org's credential binding. The token stays a
|
|
// reference: the host resolves it when the extension launches, so this
|
|
// process never holds an org's bot credential. The org's channel carries none
|
|
// of the instance operator's seams: an org's chat users reach nothing but
|
|
// chat.
|
|
func (s *Service) buildOrgChannel(ctx context.Context, plan orgChannelPlan) (channels.Channel, error) {
|
|
pkg, file, ok := s.extensions.channelPackage(ctx, telegramCredential)
|
|
if !ok {
|
|
return nil, fmt.Errorf("the %s channel package is not installed", telegramCredential)
|
|
}
|
|
ids := make([]string, 0, len(plan.allowed))
|
|
for _, id := range plan.allowed {
|
|
ids = append(ids, strconv.FormatInt(id, 10))
|
|
}
|
|
settings := map[string]string{
|
|
"token_ref": plan.binding.Engine + ":" + plan.binding.Key,
|
|
"allowed_user_ids": strings.Join(ids, ","),
|
|
"show_tool_calls": strconv.FormatBool(plan.show),
|
|
}
|
|
return s.extensions.build(ctx, pkg, file, plan.org+"/"+telegramCredential, settings)
|
|
}
|
|
|
|
func (c *channelInstance) currentPlan() orgChannelPlan {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
if c.plan == nil {
|
|
return orgChannelPlan{}
|
|
}
|
|
return *c.plan
|
|
}
|
|
|
|
// setPlan records the plan the instance runs and the chat it speaks through.
|
|
func (c *channelInstance) setPlan(plan orgChannelPlan, gateway messaging.ChatContract) {
|
|
c.mu.Lock()
|
|
defer c.mu.Unlock()
|
|
c.plan = &plan
|
|
c.chat = actingChat{ChatContract: gateway, as: plan.agent}
|
|
}
|
|
|
|
func (s *Service) orgInstance(owner string) *channelInstance {
|
|
for _, instance := range s.instances() {
|
|
if instance.owner == owner && instance.kind == telegramCredential {
|
|
return instance
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// addChannel registers a channel composed after startup and supervises it.
|
|
func (s *Service) addChannel(ctx context.Context, instance *channelInstance) {
|
|
s.chMu.Lock()
|
|
s.channels = append(s.channels, instance)
|
|
s.chMu.Unlock()
|
|
s.status.Add(instance.name, instance.name, instance.current() != nil)
|
|
instance.mu.Lock()
|
|
instance.supervised = true
|
|
instance.mu.Unlock()
|
|
s.wg.Add(1)
|
|
go s.runChannel(ctx, instance)
|
|
}
|
|
|
|
// instances returns the composed channels, including those added since start.
|
|
func (s *Service) instances() []*channelInstance {
|
|
s.chMu.RLock()
|
|
defer s.chMu.RUnlock()
|
|
return slices.Clone(s.channels)
|
|
}
|
|
|
|
// actingChat speaks to the Gateway as an org's agent, so every call lands in
|
|
// that org. Every method of the contract is wrapped: one left bare would act
|
|
// for no one, which the Gateway reads as the system org.
|
|
type actingChat struct {
|
|
messaging.ChatContract
|
|
as access.Principal
|
|
}
|
|
|
|
func (a actingChat) act(ctx context.Context) context.Context { return access.WithPrincipal(ctx, a.as) }
|
|
|
|
func (a actingChat) Snapshot(ctx context.Context) (messaging.ChatSnapshot, error) {
|
|
return a.ChatContract.Snapshot(a.act(ctx))
|
|
}
|
|
|
|
func (a actingChat) GetSession(ctx context.Context, id string) (messaging.SessionContext, bool, error) {
|
|
return a.ChatContract.GetSession(a.act(ctx), id)
|
|
}
|
|
|
|
func (a actingChat) RecentMessages(ctx context.Context, id string, limit int) ([]messaging.Message, error) {
|
|
return a.ChatContract.RecentMessages(a.act(ctx), id, limit)
|
|
}
|
|
|
|
func (a actingChat) RecentTurns(ctx context.Context, id string, limit int) ([]messaging.TurnRecord, error) {
|
|
return a.ChatContract.RecentTurns(a.act(ctx), id, limit)
|
|
}
|
|
|
|
func (a actingChat) Route(ctx context.Context, in messaging.Inbound) (messaging.ChatReply, error) {
|
|
return a.ChatContract.Route(a.act(ctx), in)
|
|
}
|
|
|
|
func (a actingChat) Stream(ctx context.Context, in messaging.Inbound) (<-chan messaging.ChatEvent, error) {
|
|
return a.ChatContract.Stream(a.act(ctx), in)
|
|
}
|
|
|
|
func (a actingChat) Cancel(ctx context.Context, id string) (messaging.ChatCancellation, error) {
|
|
return a.ChatContract.Cancel(a.act(ctx), id)
|
|
}
|
|
|
|
func (a actingChat) StopTasks(ctx context.Context, origin string, taskID int64) ([]int64, error) {
|
|
return a.ChatContract.StopTasks(a.act(ctx), origin, taskID)
|
|
}
|
|
|
|
func (a actingChat) ApplyTaskAction(ctx context.Context, origin string, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
|
|
return a.ChatContract.ApplyTaskAction(a.act(ctx), origin, taskID, action, payload)
|
|
}
|
|
|
|
func (a actingChat) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action, payload taskactions.ActionPayload) (messaging.TaskActionResult, error) {
|
|
return a.ChatContract.ApplyOperatorTaskAction(a.act(ctx), actor, taskID, action, payload)
|
|
}
|