diff --git a/cmd/archie-ui/main.go b/cmd/archie-ui/main.go index 0941d277d..6c7e59d2a 100644 --- a/cmd/archie-ui/main.go +++ b/cmd/archie-ui/main.go @@ -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() diff --git a/cmd/archie-ui/main_test.go b/cmd/archie-ui/main_test.go index afdb9504a..fc8fc2cee 100644 --- a/cmd/archie-ui/main_test.go +++ b/cmd/archie-ui/main_test.go @@ -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)) diff --git a/internal/app/archied/main.go b/internal/app/archied/main.go index a362f6902..d5910d42a 100644 --- a/internal/app/archied/main.go +++ b/internal/app/archied/main.go @@ -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) } diff --git a/internal/app/archied/task_action_adapter_test.go b/internal/app/archied/task_action_adapter_test.go index 557489c49..a49b4915a 100644 --- a/internal/app/archied/task_action_adapter_test.go +++ b/internal/app/archied/task_action_adapter_test.go @@ -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") } diff --git a/internal/app/archieui/auth.go b/internal/app/archieui/auth.go new file mode 100644 index 000000000..51b5b136a --- /dev/null +++ b/internal/app/archieui/auth.go @@ -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 +} diff --git a/internal/app/archieui/options.go b/internal/app/archieui/options.go index 2a2ce2b14..c94b38a2b 100644 --- a/internal/app/archieui/options.go +++ b/internal/app/archieui/options.go @@ -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. diff --git a/internal/app/archieui/run.go b/internal/app/archieui/run.go index ff04ac393..a50fba15c 100644 --- a/internal/app/archieui/run.go +++ b/internal/app/archieui/run.go @@ -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 diff --git a/internal/app/archieui/run_test.go b/internal/app/archieui/run_test.go index 7bb96c446..811b05cc7 100644 --- a/internal/app/archieui/run_test.go +++ b/internal/app/archieui/run_test.go @@ -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 } diff --git a/internal/channels/telegram/fake_test.go b/internal/channels/telegram/fake_test.go index ab09cbc1b..39ae67f64 100644 --- a/internal/channels/telegram/fake_test.go +++ b/internal/channels/telegram/fake_test.go @@ -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 } diff --git a/internal/domain/messaging/chat_contract.go b/internal/domain/messaging/chat_contract.go index 3937ae900..63a2fa218 100644 --- a/internal/domain/messaging/chat_contract.go +++ b/internal/domain/messaging/chat_contract.go @@ -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. diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index 36865a099..b7b6ac1f3 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -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 diff --git a/internal/gateway/chat_local.go b/internal/gateway/chat_local.go index 19ca14599..218351df5 100644 --- a/internal/gateway/chat_local.go +++ b/internal/gateway/chat_local.go @@ -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) { diff --git a/internal/gateway/task_action_tool_test.go b/internal/gateway/task_action_tool_test.go index 59a24df01..0432e5b46 100644 --- a/internal/gateway/task_action_tool_test.go +++ b/internal/gateway/task_action_tool_test.go @@ -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 } diff --git a/internal/gateway/task_tools.go b/internal/gateway/task_tools.go index b07a7bc68..88cb409fe 100644 --- a/internal/gateway/task_tools.go +++ b/internal/gateway/task_tools.go @@ -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) } diff --git a/internal/infrastructure/gatewayrpc/client.go b/internal/infrastructure/gatewayrpc/client.go index f66988820..8abfd4d55 100644 --- a/internal/infrastructure/gatewayrpc/client.go +++ b/internal/infrastructure/gatewayrpc/client.go @@ -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) } diff --git a/internal/infrastructure/gatewayrpc/conformance_test.go b/internal/infrastructure/gatewayrpc/conformance_test.go index fc472dae3..52f749398 100644 --- a/internal/infrastructure/gatewayrpc/conformance_test.go +++ b/internal/infrastructure/gatewayrpc/conformance_test.go @@ -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) } diff --git a/internal/infrastructure/gatewayrpc/server.go b/internal/infrastructure/gatewayrpc/server.go index e57fc6511..a8bcd7034 100644 --- a/internal/infrastructure/gatewayrpc/server.go +++ b/internal/infrastructure/gatewayrpc/server.go @@ -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) } diff --git a/internal/infrastructure/taskactions/rpc.go b/internal/infrastructure/taskactions/rpc.go index 58ad4b6a8..09d02caf5 100644 --- a/internal/infrastructure/taskactions/rpc.go +++ b/internal/infrastructure/taskactions/rpc.go @@ -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 } diff --git a/internal/infrastructure/taskactions/rpc_test.go b/internal/infrastructure/taskactions/rpc_test.go index 2b62cbacd..39b4e974a 100644 --- a/internal/infrastructure/taskactions/rpc_test.go +++ b/internal/infrastructure/taskactions/rpc_test.go @@ -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) } diff --git a/internal/webui/api_tasks.go b/internal/webui/api_tasks.go index 11b8c011e..18c299730 100644 --- a/internal/webui/api_tasks.go +++ b/internal/webui/api_tasks.go @@ -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 } diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 4fda273ee..cd27650a7 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -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 diff --git a/internal/webui/api_tasks_actor_test.go b/internal/webui/api_tasks_actor_test.go new file mode 100644 index 000000000..4a2d229e1 --- /dev/null +++ b/internal/webui/api_tasks_actor_test.go @@ -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) + } +}