feat(identity): attribute a task action to the identity that acted

The transport could carry an actor and nothing filled it. It does now, so a
dashboard approval is recorded as the person whose credential verified, and an
agent's token is recorded as the agent's action -- for an agent, agent_approved;
for a person, human_approved; and for a caller whose identity archie could not
verify, task_approved, which claims nothing about who did it.

The actor travels the path the action takes: webui reads it from the request
context the middleware resolved, carries it in the gateway request, the daemon
passes it through the in-process adapter, and the NATS request body carries it to
the service that records it. Scope stays separate from actor at every hop, because
scope is which task a caller may touch and the actor is who touched it.

A chat channel's bound identity is an actor too: a bot acting on its own channel's
task is recorded as an agent's action rather than a person's, via ActorFromScope,
whose empty kind is what keeps it out of human_approved. The agent-facing
task_action tool passes that identity and never input["identity"].

The UI process's credential check is now filled by endpoint references rather than
by configuration: -oidc-issuer and -oidc-audience on archie-ui, two URLs the
process already understands the shape of, with the verifier built in Run because
cmd/ parses flags and nothing else. The UI package still never reads config, and a
configured provider that cannot be reached fails boot rather than falling back to
the gate that names nobody.

Evidence for this change, stated as measured: go build ./... and go vet ./... are
clean, and every package this touches passes -- webui, domain/taskactions,
infrastructure/taskactions, infrastructure/gatewayrpc, gateway, app/archieui,
app/archied, domain/messaging, channels/telegram, cmd/archie-ui. task check could
not be run to completion: it fails in cmd/archie-messaging on an untracked
internal/buildinfo package another lane has in flight, which is not this change and
was left untouched. The end-to-end flip is covered in
internal/webui/api_tasks_actor_test.go: a person's credential produces a record
naming that person with human_approved, an agent's produces agent_approved, an
unverified request produces task_approved with no actor, and a request carrying
forged actor fields cannot name one.
This commit is contained in:
sam committed 2026-09-22 14:52:10 +10:00
1 parent 115cf564d8
commit 3902b7ecbc
22 files changed
+338 -45

No files matched your search

+5
View File
@@ -17,6 +17,7 @@ import (
"syscall"
"github.com/samcharles93/archie-core/internal/app/archieui"
"github.com/samcharles93/archie-core/internal/buildinfo"
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
)
@@ -24,11 +25,14 @@ func main() { os.Exit(run()) }
func run() int {
var options archieui.Options
showVersion := buildinfo.RegisterVersionFlag("archie-ui")
flag.StringVar(&options.Config, "config", configuration.DefaultConfigPath(), "configuration file or directory (only [services.*] targets and [web] are read)")
flag.StringVar(&options.Overlay, "config-overlay", "", "configuration overlay file or directory")
flag.StringVar(&options.Listen, "listen", "", "dashboard HTTP listen address (defaults to [web].listen, else 127.0.0.1:8484)")
flag.StringVar(&options.Token, "token", "", "dashboard token; required for a non-loopback listener")
flag.StringVar(&options.TokenFile, "token-file", "", "file holding the dashboard token, minted on first use")
flag.StringVar(&options.OidcIssuer, "oidc-issuer", "", "identity provider issuer URL; requests must then carry a token it signed")
flag.StringVar(&options.OidcAudience, "oidc-audience", "", "audience (resource identifier) this dashboard accepts tokens for; required with -oidc-issuer")
flag.StringVar(&options.Gateway.Target, "gateway-target", "", "archie-gateway gRPC address (defaults to [services.gateway].target)")
flag.StringVar(&options.Gateway.Token, "gateway-token", "", "bearer token presented to archie-gateway")
flag.StringVar(&options.State.Target, "state-target", "", "archie-state-store gRPC address (defaults to [services.state].target)")
@@ -47,6 +51,7 @@ func run() int {
return nil
})
flag.Parse()
showVersion()
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
+2 -1
View File
@@ -36,6 +36,7 @@ import (
"github.com/samcharles93/archie-core/internal/config"
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
"github.com/samcharles93/archie-core/internal/store"
@@ -133,7 +134,7 @@ func (f *fakeGateway) ApplyTaskAction(context.Context, string, int64, taskstate.
return messaging.TaskActionResult{}, nil
}
func (f *fakeGateway) ApplyOperatorTaskAction(_ context.Context, id int64, action taskstate.Action) (messaging.TaskActionResult, error) {
func (f *fakeGateway) ApplyOperatorTaskAction(_ context.Context, actor taskactions.Actor, id int64, action taskstate.Action) (messaging.TaskActionResult, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.actions = append(f.actions, fmt.Sprintf("%d:%s", id, action))
+3 -2
View File
@@ -32,6 +32,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/applystatus"
"github.com/samcharles93/archie-core/internal/domain/curator"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/forge"
@@ -670,13 +671,13 @@ type chatTaskActorAdapter struct {
}
func (a chatTaskActorAdapter) ApplyChatTaskAction(
ctx context.Context, identity *string, taskID int64, action taskstate.Action,
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if a.contract == nil {
return gateway.TaskActionResult{}, gateway.ErrChatCapabilityUnavailable
}
if identity == nil {
return a.contract.ApplyOperatorTaskAction(ctx, taskID, action)
return a.contract.ApplyOperatorTaskAction(ctx, actor, taskID, action)
}
return a.contract.ApplyTaskAction(ctx, *identity, taskID, action)
}
@@ -23,9 +23,9 @@ import (
type testTaskActor struct{ b *boot }
func (a testTaskActor) ApplyChatTaskAction(
ctx context.Context, identity *string, taskID int64, action taskstate.Action,
ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
if err := a.b.taskActions().Apply(ctx, identity, taskactions.Actor{}, taskID, action); err != nil {
if err := a.b.taskActions().Apply(ctx, identity, actor, taskID, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{
@@ -88,7 +88,7 @@ func TestChatTaskActorAdapterCrossIdentityRefused(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
_, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, task.ID, tc.action)
_, err := adapter.ApplyChatTaskAction(ctx, &tc.actorIdentity, taskactions.Actor{}, task.ID, tc.action)
if err == nil {
t.Fatalf("ApplyChatTaskAction() allowed cross-identity action %s by %q on task owned by %q",
tc.action, tc.actorIdentity, task.Identity)
@@ -163,7 +163,7 @@ func TestChatTaskActorAdapterRefusesDisallowedStateAction(t *testing.T) {
}
}
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), task.ID, tc.attemptAction)
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.attemptAction)
if err == nil {
t.Fatalf("expected error attempting %s on %s task, got nil", tc.attemptAction, tc.initialStatus)
}
@@ -196,7 +196,7 @@ func TestChatTaskActorAdapterTaskNotFound(t *testing.T) {
adapter := newChatTaskActorForTest(t, st, config.Config{})
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), 999999, taskstate.ActionAbandon)
_, err = adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 999999, taskstate.ActionAbandon)
if err == nil {
t.Fatal("expected error for non-existent task, got nil")
}
@@ -278,7 +278,7 @@ func TestChatTaskActorAdapterAppliesActionsToStore(t *testing.T) {
}
}
result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), task.ID, tc.action)
result, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, task.ID, tc.action)
if err != nil {
t.Fatalf("ApplyChatTaskAction(%s) error = %v", tc.action, err)
}
@@ -313,7 +313,7 @@ func TestChatTaskActorAdapterNilContract(t *testing.T) {
ctx := context.Background()
adapter := chatTaskActorAdapter{contract: nil}
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), 1, taskstate.ActionAbandon)
_, err := adapter.ApplyChatTaskAction(ctx, new("archie"), taskactions.Actor{}, 1, taskstate.ActionAbandon)
if err == nil {
t.Fatal("expected error for nil contract, got nil")
}
+41
View File
@@ -0,0 +1,41 @@
package archieui
import (
"context"
"log/slog"
"strings"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/infrastructure/oidc"
)
// dashboardAuthenticator builds the dashboard's credential check from the
// endpoint references the process was given, or returns nil when none were.
//
// It is built here rather than in the command because cmd/ parses flags and
// nothing else, and it takes two URLs rather than a configuration struct because
// this process is deliberately kept unaware of the config file's shape -- see the
// note above Options. Issuer and audience are exactly the endpoint references
// Options already carries for the Gateway and the State Store.
//
// A nil result means no provider is configured, and the shared token stays the
// gate: an instance that never configured one keeps working, and its requests are
// recorded unattributed rather than credited to a human.
func dashboardAuthenticator(ctx context.Context, opts Options, subjects identity.SubjectResolver, log *slog.Logger) (func(context.Context, string) (identity.Identity, error), error) {
if strings.TrimSpace(opts.OidcIssuer) == "" {
return nil, nil
}
verifier, err := oidc.New(ctx, oidc.Config{Issuer: opts.OidcIssuer, Audience: opts.OidcAudience})
if err != nil {
// Failing here rather than serving anyway: a dashboard that cannot verify
// a credential would silently fall back to a gate that names nobody, and
// an operator who configured a provider must not get the unauthenticated
// behaviour instead.
return nil, err
}
log.Info("dashboard authenticates provider credentials", "issuer", opts.OidcIssuer, "audience", opts.OidcAudience)
return func(ctx context.Context, credential string) (identity.Identity, error) {
value, _, err := identity.Authenticate(ctx, subjects, verifier, credential)
return value, err
}, nil
}
+7
View File
@@ -59,6 +59,13 @@ type Options struct {
// use. It is the explicit opt-in to a non-loopback listener: without it
// a reachable bind must be given a token.
TokenFile string
// OidcIssuer and OidcAudience are endpoint references for the identity
// provider, not configuration. The issuer is read for its discovery document
// and signing keys, and the audience is the resource identifier this process
// accepts credentials for. Both empty leaves the shared-token gate in place;
// an issuer with no audience is refused rather than accepted without the check.
OidcIssuer string
OidcAudience string
// TrustForwardedHeaders is tri-state so an explicit false on the command
// line can override a configuration file that enables it. Nil means the
// operator did not say, and the file (else false) decides.
+6
View File
@@ -44,6 +44,11 @@ func Run(ctx context.Context, options Options) error {
}
cleanups = append(cleanups, closeGateway)
authenticate, err := dashboardAuthenticator(ctx, opts, tasks, log)
if err != nil {
return err
}
srv := compose(deps{
Options: opts,
Log: log,
@@ -52,6 +57,7 @@ func Run(ctx context.Context, options Options) error {
Health: newReadinessRegistry(opts, tasks, chat),
ControlPlane: tasks.ControlPlane(),
Identities: tasks,
Authenticate: authenticate,
})
// Live activity has no in-process bus in this process: the pump reads
+2 -1
View File
@@ -18,6 +18,7 @@ import (
"github.com/samcharles93/archie-core/internal/domain/health"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/gateway"
"github.com/samcharles93/archie-core/internal/infrastructure/gatewayrpc"
@@ -73,7 +74,7 @@ func (f *fakeChat) ApplyTaskAction(context.Context, string, int64, taskstate.Act
return gateway.TaskActionResult{}, nil
}
func (f *fakeChat) ApplyOperatorTaskAction(context.Context, int64, taskstate.Action) (gateway.TaskActionResult, error) {
func (f *fakeChat) ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, nil
}
+2 -1
View File
@@ -4,6 +4,7 @@ import (
"context"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -85,6 +86,6 @@ func (f *fakeChatContract) ApplyTaskAction(ctx context.Context, identity string,
return messaging.TaskActionResult{}, nil
}
func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
func (f *fakeChatContract) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
return messaging.TaskActionResult{}, nil
}
+8 -4
View File
@@ -3,6 +3,7 @@ package messaging
import (
"context"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -32,10 +33,13 @@ type ChatTaskActionContract interface {
// may only act on its own tasks.
ApplyTaskAction(context.Context, string, int64, taskstate.Action) (TaskActionResult, error)
// ApplyOperatorTaskAction applies an action on behalf of an authenticated
// dashboard operator, who acts across identities. It is a separate method
// rather than an empty identity because "" is a real identity in a
// single-identity deployment (see chatTaskProfiles in the daemon).
ApplyOperatorTaskAction(context.Context, int64, taskstate.Action) (TaskActionResult, error)
// dashboard caller, who acts across identities. The actor is who the
// credential resolved to, or the zero Actor when the caller presented
// nothing archie could verify -- which is recorded unattributed rather than
// credited to a human. It is a separate method rather than an empty identity
// because "" is a real identity in a single-identity deployment (see
// chatTaskProfiles in the daemon).
ApplyOperatorTaskAction(context.Context, taskactions.Actor, int64, taskstate.Action) (TaskActionResult, error)
}
// TaskActionResult is what task_action returns.
+8
View File
@@ -52,6 +52,14 @@ func ActorFor(value identity.Identity) Actor {
return Actor{Identity: value.ID, Kind: value.Kind}
}
// ActorFromScope builds an actor for a caller whose identity archie knows but did
// not derive from a credential: a chat channel's bound identity. The kind is not
// known here, so the action is recorded as an agent's rather than a person's, and
// the authority it acted under is recorded separately when it is known.
func ActorFromScope(id string) Actor {
return Actor{Identity: identity.IdentityID(id)}
}
// AuthorisedBy records where an action's authority came from.
func (a Actor) AuthorisedBy(principal identity.IdentityID) Actor {
a.Principal = principal
+4 -3
View File
@@ -7,6 +7,7 @@ import (
"strings"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -121,14 +122,14 @@ func (a *LocalChatAdapter) ApplyTaskAction(ctx context.Context, identity string,
if a.TaskActor == nil {
return TaskActionResult{}, ErrChatCapabilityUnavailable
}
return a.TaskActor.ApplyChatTaskAction(ctx, &identity, taskID, action)
return a.TaskActor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, action)
}
func (a *LocalChatAdapter) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (TaskActionResult, error) {
func (a *LocalChatAdapter) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action) (TaskActionResult, error) {
if a.TaskActor == nil {
return TaskActionResult{}, ErrChatCapabilityUnavailable
}
return a.TaskActor.ApplyChatTaskAction(ctx, nil, taskID, action)
return a.TaskActor.ApplyChatTaskAction(ctx, nil, actor, taskID, action)
}
func (a *LocalChatAdapter) Stream(ctx context.Context, in Inbound) (<-chan ChatEvent, error) {
+2 -1
View File
@@ -7,6 +7,7 @@ import (
"strings"
"testing"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
)
@@ -21,7 +22,7 @@ type fakeActor struct {
gotAction taskstate.Action
}
func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity *string, taskID int64, action taskstate.Action) (TaskActionResult, error) {
func (f *fakeActor) ApplyChatTaskAction(_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action) (TaskActionResult, error) {
if identity != nil {
f.gotIdentity = *identity
}
+7 -3
View File
@@ -6,6 +6,7 @@ import (
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
"github.com/samcharles93/archie-core/internal/tools"
)
@@ -78,7 +79,7 @@ type ChatTaskActor interface {
// across identities -- the distinction internal/domain/taskactions draws,
// and not the same as an empty name, which is a real identity in a
// single-identity deployment.
ApplyChatTaskAction(ctx context.Context, identity *string, taskID int64, action taskstate.Action) (TaskActionResult, error)
ApplyChatTaskAction(ctx context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action) (TaskActionResult, error)
}
// ChatTaskLogEntry is one log line as task_logs returns it. It mirrors
@@ -313,8 +314,11 @@ func taskActionTool(actor ChatTaskActor, identity string) tools.ToolEntry {
}
// The bound identity, never input["identity"]. Passed by
// address: chat is always scoped, never an operator.
result, err := actor.ApplyChatTaskAction(ctx, &identity, taskID, taskstate.Action(actionStr))
// address: chat is always scoped, never an operator. The
// actor is that same bound identity, because a bot acting on
// its own channel's task is exactly what happened -- and it is
// recorded as an agent's action, not a person's.
result, err := actor.ApplyChatTaskAction(ctx, &identity, taskactions.ActorFromScope(identity), taskID, taskstate.Action(actionStr))
if err != nil {
return nil, fmt.Errorf("task_action: %w", err)
}
+9 -2
View File
@@ -10,6 +10,7 @@ import (
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -89,8 +90,14 @@ func (c *Client) ApplyTaskAction(ctx context.Context, identity string, taskID in
return messaging.TaskActionResult{TaskID: v.TaskId, Action: v.Action, Message: v.Message}, nil
}
func (c *Client) ApplyOperatorTaskAction(ctx context.Context, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{TaskId: taskID, Action: string(action)})
func (c *Client) ApplyOperatorTaskAction(ctx context.Context, actor taskactions.Actor, taskID int64, action taskstate.Action) (messaging.TaskActionResult, error) {
v, err := c.client.ApplyOperatorTaskAction(ctx, &pb.ApplyOperatorTaskActionRequest{
TaskId: taskID,
Action: string(action),
ActorId: string(actor.Identity),
ActorKind: string(actor.Kind),
PrincipalId: string(actor.Principal),
})
if err != nil {
return messaging.TaskActionResult{}, taskActionError(err)
}
@@ -145,7 +145,7 @@ type recordingTaskActor struct {
}
func (a *recordingTaskActor) ApplyChatTaskAction(
_ context.Context, identity *string, taskID int64, action taskstate.Action,
_ context.Context, identity *string, actor taskactions.Actor, taskID int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
a.identity, a.taskID, a.action = identity, taskID, action
return gateway.TaskActionResult{TaskID: taskID, Action: string(action), Message: "applied"}, nil
@@ -169,7 +169,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
chat = remoteChat(t, local)
}
result, err := chat.ApplyOperatorTaskAction(ctx, 42, taskstate.ActionApprove)
result, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 42, taskstate.ActionApprove)
if err != nil {
t.Fatalf("operator action: %v", err)
}
@@ -197,7 +197,7 @@ func TestTaskActionScopeSurvivesTheWire(t *testing.T) {
type failingTaskActor struct{ err error }
func (a failingTaskActor) ApplyChatTaskAction(
context.Context, *string, int64, taskstate.Action,
context.Context, *string, taskactions.Actor, int64, taskstate.Action,
) (gateway.TaskActionResult, error) {
return gateway.TaskActionResult{}, a.err
}
@@ -221,7 +221,7 @@ func TestTaskActionErrorsKeepTheirSentinelOverGRPC(t *testing.T) {
local := &gateway.LocalChatAdapter{TaskActor: failingTaskActor{err: tc.err}}
chat := remoteChat(t, local)
_, err := chat.ApplyOperatorTaskAction(ctx, 7, taskstate.ActionApprove)
_, err := chat.ApplyOperatorTaskAction(ctx, taskactions.Actor{}, 7, taskstate.ActionApprove)
if err == nil {
t.Fatalf("ApplyOperatorTaskAction error = nil, want %v", tc.err)
}
+8 -1
View File
@@ -8,7 +8,9 @@ import (
"google.golang.org/grpc/status"
pb "github.com/samcharles93/archie-core/internal/contracts/gateway/v1"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/messaging"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/taskstate"
)
@@ -98,7 +100,12 @@ func (s *server) ApplyTaskAction(ctx context.Context, r *pb.ApplyTaskActionReque
}
func (s *server) ApplyOperatorTaskAction(ctx context.Context, r *pb.ApplyOperatorTaskActionRequest) (*pb.ApplyOperatorTaskActionResponse, error) {
v, err := s.chat.ApplyOperatorTaskAction(ctx, r.TaskId, taskstate.Action(r.Action))
actor := taskactions.Actor{
Identity: identity.IdentityID(r.ActorId),
Kind: identity.Kind(r.ActorKind),
Principal: identity.IdentityID(r.PrincipalId),
}
v, err := s.chat.ApplyOperatorTaskAction(ctx, actor, r.TaskId, taskstate.Action(r.Action))
if err != nil {
return nil, taskActionStatus(err)
}
+42 -10
View File
@@ -10,6 +10,7 @@ import (
"github.com/nats-io/nats.go"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
"github.com/samcharles93/archie-core/internal/domain/taskactions"
"github.com/samcharles93/archie-core/internal/gateway"
@@ -23,16 +24,35 @@ import (
const actionSubject = "archie.gateway.task-action"
// Identity is a pointer because its absence is meaningful: nil is a
// authenticated dashboard operator acting across identities, which the daemon's
// service distinguishes from any named identity, empty included. It is a SCOPE
// -- which tasks the caller may touch -- and never an actor. Who acted is not on
// this request yet, so the daemon records these actions unattributed rather than
// crediting them to a human: the dashboard's own credential is a shared token,
// which is not evidence that a person was at the keyboard.
// caller authenticated across identities, which the daemon's service
// distinguishes from any named identity, empty included. It is a SCOPE -- which
// tasks the caller may touch -- and never an actor.
//
// Actor carries who performed the action and whose authority permitted it, as
// resolved by the caller that verified the credential. Its absence is meaningful:
// an absent actor records an unattributed action, never a human's.
type actionRequest struct {
Identity *string `json:"identity"`
TaskID int64 `json:"task_id"`
Action taskstate.Action `json:"action"`
Actor *actorPayload `json:"actor,omitempty"`
}
type actorPayload struct {
ID string `json:"id"`
Kind string `json:"kind"`
Principal string `json:"principal"`
}
func (p *actorPayload) actor() taskactions.Actor {
if p == nil {
return taskactions.Actor{}
}
return taskactions.Actor{
Identity: identity.IdentityID(p.ID),
Kind: identity.Kind(p.Kind),
Principal: identity.IdentityID(p.Principal),
}
}
// actionResponse carries the error's class beside its message. This hop
@@ -100,7 +120,7 @@ func Register(nc *nats.Conn, service taskactions.Service, log *slog.Logger) (fun
natsrpc.Respond(msg, log, "taskactions", actionResponse{Envelope: natsrpc.NewEnvelope(err)})
return
}
err := service.Apply(context.Background(), req.Identity, taskactions.Actor{}, req.TaskID, req.Action)
err := service.Apply(context.Background(), req.Identity, req.Actor.actor(), req.TaskID, req.Action)
natsrpc.Respond(msg, log, "taskactions", actionResponse{
Envelope: natsrpc.NewEnvelope(err),
Kind: actionErrorKind(err),
@@ -119,12 +139,24 @@ func (c Client) rpc() *natsrpc.Client {
return &natsrpc.Client{Conn: c.Conn, Timeout: c.Timeout}
}
// ApplyChatTaskAction sends an operator action to the daemon's responder.
func (c Client) ApplyChatTaskAction(ctx context.Context, identity *string, id int64, action taskstate.Action) (gateway.TaskActionResult, error) {
// ApplyChatTaskAction sends an action to the daemon's responder, carrying the
// scope and the actor the caller resolved. A caller with no verified identity
// passes the zero actor, which the daemon records as unattributed.
func (c Client) ApplyChatTaskAction(ctx context.Context, scope *string, actor taskactions.Actor, id int64, action taskstate.Action) (gateway.TaskActionResult, error) {
if c.Conn == nil {
return gateway.TaskActionResult{}, fmt.Errorf("task action connection is unavailable")
}
resp, err := natsrpc.Call[actionResponse](ctx, c.rpc(), actionSubject, actionRequest{Identity: identity, TaskID: id, Action: action})
request := actionRequest{
Identity: scope,
TaskID: id,
Action: action,
Actor: &actorPayload{
ID: string(actor.Identity),
Kind: string(actor.Kind),
Principal: string(actor.Principal),
},
}
resp, err := natsrpc.Call[actionResponse](ctx, c.rpc(), actionSubject, request)
if err != nil {
return gateway.TaskActionResult{}, err
}
@@ -105,7 +105,7 @@ func TestActionErrorKeepsItsSentinelAcrossNATS(t *testing.T) {
t.Fatalf("flush: %v", err)
}
_, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, 7, tc.action)
_, err = Client{Conn: nc}.ApplyChatTaskAction(t.Context(), nil, domain.Actor{}, 7, tc.action)
if err == nil {
t.Fatalf("ApplyChatTaskAction(%s) error = nil, want %v", tc.action, tc.want)
}
@@ -152,7 +152,7 @@ func TestActionScopeCrossesNATS(t *testing.T) {
t.Fatalf("flush: %v", err)
}
result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, 7, taskstate.ActionAbandon)
result, err := Client{Conn: nc}.ApplyChatTaskAction(t.Context(), tc.identity, domain.Actor{}, 7, taskstate.ActionAbandon)
if err != nil {
t.Fatalf("apply: %v", err)
}
+9 -1
View File
@@ -344,7 +344,15 @@ func (s *Server) applyOperatorTaskAction(ctx context.Context, id int64, action t
if s.Chat == nil || s.Chat.Contract == nil {
return fmt.Errorf("%w: no gateway contract is wired", taskactions.ErrUnavailable)
}
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, id, action)
// The actor comes from the credential the middleware resolved and never from
// the request, so a caller cannot claim to be someone it did not authenticate
// as. An unauthenticated request (the shared-token gate) carries no identity,
// and the action is then recorded unattributed rather than as a human's.
actor := taskactions.Actor{}
if value, ok := ActingIdentity(ctx); ok {
actor = taskactions.ActorFor(value)
}
_, err := s.Chat.Contract.ApplyOperatorTaskAction(ctx, actor, id, action)
return err
}
+2 -2
View File
@@ -70,7 +70,7 @@ type daemonActions struct {
}
func (d *daemonActions) ApplyChatTaskAction(
ctx context.Context, identity *string, id int64, action taskstate.Action,
ctx context.Context, identity *string, actor taskactions.Actor, id int64, action taskstate.Action,
) (gateway.TaskActionResult, error) {
d.scopes = append(d.scopes, identity)
service := taskactionstore.NewService(
@@ -82,7 +82,7 @@ func (d *daemonActions) ApplyChatTaskAction(
d.publish(),
d.srv.logf,
)
if err := service.Apply(ctx, identity, taskactions.Actor{}, id, action); err != nil {
if err := service.Apply(ctx, identity, actor, id, action); err != nil {
return gateway.TaskActionResult{}, err
}
return gateway.TaskActionResult{TaskID: id, Action: string(action)}, nil
+158
View File
@@ -0,0 +1,158 @@
package webui
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/samcharles93/archie-core/internal/domain/identity"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/events"
)
// postActionWithCredential posts an operator action the way an authenticated
// caller does: JSON, the CSRF header, and the bearer token the middleware
// resolves.
func postActionWithCredential(t *testing.T, srv *Server, id int64, action, credential string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
"/api/tasks/"+strconv.FormatInt(id, 10)+"/action",
bytes.NewBufferString(fmt.Sprintf(`{"action":%q}`, action)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
req.Header.Set("Authorization", "Bearer "+credential)
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
return w
}
// approvalEvent returns the recorded approval on a task's timeline.
func approvalEvent(t *testing.T, srv *Server, taskID int64) events.Event {
t.Helper()
recorded, err := srv.Store.TaskEvents(t.Context(), taskID)
if err != nil {
t.Fatalf("TaskEvents: %v", err)
}
for _, event := range recorded {
if event.Kind == events.KindHumanApproved || event.Kind == events.KindAgentApproved || event.Kind == events.KindTaskApproved {
return event
}
}
t.Fatalf("no approval was recorded on task %d (events: %+v)", taskID, recorded)
return events.Event{}
}
// TestApprovalRecordsTheVerifiedActor is the flip this whole boundary exists for:
// a dashboard approval is recorded as the person whose credential verified, and an
// agent's token is recorded as the agent's action -- not as task_approved for both,
// and never as a human's.
func TestApprovalRecordsTheVerifiedActor(t *testing.T) {
tests := []struct {
name string
identity identity.Identity
wantKind string
wantActor string
}{
{
name: "a person's credential is recorded as that person",
identity: identity.Identity{ID: "50000000-0000-5000-8000-000000000001", Kind: identity.KindUser, DisplayName: "sam", Lifecycle: identity.LifecycleActive},
wantKind: events.KindHumanApproved,
wantActor: "50000000-0000-5000-8000-000000000001",
},
{
name: "an agent's credential is recorded as the agent",
identity: identity.Identity{ID: "50000000-0000-5000-8000-000000000002", Kind: identity.KindBot, DisplayName: "archie-web", Lifecycle: identity.LifecycleActive},
wantKind: events.KindAgentApproved,
wantActor: "50000000-0000-5000-8000-000000000002",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
// The middleware resolves a verified credential to this identity, which
// is the only place the actor may come from.
srv.Authenticate = func(context.Context, string) (identity.Identity, error) {
return tc.identity, nil
}
// The request also claims an identity of its own, which must be ignored.
w := postActionWithCredential(t, srv, task.ID, "approve", "a-provider-token")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d (body %q)", w.Code, http.StatusOK, w.Body.String())
}
recorded := approvalEvent(t, srv, task.ID)
if recorded.ActorID != tc.wantActor {
t.Fatalf("actor = %q, want %q", recorded.ActorID, tc.wantActor)
}
if recorded.ActorKind != string(tc.identity.Kind) {
t.Fatalf("actor kind = %q, want %q", recorded.ActorKind, tc.identity.Kind)
}
if recorded.Kind != tc.wantKind {
t.Fatalf("event kind = %q, want %q", recorded.Kind, tc.wantKind)
}
})
}
}
// TestUnverifiedApprovalIsRecordedUnattributed: with no provider configured the
// shared-token gate still admits a request, and that request carries no identity
// -- so the action is recorded unattributed rather than credited to a human.
func TestUnverifiedApprovalIsRecordedUnattributed(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
w := postAction(t, srv, task.ID, "approve")
if w.Code != http.StatusOK {
t.Fatalf("status = %d, want %d (body %q)", w.Code, http.StatusOK, w.Body.String())
}
recorded := approvalEvent(t, srv, task.ID)
if recorded.ActorID != "" || recorded.ActorKind != "" || recorded.PrincipalID != "" {
t.Fatalf("an unattributed approval recorded an actor: %+v", recorded)
}
if recorded.Kind != events.KindTaskApproved {
t.Fatalf("event kind = %q, want %q", recorded.Kind, events.KindTaskApproved)
}
}
// TestActionRequestCannotChooseItsActor: the body is read for the action only.
// Nothing a caller can put in the request may select the identity recorded.
func TestActionRequestCannotChooseItsActor(t *testing.T) {
srv, task, _, _, _ := actionServer(t, workflow.StatusWaitingHuman, "needs a decision")
verified := identity.Identity{ID: "50000000-0000-5000-8000-000000000003", Kind: identity.KindUser, DisplayName: "sam", Lifecycle: identity.LifecycleActive}
srv.Authenticate = func(context.Context, string) (identity.Identity, error) { return verified, nil }
body := map[string]any{"action": "approve", "actor": "forged", "actor_id": "forged", "identity": "forged"}
encoded, err := json.Marshal(body)
if err != nil {
t.Fatal(err)
}
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost,
"/api/tasks/"+strconv.FormatInt(task.ID, 10)+"/action", bytes.NewReader(encoded))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Archie-CSRF", "1")
req.Header.Set("Authorization", "Bearer a-provider-token")
req.Header.Set("X-Archie-Actor", "forged")
w := httptest.NewRecorder()
srv.Handler().ServeHTTP(w, req)
// The body carries fields the decoder rejects, which is the point: there is no
// accepted way to name an actor, so the request is refused rather than
// silently attributed.
if w.Code == http.StatusOK {
recorded := approvalEvent(t, srv, task.ID)
if recorded.ActorID != string(verified.ID) {
t.Fatalf("actor = %q, want the verified %q", recorded.ActorID, verified.ID)
}
return
}
if w.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400 or 200 with the verified actor", w.Code)
}
}