feat(audit,approvals,deliveries): wire audit producers, ITSM change requests, and fix Dockerfile.archie (#2153)
This commit is contained in:
26 files changed
+671
-35
No files matched your search
@@ -5,6 +5,7 @@
|
||||
package approvals
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json/jsontext"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/hub"
|
||||
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/deliveries"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
@@ -273,6 +275,7 @@ type Module struct {
|
||||
authz governance.Authorizer
|
||||
confirm Confirmer
|
||||
changes ChangeRequests
|
||||
audit audit.Recorder
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
@@ -285,6 +288,10 @@ func NewModule(db *sqlx.DB, log *slog.Logger, orgID string, tell Delivery, wake
|
||||
}
|
||||
}
|
||||
|
||||
// UseAudit configures the audit recorder notified on approval requests, decisions,
|
||||
// refusals, and expirations.
|
||||
func (m *Module) UseAudit(r audit.Recorder) { m.audit = r }
|
||||
|
||||
// UseLive publishes a note on the hub whenever a request moves, so a mounted
|
||||
// view re-reads instead of polling.
|
||||
func (m *Module) UseLive(h *hub.Hub) {
|
||||
@@ -340,15 +347,27 @@ func (m *Module) Ask(ctx context.Context, runID uuid.UUID, key string, ds []judg
|
||||
if err := m.changes.Open(ctx, r); err != nil {
|
||||
return Request{}, fmt.Errorf("open change request: %w", err)
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{
|
||||
} else if err := m.tell.Ask(ctx, deliveries.ApprovalRequest{
|
||||
RunID: r.RunID, RequestID: r.ID, Key: r.Key + ":ask",
|
||||
Title: approvalTitle(ds),
|
||||
Body: r.Summary, ExpiresAt: r.StepDeadline,
|
||||
}); err != nil {
|
||||
return Request{}, fmt.Errorf("send approval request: %w", err)
|
||||
}
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "approval",
|
||||
Action: "approval.request",
|
||||
ActorID: cmp.Or(r.InitiatorID, string(governance.WorkloadID)),
|
||||
ResourceKind: "approval",
|
||||
ResourceID: r.ID.String(),
|
||||
Outcome: StatePending,
|
||||
Detail: map[string]any{
|
||||
"connector": r.Connector,
|
||||
"action": r.Action,
|
||||
"change_request": r.ChangeRequest,
|
||||
"require_sod": r.RequireSoD,
|
||||
},
|
||||
})
|
||||
return r, nil
|
||||
}
|
||||
|
||||
@@ -408,6 +427,19 @@ func (m *Module) answerAs(ctx context.Context, id uuid.UUID, who Answerer, via s
|
||||
if row.State != state {
|
||||
return Request{}, fmt.Errorf("%w: %s", ErrAnswered, row.State)
|
||||
}
|
||||
action := "approval.deny"
|
||||
if approved {
|
||||
action = "approval.approve"
|
||||
}
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "approval",
|
||||
Action: action,
|
||||
ActorID: cmp.Or(who.ID, who.Name, "unknown"),
|
||||
ActorKind: via,
|
||||
ResourceKind: "approval",
|
||||
ResourceID: row.ID.String(),
|
||||
Outcome: state,
|
||||
})
|
||||
answer := Answer{RequestID: row.ID, Approved: approved, By: who.Name, ByID: who.ID, Via: via, At: now}
|
||||
if row.Kind == KindAutonomy {
|
||||
if err := m.answerProposal(ctx, row, answer); err != nil {
|
||||
@@ -525,6 +557,16 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
|
||||
if refusal(err) {
|
||||
identity := who.Issuer + ":" + who.Subject
|
||||
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", err.Error())
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "approval",
|
||||
Action: "approval.refuse",
|
||||
ActorID: identity,
|
||||
ActorKind: via,
|
||||
ResourceKind: "approval",
|
||||
ResourceID: id.String(),
|
||||
Outcome: "denied",
|
||||
Detail: map[string]any{"reason": err.Error()},
|
||||
})
|
||||
if rerr := m.store.Refuse(ctx, store.Refusal{
|
||||
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: via, Reason: err.Error(), At: m.now().UTC(),
|
||||
}); rerr != nil {
|
||||
@@ -548,6 +590,34 @@ func (m *Module) Settle(ctx context.Context, id uuid.UUID, who governance.Subjec
|
||||
return false, err
|
||||
}
|
||||
|
||||
// SettleChangeRequest settles a pending change-request approval from an
|
||||
// external ITSM decision event. Missing, already-settled, expired, or
|
||||
// non-change-request items return (false, nil).
|
||||
func (m *Module) SettleChangeRequest(ctx context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error) {
|
||||
row, err := m.store.ByID(ctx, m.orgID, id)
|
||||
if errors.Is(err, ErrNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if !row.ChangeRequest || row.State != StatePending {
|
||||
return false, nil
|
||||
}
|
||||
who := Answerer{
|
||||
ID: connector + ":" + changeNumber,
|
||||
Name: strings.TrimSpace(connector + " " + changeNumber),
|
||||
}
|
||||
_, err = m.answerAs(ctx, id, who, connector, approved)
|
||||
switch {
|
||||
case err == nil:
|
||||
return true, nil
|
||||
case errors.Is(err, ErrAnswered), errors.Is(err, ErrExpired), errors.Is(err, ErrNotFound):
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
// channelAnswerer returns the account that holds the channel credential when
|
||||
// that account may answer row.
|
||||
func (m *Module) channelAnswerer(ctx context.Context, who governance.Subject, row store.Request) (Answerer, error) {
|
||||
@@ -660,6 +730,15 @@ func (m *Module) Expire(ctx context.Context, id uuid.UUID) error {
|
||||
return nil
|
||||
}
|
||||
m.log.InfoContext(ctx, "approval request expired", "request", row.ID, "run", row.RunID)
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "approval",
|
||||
Action: "approval.expire",
|
||||
ActorID: "clock",
|
||||
ActorKind: "system",
|
||||
ResourceKind: "approval",
|
||||
ResourceID: row.ID.String(),
|
||||
Outcome: StateExpired,
|
||||
})
|
||||
withdrawn := ""
|
||||
if row.ChangeRequest {
|
||||
if err := m.changes.Withdraw(ctx, requestOf(row, judgement.Decision{})); err != nil {
|
||||
|
||||
@@ -3,12 +3,14 @@ package approvals
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
)
|
||||
@@ -296,3 +298,23 @@ func TestSoDRefusesSelfApproval(t *testing.T) {
|
||||
t.Fatal("requireSoDOf override true returned false")
|
||||
}
|
||||
}
|
||||
|
||||
type recordedAudit []audit.Event
|
||||
|
||||
func (r *recordedAudit) Record(_ context.Context, e audit.Event) error {
|
||||
*r = append(*r, e)
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestUseAuditRecordsRefusals(t *testing.T) {
|
||||
var rec recordedAudit
|
||||
m := &Module{log: slog.New(slog.DiscardHandler)}
|
||||
m.UseAudit(&rec)
|
||||
audit.Emit(t.Context(), m.audit, m.log, audit.Event{
|
||||
Category: "approval", Action: "approval.refuse", ActorID: "alice",
|
||||
ResourceKind: "approval", ResourceID: uuid.NewString(), Outcome: "denied",
|
||||
})
|
||||
if len(rec) != 1 || rec[0].Action != "approval.refuse" || rec[0].Outcome != "denied" {
|
||||
t.Fatalf("recorded audit events = %+v", rec)
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/approvals/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement"
|
||||
@@ -196,6 +197,16 @@ func (m *Module) refuse(ctx context.Context, id uuid.UUID, identity string, reas
|
||||
identity = "shared-token"
|
||||
}
|
||||
m.log.WarnContext(ctx, "approval answer refused", "request", id, "identity", identity, "reason", reason.Error())
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "approval",
|
||||
Action: "approval.refuse",
|
||||
ActorID: identity,
|
||||
ActorKind: viaDashboard,
|
||||
ResourceKind: "approval",
|
||||
ResourceID: id.String(),
|
||||
Outcome: "denied",
|
||||
Detail: map[string]any{"reason": reason.Error()},
|
||||
})
|
||||
if err := m.store.Refuse(ctx, store.Refusal{
|
||||
ID: uuid.New(), OrgID: m.orgID, RequestID: id, Identity: identity, Via: viaDashboard, Reason: reason.Error(), At: m.now().UTC(),
|
||||
}); err != nil {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
@@ -75,6 +76,29 @@ type auditStore interface {
|
||||
List(ctx context.Context, f store.Filter) ([]store.EventRow, error)
|
||||
}
|
||||
|
||||
// Recorder records immutable security and operational audit events.
|
||||
type Recorder interface {
|
||||
Record(ctx context.Context, e Event) error
|
||||
}
|
||||
|
||||
// Emit forwards e to r when r is configured, logging any persistence error to
|
||||
// log without failing the caller's operation.
|
||||
func Emit(ctx context.Context, r Recorder, log *slog.Logger, e Event) {
|
||||
if r == nil {
|
||||
return
|
||||
}
|
||||
v := reflect.ValueOf(r)
|
||||
if v.Kind() == reflect.Pointer && v.IsNil() {
|
||||
return
|
||||
}
|
||||
if m, ok := r.(*Module); ok && m.store == nil {
|
||||
return
|
||||
}
|
||||
if err := r.Record(ctx, e); err != nil && log != nil {
|
||||
log.WarnContext(ctx, "record audit event", "category", e.Category, "action", e.Action, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Module records and serves one organisation's append-only audit stream.
|
||||
type Module struct {
|
||||
orgID string
|
||||
|
||||
@@ -15,14 +15,17 @@ import (
|
||||
// the extension contract: a connector that declares one must declare a schema
|
||||
// that accepts what core sends.
|
||||
const (
|
||||
DeliveryMessage = "message"
|
||||
DeliveryChatMessage = "chat_message"
|
||||
DeliveryMessage = "message"
|
||||
DeliveryChatMessage = "chat_message"
|
||||
DeliveryChangeRequest = "change_request"
|
||||
DeliveryChangeRequestWithdraw = "change_request_withdraw"
|
||||
)
|
||||
|
||||
// coreDeliveries lists, for each delivery core sends itself, every payload
|
||||
// shape core may put in it: a message always has a title, and may also carry
|
||||
// a body and, for an approval request, its request id; a chat message always
|
||||
// has a chat id and text.
|
||||
// has a chat id and text; change requests carry short_description and
|
||||
// description; withdrawals carry key and reason.
|
||||
var coreDeliveries = map[string][]jsontext.Value{
|
||||
DeliveryMessage: {
|
||||
jsontext.Value(`{"title":"a title"}`),
|
||||
@@ -33,13 +36,19 @@ var coreDeliveries = map[string][]jsontext.Value{
|
||||
DeliveryChatMessage: {
|
||||
jsontext.Value(`{"chat_id":"a chat","text":"a message"}`),
|
||||
},
|
||||
DeliveryChangeRequest: {
|
||||
jsontext.Value(`{"short_description":"a change","description":"details"}`),
|
||||
},
|
||||
DeliveryChangeRequestWithdraw: {
|
||||
jsontext.Value(`{"key":"req:change_request","reason":"approval expired"}`),
|
||||
},
|
||||
}
|
||||
|
||||
// checkCoreDeliveries refuses a declaration of a delivery core sends itself
|
||||
// whose input schema rejects a payload core sends, so the mismatch surfaces
|
||||
// when the connector loads rather than when a delivery is mid-flight.
|
||||
func checkCoreDeliveries(caps Capabilities) error {
|
||||
for _, name := range []string{DeliveryMessage, DeliveryChatMessage} {
|
||||
for _, name := range []string{DeliveryMessage, DeliveryChatMessage, DeliveryChangeRequest, DeliveryChangeRequestWithdraw} {
|
||||
d, ok := caps.Delivery(name)
|
||||
if !ok {
|
||||
continue
|
||||
|
||||
@@ -110,6 +110,7 @@ func (m *Module) saveCatalogueSource(ctx context.Context, src store.Source) (*ht
|
||||
return nil, huma.NewError(http.StatusInternalServerError, "couldn't save the catalogue source")
|
||||
}
|
||||
m.log.InfoContext(ctx, "catalogue source set", "audit", true, "action", "catalogue.source")
|
||||
m.emitAudit(ctx, "catalogue.source", "catalogue", src.Location, nil)
|
||||
return m.getCatalogueSource(ctx, nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -251,6 +251,7 @@ func (m *Module) saveInstallation(ctx context.Context, auth authority, a store.I
|
||||
}
|
||||
m.log.InfoContext(ctx, "installation saved", "audit", true, "action", "installation.save",
|
||||
"installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName)
|
||||
m.emitAudit(ctx, "installation.save", "installation", a.ID.String(), map[string]any{"scope": a.Scope, "package": a.PackageName})
|
||||
view, err := m.viewOf(a, auth.manages(a.Owner()))
|
||||
if err != nil {
|
||||
return nil, huma.NewError(http.StatusInternalServerError, err.Error())
|
||||
|
||||
@@ -20,8 +20,10 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/seal"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/catalogue"
|
||||
"github.com/samcharles93/archie-core/modules/connectors/internal/store"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
// validName is the shape of a connector name: it appears in logs and URLs.
|
||||
@@ -35,6 +37,7 @@ type Module struct {
|
||||
host *Host
|
||||
store registry
|
||||
sealer *seal.Sealer
|
||||
audit audit.Recorder
|
||||
log *slog.Logger
|
||||
// sources and fetcher read the catalogue and its artifacts, and pkgMu
|
||||
// serialises changes to a package's versions.
|
||||
@@ -80,6 +83,21 @@ func (m *Module) Use(recheck Recheck) {
|
||||
m.recheck = recheck
|
||||
}
|
||||
|
||||
// UseAudit configures the audit recorder notified on extension and catalogue changes.
|
||||
func (m *Module) UseAudit(r audit.Recorder) { m.audit = r }
|
||||
|
||||
func (m *Module) emitAudit(ctx context.Context, action, resourceKind, resourceID string, detail any) {
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "extensions",
|
||||
Action: action,
|
||||
ActorID: governance.CallerID(ctx),
|
||||
ResourceKind: resourceKind,
|
||||
ResourceID: resourceID,
|
||||
Outcome: "success",
|
||||
Detail: detail,
|
||||
})
|
||||
}
|
||||
|
||||
// UseRemotes configures static remote gRPC+mTLS extension endpoints.
|
||||
func (m *Module) UseRemotes(cfg RemoteConfig) error {
|
||||
return m.host.UseRemotes(cfg)
|
||||
|
||||
@@ -137,6 +137,7 @@ func (m *Module) register(ctx context.Context, source catalogueSnapshot, entry c
|
||||
}
|
||||
m.log.InfoContext(ctx, "package version registered", "audit", true, "action", "package.register",
|
||||
"package", entry.Name, "version", v.Version, "digest", v.Digest)
|
||||
m.emitAudit(ctx, "package.register", "package", entry.Name, map[string]any{"version": v.Version, "digest": v.Digest})
|
||||
return pkg, ver, nil
|
||||
}
|
||||
|
||||
@@ -183,6 +184,7 @@ func (m *Module) acceptGrants(ctx context.Context, v store.Version, want *grants
|
||||
}
|
||||
m.log.InfoContext(ctx, "package version accepted", "audit", true, "action", "package.accept",
|
||||
"version_id", v.ID.String(), "version", v.Version)
|
||||
m.emitAudit(ctx, "package.accept", "package_version", v.ID.String(), map[string]any{"version": v.Version})
|
||||
return accepted, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,7 @@ func (m *Module) removeAs(ctx context.Context, in *nameInput, contract string) (
|
||||
// There is no audit trail module yet, so the removal is a structured log
|
||||
// line.
|
||||
m.log.InfoContext(ctx, "accepted package removed", "audit", true, "action", "package.remove", "contract", contract, "package", name)
|
||||
m.emitAudit(ctx, "package.remove", "package", name, map[string]any{"contract": contract})
|
||||
return httpapi.OK(packageState{Name: name, State: "removed"}), nil
|
||||
}
|
||||
|
||||
@@ -143,6 +144,7 @@ func (m *Module) removeInstallation(ctx context.Context, in *installationInput)
|
||||
}
|
||||
m.log.InfoContext(ctx, "installation removed", "audit", true, "action", "installation.remove",
|
||||
"installation", a.ID.String(), "scope", a.Scope, "package", a.PackageName)
|
||||
m.emitAudit(ctx, "installation.remove", "installation", a.ID.String(), map[string]any{"scope": a.Scope, "package": a.PackageName})
|
||||
return httpapi.OK(packageState{Name: a.Name, State: "removed"}), nil
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package deliveries
|
||||
|
||||
import (
|
||||
"context"
|
||||
json "encoding/json/v2"
|
||||
"log/slog"
|
||||
"slices"
|
||||
"strings"
|
||||
@@ -105,3 +106,42 @@ func TestDeliveryIsAuthorizedOnEveryAttempt(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenChangeRequestFailsWithoutConnectorAndFormatsPayloads(t *testing.T) {
|
||||
m := &Module{channels: &channelLookups{}, log: slog.New(slog.DiscardHandler)}
|
||||
if err := m.OpenChangeRequest(t.Context(), ChangeRequest{
|
||||
RunID: uuid.New(),
|
||||
RequestID: uuid.New(),
|
||||
Key: "step:1",
|
||||
ShortDescription: "Restart prod app",
|
||||
Description: "Verdict summary",
|
||||
}); err == nil || !strings.Contains(err.Error(), "no running connector") {
|
||||
t.Fatalf("OpenChangeRequest without connector = %v, want missing connector error", err)
|
||||
}
|
||||
|
||||
kind, raw, err := deliveryPayload(store.Message{
|
||||
Kind: KindChangeRequest,
|
||||
Title: "Short summary",
|
||||
Body: "Full action details",
|
||||
})
|
||||
if err != nil || kind != connectors.DeliveryChangeRequest {
|
||||
t.Fatalf("deliveryPayload(change_request) = (%q, %v)", kind, err)
|
||||
}
|
||||
var cr map[string]string
|
||||
if err := json.Unmarshal(raw, &cr); err != nil || cr["short_description"] != "Short summary" || cr["description"] != "Full action details" {
|
||||
t.Fatalf("unexpected change_request payload: %s (%v)", raw, err)
|
||||
}
|
||||
|
||||
kind, raw, err = deliveryPayload(store.Message{
|
||||
Kind: KindChangeRequestWithdraw,
|
||||
Title: "approval timed out",
|
||||
Body: "step:1:change_request",
|
||||
})
|
||||
if err != nil || kind != connectors.DeliveryChangeRequestWithdraw {
|
||||
t.Fatalf("deliveryPayload(change_request_withdraw) = (%q, %v)", kind, err)
|
||||
}
|
||||
var wd map[string]string
|
||||
if err := json.Unmarshal(raw, &wd); err != nil || wd["key"] != "step:1:change_request" || wd["reason"] != "approval timed out" {
|
||||
t.Fatalf("unexpected change_request_withdraw payload: %s (%v)", raw, err)
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,10 @@ const (
|
||||
KindApprovalRequest = "approval_request"
|
||||
// KindApprovalAnswer records what they answered.
|
||||
KindApprovalAnswer = "approval_answer"
|
||||
// KindChangeRequest opens an external change request for an approval.
|
||||
KindChangeRequest = "change_request"
|
||||
// KindChangeRequestWithdraw withdraws an open external change request.
|
||||
KindChangeRequestWithdraw = "change_request_withdraw"
|
||||
)
|
||||
|
||||
// Notification is something a run tells people: what happened, what was done,
|
||||
@@ -76,6 +80,15 @@ type ApprovalRequest struct {
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// ChangeRequest is an approval routed through an external ITSM system.
|
||||
type ChangeRequest struct {
|
||||
RunID uuid.UUID
|
||||
RequestID uuid.UUID
|
||||
Key string
|
||||
ShortDescription string
|
||||
Description string
|
||||
}
|
||||
|
||||
// Message is a composer message as the API shows it. Attempts are the delivery
|
||||
// attempts recorded on the connector rows that carry the same message, one per
|
||||
// channel.
|
||||
@@ -194,6 +207,64 @@ func (m *Module) Told(ctx context.Context, a ApprovalRequest, answer string) err
|
||||
})
|
||||
}
|
||||
|
||||
// OpenChangeRequest queues a change_request delivery on every running connector
|
||||
// that declares it, failing closed when no such connector is running.
|
||||
func (m *Module) OpenChangeRequest(ctx context.Context, cr ChangeRequest) error {
|
||||
if cr.Key == "" {
|
||||
return errors.New("a change request needs a key")
|
||||
}
|
||||
targets := m.channels.Delivering(ctx, connectors.DeliveryChangeRequest)
|
||||
if len(targets) == 0 {
|
||||
return errors.New("no running connector supports change_request delivery")
|
||||
}
|
||||
if _, _, err := m.store.Insert(ctx, store.Message{
|
||||
ID: uuid.New(), OrgID: m.orgID, Channel: channelComposer, Kind: KindNotification,
|
||||
RunID: uuid.NullUUID{UUID: cr.RunID, Valid: cr.RunID != uuid.Nil},
|
||||
Title: cr.ShortDescription, Body: cr.Description, Key: cr.Key + ":change_request:opened", Sent: true,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, c := range targets {
|
||||
if _, _, err := m.store.Insert(ctx, store.Message{
|
||||
ID: uuid.New(), OrgID: m.orgID, Channel: c.Name(), Kind: KindChangeRequest,
|
||||
RunID: uuid.NullUUID{UUID: cr.RunID, Valid: cr.RunID != uuid.Nil},
|
||||
RequestID: uuid.NullUUID{UUID: cr.RequestID, Valid: cr.RequestID != uuid.Nil},
|
||||
Title: cr.ShortDescription, Body: cr.Description, Key: cr.Key + ":change_request", Sent: false,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WithdrawChangeRequest queues a change_request_withdraw delivery on every
|
||||
// running connector that declares it.
|
||||
func (m *Module) WithdrawChangeRequest(ctx context.Context, runID, requestID uuid.UUID, key, reason string) error {
|
||||
if key == "" {
|
||||
return errors.New("a change request withdrawal needs a key")
|
||||
}
|
||||
for _, c := range m.channels.Delivering(ctx, connectors.DeliveryChangeRequestWithdraw) {
|
||||
if _, _, err := m.store.Insert(ctx, store.Message{
|
||||
ID: uuid.New(), OrgID: m.orgID, Channel: c.Name(), Kind: KindChangeRequestWithdraw,
|
||||
RunID: uuid.NullUUID{UUID: runID, Valid: runID != uuid.Nil},
|
||||
RequestID: uuid.NullUUID{UUID: requestID, Valid: requestID != uuid.Nil},
|
||||
Title: reason, Body: key + ":change_request", Key: key + ":change_request_withdraw", Sent: false,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequestByExternalID resolves an external change number confirmed on channel
|
||||
// back to its Archie approval request ID.
|
||||
func (m *Module) RequestByExternalID(ctx context.Context, channel, externalID string) (uuid.UUID, bool, error) {
|
||||
if externalID == "" {
|
||||
return uuid.Nil, false, nil
|
||||
}
|
||||
return m.store.RequestByExternalID(ctx, m.orgID, channel, externalID)
|
||||
}
|
||||
|
||||
// send writes msg to the composer, which wakes its readers, and queues it for
|
||||
// every connector that delivers messages. Work sends the queued rows.
|
||||
func (m *Module) send(ctx context.Context, msg store.Message) error {
|
||||
@@ -302,18 +373,38 @@ func (m *Module) sendTo(ctx context.Context, msg store.Message) (string, error)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("connector %q isn't running", msg.Channel)
|
||||
}
|
||||
input := map[string]string{"title": msg.Title}
|
||||
if msg.Body != "" {
|
||||
input["body"] = msg.Body
|
||||
}
|
||||
if msg.Kind == KindApprovalRequest && msg.RequestID.Valid {
|
||||
input["approval_request_id"] = msg.RequestID.UUID.String()
|
||||
}
|
||||
raw, err := json.Marshal(input)
|
||||
deliveryType, raw, err := deliveryPayload(msg)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return c.Deliver(ctx, connectors.DeliveryMessage, raw, msg.Key)
|
||||
return c.Deliver(ctx, deliveryType, raw, msg.Key)
|
||||
}
|
||||
|
||||
func deliveryPayload(msg store.Message) (deliveryType string, raw []byte, err error) {
|
||||
switch msg.Kind {
|
||||
case KindChangeRequest:
|
||||
raw, err = json.Marshal(map[string]string{
|
||||
"short_description": msg.Title,
|
||||
"description": msg.Body,
|
||||
})
|
||||
return connectors.DeliveryChangeRequest, raw, err
|
||||
case KindChangeRequestWithdraw:
|
||||
raw, err = json.Marshal(map[string]string{
|
||||
"key": msg.Body,
|
||||
"reason": msg.Title,
|
||||
})
|
||||
return connectors.DeliveryChangeRequestWithdraw, raw, err
|
||||
default:
|
||||
input := map[string]string{"title": msg.Title}
|
||||
if msg.Body != "" {
|
||||
input["body"] = msg.Body
|
||||
}
|
||||
if msg.Kind == KindApprovalRequest && msg.RequestID.Valid {
|
||||
input["approval_request_id"] = msg.RequestID.UUID.String()
|
||||
}
|
||||
raw, err = json.Marshal(input)
|
||||
return connectors.DeliveryMessage, raw, err
|
||||
}
|
||||
}
|
||||
|
||||
// backoff returns the wait before the next attempt, given the number of
|
||||
|
||||
@@ -164,6 +164,24 @@ func (s *Store) SentBy(ctx context.Context, orgID, channel string, ids []string)
|
||||
return run, true, nil
|
||||
}
|
||||
|
||||
// RequestByExternalID finds the approval request associated with a confirmed
|
||||
// change_request delivery matching externalID on channel.
|
||||
func (s *Store) RequestByExternalID(ctx context.Context, orgID, channel, externalID string) (uuid.UUID, bool, error) {
|
||||
var id uuid.NullUUID
|
||||
err := s.db.GetContext(ctx, &id, `
|
||||
SELECT request_id FROM deliveries.messages
|
||||
WHERE org_id = $1 AND channel = $2 AND kind = 'change_request'
|
||||
AND external_id = $3 AND request_id IS NOT NULL
|
||||
LIMIT 1`, orgID, channel, externalID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return uuid.Nil, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, false, fmt.Errorf("find change request message: %w", err)
|
||||
}
|
||||
return id.UUID, id.Valid, nil
|
||||
}
|
||||
|
||||
// Failed records why an attempt failed, along with the attempt that failed.
|
||||
// The lease that Claim set still decides when the next attempt is due.
|
||||
func (s *Store) Failed(ctx context.Context, seq int64, attempt int, reason string, took time.Duration) error {
|
||||
|
||||
@@ -2,6 +2,7 @@ package events
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
@@ -50,8 +51,84 @@ func (noEcho) SentBy(context.Context, string, ...string) (uuid.UUID, bool, error
|
||||
return uuid.Nil, false, nil
|
||||
}
|
||||
|
||||
func (noEcho) RequestByExternalID(context.Context, string, string) (uuid.UUID, bool, error) {
|
||||
return uuid.Nil, false, nil
|
||||
}
|
||||
|
||||
func (noEcho) Send(context.Context, string, string, string, string) error { return nil }
|
||||
|
||||
type fakeChangeDeliveries struct {
|
||||
noEcho
|
||||
byNumber map[string]uuid.UUID
|
||||
}
|
||||
|
||||
func (f fakeChangeDeliveries) RequestByExternalID(_ context.Context, channel, externalID string) (uuid.UUID, bool, error) {
|
||||
id, ok := f.byNumber[channel+":"+externalID]
|
||||
return id, ok, nil
|
||||
}
|
||||
|
||||
type fakeChangeAnswers struct {
|
||||
settled []struct {
|
||||
id uuid.UUID
|
||||
via string
|
||||
number string
|
||||
approved bool
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeChangeAnswers) Settle(context.Context, uuid.UUID, governance.Subject, string, bool) (bool, error) {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (f *fakeChangeAnswers) SettleChangeRequest(_ context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error) {
|
||||
f.settled = append(f.settled, struct {
|
||||
id uuid.UUID
|
||||
via string
|
||||
number string
|
||||
approved bool
|
||||
}{id: id, via: connector, number: changeNumber, approved: approved})
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func TestDispatchSettlesOwnChangeRequestDecisionEvents(t *testing.T) {
|
||||
reqID := uuid.New()
|
||||
answers := &fakeChangeAnswers{}
|
||||
m := &Module{
|
||||
reader: oneSource{connector: "servicenow"},
|
||||
deliveries: fakeChangeDeliveries{byNumber: map[string]uuid.UUID{"servicenow:CHG0012345": reqID}},
|
||||
answers: answers,
|
||||
log: slog.New(slog.DiscardHandler),
|
||||
}
|
||||
evApproved := store.Event{
|
||||
ID: uuid.New(),
|
||||
OrgID: "default",
|
||||
SourceID: hookSource,
|
||||
DeclaredEventType: changeApprovedType,
|
||||
LinkKey: sql.NullString{String: "CHG0012345", Valid: true},
|
||||
Own: true,
|
||||
}
|
||||
if _, err := m.dispatch(nil, evApproved); err != nil {
|
||||
t.Fatalf("dispatch approved change event: %v", err)
|
||||
}
|
||||
evRejected := evApproved
|
||||
evRejected.ID = uuid.New()
|
||||
evRejected.DeclaredEventType = changeRejectedType
|
||||
evRejected.LinkKey = sql.NullString{}
|
||||
evRejected.Fields = []byte(`{"number":"CHG0012345"}`)
|
||||
if _, err := m.dispatch(nil, evRejected); err != nil {
|
||||
t.Fatalf("dispatch rejected change event: %v", err)
|
||||
}
|
||||
if len(answers.settled) != 2 {
|
||||
t.Fatalf("settled count = %d, want 2", len(answers.settled))
|
||||
}
|
||||
if answers.settled[0].id != reqID || answers.settled[0].via != "servicenow" || answers.settled[0].number != "CHG0012345" || !answers.settled[0].approved {
|
||||
t.Fatalf("unexpected first settlement: %+v", answers.settled[0])
|
||||
}
|
||||
if answers.settled[1].id != reqID || answers.settled[1].approved {
|
||||
t.Fatalf("unexpected second settlement: %+v", answers.settled[1])
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntakeAppliesTheDeliveryPolicyBeforeStoring guards the webhook entry
|
||||
// point: a delivery that passes source verification is still refused when the
|
||||
// per-source, per-address delivery policy denies it or can't be read, and
|
||||
|
||||
+77
-14
@@ -60,6 +60,9 @@ type Runs interface {
|
||||
// belonged to no run.
|
||||
type Deliveries interface {
|
||||
SentBy(ctx context.Context, channel string, ids ...string) (run uuid.UUID, found bool, err error)
|
||||
// RequestByExternalID resolves a confirmed change_request's external ID
|
||||
// back to its approval request ID.
|
||||
RequestByExternalID(ctx context.Context, channel, externalID string) (uuid.UUID, bool, error)
|
||||
// Send writes text to one chat on a channel.
|
||||
Send(ctx context.Context, channel, chatID, text, key string) error
|
||||
}
|
||||
@@ -67,6 +70,7 @@ type Deliveries interface {
|
||||
// Answers settles the approval requests answer events name.
|
||||
type Answers interface {
|
||||
Settle(ctx context.Context, id uuid.UUID, who governance.Subject, via string, approved bool) (bool, error)
|
||||
SettleChangeRequest(ctx context.Context, id uuid.UUID, connector, changeNumber string, approved bool) (bool, error)
|
||||
}
|
||||
|
||||
// Links binds the channel accounts that account.link events name to the
|
||||
@@ -82,8 +86,10 @@ type Links interface {
|
||||
// Both name the sender as "<connector>:<channel user id>" in by, and may name
|
||||
// the chat to reply to in chat_id.
|
||||
const (
|
||||
answerType = "approval.answer"
|
||||
linkType = "account.link"
|
||||
answerType = "approval.answer"
|
||||
linkType = "account.link"
|
||||
changeApprovedType = "change.approved"
|
||||
changeRejectedType = "change.rejected"
|
||||
)
|
||||
|
||||
// listenRetry is how long a listener waits after its stream breaks.
|
||||
@@ -551,6 +557,50 @@ func (m *Module) answer(ctx context.Context, e store.Event) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// settleChange resolves a confirmed change number from change.approved or
|
||||
// change.rejected back to the pending change-request approval and settles it.
|
||||
func (m *Module) settleChange(ctx context.Context, e store.Event, approved bool) error {
|
||||
if !e.SourceID.Valid || m.reader == nil || m.deliveries == nil || m.answers == nil {
|
||||
return nil
|
||||
}
|
||||
src, err := m.reader.Source(ctx, e.OrgID, e.SourceID.UUID)
|
||||
if err != nil {
|
||||
m.log.WarnContext(ctx, "change event from an unknown source", "event", e.ID, "source", e.SourceID.UUID, "error", err)
|
||||
return nil
|
||||
}
|
||||
var changeNumber string
|
||||
if e.LinkKey.Valid {
|
||||
changeNumber = strings.TrimSpace(e.LinkKey.String)
|
||||
}
|
||||
if changeNumber == "" {
|
||||
var f struct {
|
||||
Number string `json:"number"`
|
||||
}
|
||||
if err := json.Unmarshal(e.Fields, &f); err == nil {
|
||||
changeNumber = strings.TrimSpace(f.Number)
|
||||
}
|
||||
}
|
||||
if changeNumber == "" {
|
||||
m.log.WarnContext(ctx, "change event missing link key or change number", "event", e.ID)
|
||||
return nil
|
||||
}
|
||||
reqID, found, err := m.deliveries.RequestByExternalID(ctx, src.Connector, changeNumber)
|
||||
if err != nil {
|
||||
return fmt.Errorf("lookup change request %s: %w", changeNumber, err)
|
||||
}
|
||||
if !found {
|
||||
return nil
|
||||
}
|
||||
settled, err := m.answers.SettleChangeRequest(ctx, reqID, src.Connector, changeNumber, approved)
|
||||
if err != nil {
|
||||
return fmt.Errorf("settle change request %s: %w", reqID, err)
|
||||
}
|
||||
if !settled {
|
||||
m.log.InfoContext(ctx, "change request decision changed nothing", "event", e.ID, "request", reqID, "change", changeNumber)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// link binds the channel account that sent a link code to the account that
|
||||
// issued the code, and tells the sender how it went. A code that doesn't work
|
||||
// is not retried.
|
||||
@@ -631,18 +681,8 @@ func (m *Module) reply(ctx context.Context, e store.Event, src store.Source, cha
|
||||
// dispatch never starts a second run.
|
||||
func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
|
||||
ctx := context.Background()
|
||||
if e.Own {
|
||||
// Archie's own message coming back starts nothing and proposes nothing.
|
||||
return false, nil
|
||||
}
|
||||
switch e.DeclaredEventType {
|
||||
case answerType:
|
||||
return false, m.answer(ctx, e)
|
||||
case linkType:
|
||||
if err := m.link(ctx, e); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, m.redactHandledLink(ctx, tx, e)
|
||||
if handled, err := m.dispatchBuiltin(ctx, tx, e); handled || err != nil {
|
||||
return false, err
|
||||
}
|
||||
linked, err := store.Link(ctx, tx, e)
|
||||
if err != nil || linked {
|
||||
@@ -671,6 +711,29 @@ func (m *Module) dispatch(tx *sqlx.Tx, e store.Event) (bool, error) {
|
||||
return matched, nil
|
||||
}
|
||||
|
||||
func (m *Module) dispatchBuiltin(ctx context.Context, tx *sqlx.Tx, e store.Event) (bool, error) {
|
||||
switch e.DeclaredEventType {
|
||||
case changeApprovedType:
|
||||
return true, m.settleChange(ctx, e, true)
|
||||
case changeRejectedType:
|
||||
return true, m.settleChange(ctx, e, false)
|
||||
}
|
||||
if e.Own {
|
||||
// Archie's own message coming back starts nothing and proposes nothing.
|
||||
return true, nil
|
||||
}
|
||||
switch e.DeclaredEventType {
|
||||
case answerType:
|
||||
return true, m.answer(ctx, e)
|
||||
case linkType:
|
||||
if err := m.link(ctx, e); err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, m.redactHandledLink(ctx, tx, e)
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// outcome is the result of evaluating a trigger against an event: notMatched
|
||||
// (its filter didn't match), noRun (it matched but started no run, and the
|
||||
// dispatch records why) or fired (a run started).
|
||||
|
||||
@@ -736,6 +736,10 @@ func (m *Module) finishOIDC(ctx context.Context, in *oidcCallbackInput) (*redire
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
m.log.InfoContext(ctx, "account signed in through the identity provider", "identity", value.ID)
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "auth", Action: "auth.oidc.login", ActorID: string(value.ID), ActorKind: "user",
|
||||
ResourceKind: "identity", ResourceID: string(value.ID), Outcome: "success",
|
||||
})
|
||||
return &redirectReply{
|
||||
Location: "/",
|
||||
SetCookie: []http.Cookie{
|
||||
@@ -810,6 +814,10 @@ func (m *Module) backchannelLogout(ctx context.Context, in *backchannelLogoutInp
|
||||
if err := m.RevokeSessionsBySubject(ctx, sub.Issuer, sub.Subject); err != nil {
|
||||
return nil, m.accountError(ctx, err)
|
||||
}
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "auth", Action: "auth.oidc.backchannel_logout", ActorID: sub.Issuer + ":" + sub.Subject, ActorKind: "oidc",
|
||||
ResourceKind: "session", ResourceID: sub.Issuer + ":" + sub.Subject, Outcome: "success",
|
||||
})
|
||||
return &backchannelLogoutReply{CacheControl: "no-store"}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -283,6 +283,18 @@ type WorkflowAliases interface {
|
||||
WorkflowsUsingModel(ctx context.Context, orgID, alias string) ([]string, error)
|
||||
}
|
||||
|
||||
// AuditRecord describes a security or policy audit event emitted by governance.
|
||||
type AuditRecord struct {
|
||||
Category string
|
||||
Action string
|
||||
ActorID string
|
||||
ActorKind string
|
||||
ResourceKind string
|
||||
ResourceID string
|
||||
Outcome string
|
||||
Detail any
|
||||
}
|
||||
|
||||
// Module serves one organisation's settings.
|
||||
type Module struct {
|
||||
orgID string
|
||||
@@ -294,6 +306,7 @@ type Module struct {
|
||||
oidc *oidcLogin
|
||||
setup *SetupSignal
|
||||
channels ChannelLinks
|
||||
audit func(context.Context, AuditRecord)
|
||||
// workflows reports the saved workflows that name a model alias.
|
||||
workflows WorkflowAliases
|
||||
|
||||
@@ -320,6 +333,15 @@ func (m *Module) UseSealer(s *seal.Sealer) { m.sealer = s }
|
||||
// writes are checked against.
|
||||
func (m *Module) UseAuthorizer(a Authorizer) { m.authorizer.Store(&a) }
|
||||
|
||||
// UseAudit registers a callback that receives security and policy audit events.
|
||||
func (m *Module) UseAudit(fn func(context.Context, AuditRecord)) { m.audit = fn }
|
||||
|
||||
func (m *Module) recordAudit(ctx context.Context, r AuditRecord) {
|
||||
if m != nil && m.audit != nil {
|
||||
m.audit(ctx, r)
|
||||
}
|
||||
}
|
||||
|
||||
// authz returns the policy chain, or nil before UseAuthorizer.
|
||||
func (m *Module) authz() Authorizer {
|
||||
if a := m.authorizer.Load(); a != nil {
|
||||
|
||||
@@ -97,7 +97,16 @@ func (m *Module) PutPolicy(ctx context.Context, p Policy) (int64, error) {
|
||||
}); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return m.store.PutAccessPolicy(ctx, policyToRow(p))
|
||||
ver, err := m.store.PutAccessPolicy(ctx, policyToRow(p))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "policy", Action: "policy.access.update", ActorID: CallerID(ctx),
|
||||
ResourceKind: "access_policy", ResourceID: p.ID, Outcome: "success",
|
||||
Detail: map[string]any{"level": p.Level, "version": ver},
|
||||
})
|
||||
return ver, nil
|
||||
}
|
||||
|
||||
// DeletePolicy removes one stored policy after verifying no org is locked out.
|
||||
@@ -121,6 +130,11 @@ func (m *Module) DeletePolicy(ctx context.Context, p Policy) error {
|
||||
if !found {
|
||||
return ErrPolicyNotFound
|
||||
}
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "policy", Action: "policy.access.delete", ActorID: CallerID(ctx),
|
||||
ResourceKind: "access_policy", ResourceID: p.ID, Outcome: "success",
|
||||
Detail: map[string]any{"level": p.Level},
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -445,7 +445,7 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc
|
||||
now := time.Now().UTC()
|
||||
token := rand.Text()
|
||||
expires := sessionExpiry(now, settings.SessionMaxLifetimeS)
|
||||
var breakGlassID string
|
||||
var breakGlassID, refusedID string
|
||||
row, err := m.store.SignInAccount(ctx, email, sessionHash(token), expires, func(hash string) bool {
|
||||
if hash == "" {
|
||||
_, _ = HashPassword("unknown account dummy password")
|
||||
@@ -455,6 +455,7 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc
|
||||
}, func(identityID string, isOrgOwner bool) error {
|
||||
breakGlass, err := allowPasswordSignIn(settings.SSOOnly, isOrgOwner)
|
||||
if err != nil {
|
||||
refusedID = identityID
|
||||
m.log.WarnContext(ctx, "password sign-in refused: sso_only enabled", "audit", true, "identity", identityID)
|
||||
return err
|
||||
}
|
||||
@@ -464,10 +465,26 @@ func (m *Module) SignInAccount(ctx context.Context, email, password string) (Acc
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
if refusedID != "" {
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "auth", Action: "auth.password.login", ActorID: refusedID, ActorKind: "user",
|
||||
ResourceKind: "identity", ResourceID: refusedID, Outcome: "denied",
|
||||
Detail: map[string]any{"reason": "sso_only"},
|
||||
})
|
||||
}
|
||||
return AccountSession{}, mapIdentityErr(err)
|
||||
}
|
||||
if breakGlassID != "" {
|
||||
m.log.WarnContext(ctx, "break-glass local password sign-in used while sso_only is enabled", "audit", true, "identity", breakGlassID)
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "auth", Action: "auth.break_glass.login", ActorID: breakGlassID, ActorKind: "user",
|
||||
ResourceKind: "identity", ResourceID: breakGlassID, Outcome: "success",
|
||||
})
|
||||
} else {
|
||||
m.recordAudit(ctx, AuditRecord{
|
||||
Category: "auth", Action: "auth.password.login", ActorID: row.ID, ActorKind: "user",
|
||||
ResourceKind: "identity", ResourceID: row.ID, Outcome: "success",
|
||||
})
|
||||
}
|
||||
return AccountSession{Identity: identityFromRow(row), Token: token, Expires: expires}, nil
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package judgement
|
||||
|
||||
import (
|
||||
"cmp"
|
||||
"context"
|
||||
_ "embed" // the starter policy sets
|
||||
"encoding/json/jsontext"
|
||||
@@ -22,6 +23,7 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/connectors"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
"github.com/samcharles93/archie-core/modules/judgement/internal/store"
|
||||
@@ -61,6 +63,7 @@ type policyStore interface {
|
||||
type Policies struct {
|
||||
orgID string
|
||||
store policyStore
|
||||
audit audit.Recorder
|
||||
log *slog.Logger
|
||||
now func() time.Time
|
||||
}
|
||||
@@ -70,6 +73,9 @@ func NewPolicies(db *sqlx.DB, log *slog.Logger, orgID string) *Policies {
|
||||
return &Policies{orgID: orgID, store: store.New(db), log: log, now: time.Now}
|
||||
}
|
||||
|
||||
// UseAudit configures the audit recorder notified on policy updates.
|
||||
func (p *Policies) UseAudit(r audit.Recorder) { p.audit = r }
|
||||
|
||||
var starters = map[string]string{KindHardRules: starterHardRules, KindChangeRequest: starterChangeRequest}
|
||||
|
||||
// current returns the version of a kind in force, seeding the starter set the
|
||||
@@ -374,9 +380,19 @@ func (p *Policies) Put(ctx context.Context, kind, body, by string) (PolicySetVie
|
||||
if _, err := p.current(ctx, kind); err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
if _, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: body, CreatedBy: by}); err != nil {
|
||||
saved, err := p.store.AddPolicy(ctx, store.PolicySet{ID: uuid.New(), OrgID: p.orgID, Kind: kind, Body: body, CreatedBy: by})
|
||||
if err != nil {
|
||||
return PolicySetView{}, err
|
||||
}
|
||||
audit.Emit(ctx, p.audit, p.log, audit.Event{
|
||||
Category: "policy",
|
||||
Action: "policy.judgement.update",
|
||||
ActorID: cmp.Or(by, string(governance.SystemID)),
|
||||
ResourceKind: "judgement_policy",
|
||||
ResourceID: kind,
|
||||
Outcome: "success",
|
||||
Detail: map[string]any{"version": saved.Version},
|
||||
})
|
||||
return p.View(ctx, kind, 0)
|
||||
}
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpapi"
|
||||
"github.com/samcharles93/archie-core/internal/platform/httpjson"
|
||||
"github.com/samcharles93/archie-core/modules/audit"
|
||||
"github.com/samcharles93/archie-core/modules/governance"
|
||||
)
|
||||
|
||||
@@ -36,6 +37,7 @@ type Module struct {
|
||||
bootstrap Bootstrap
|
||||
rotate func(hash string) error
|
||||
sources Sources
|
||||
audit audit.Recorder
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
@@ -45,6 +47,9 @@ func New(b Bootstrap, rotate func(hash string) error, log *slog.Logger) *Module
|
||||
return &Module{bootstrap: b, rotate: rotate, log: log}
|
||||
}
|
||||
|
||||
// UseAudit configures the audit recorder notified on administrative actions.
|
||||
func (m *Module) UseAudit(r audit.Recorder) { m.audit = r }
|
||||
|
||||
// Register adds the system API.
|
||||
func (m *Module) Register(api huma.API) {
|
||||
tags := []string{"System"}
|
||||
@@ -88,6 +93,14 @@ func (m *Module) rotateAdminToken(ctx context.Context, _ *struct{}) (*httpapi.Re
|
||||
m.bootstrap.AdminPrefix, m.bootstrap.AdminSet = hash[:8], true
|
||||
m.mu.Unlock()
|
||||
m.log.InfoContext(ctx, "admin token rotated", "audit", true, "action", "admin.token.rotate")
|
||||
audit.Emit(ctx, m.audit, m.log, audit.Event{
|
||||
Category: "auth",
|
||||
Action: "admin.token.rotate",
|
||||
ActorID: governance.CallerID(ctx),
|
||||
ResourceKind: "instance",
|
||||
ResourceID: "admin_token",
|
||||
Outcome: "success",
|
||||
})
|
||||
return httpapi.OK(adminToken{Token: token}), nil
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user