package chat import ( "bytes" "crypto/sha256" "encoding/hex" "encoding/json/jsontext" json "encoding/json/v2" "errors" "fmt" "slices" "time" "github.com/google/uuid" "github.com/samcharles93/archie-core/modules/approvals" "github.com/samcharles93/archie-core/modules/chat/internal/store" "github.com/samcharles93/archie-core/modules/connectors" "github.com/samcharles93/archie-core/modules/governance" "github.com/samcharles93/archie-core/modules/judgement" ) // bindingDomain separates a binding digest from every other SHA-256 the // binary computes, so a digest can't be replayed as another kind of record. const bindingDomain = "archie.chat.binding.v1\x00" // Binding is the immutable record a held chat action's approval is bound to. // The approver's answer covers this whole record, not only the action name and // input, so an approval can't be moved to another organisation, conversation, // turn, target or approver set, or run after any of them changed. // // Level is not part of it: a stricter level than the one held at is refused // when the action is judged again, and a lower one is not a risk. type Binding struct { // ID is the held action's single-use id. ID uuid.UUID `json:"id"` Org string `json:"org"` Session uuid.UUID `json:"session"` Turn uuid.UUID `json:"turn"` // Owner is the person whose conversation the action belongs to. Owner string `json:"owner"` // Request is the approval request put to the approvers. Request uuid.UUID `json:"request"` Connector string `json:"connector"` Action string `json:"action"` // Input is the action's arguments in connectors.Canonical form. Input jsontext.Value `json:"input"` Target connectors.Target `json:"target"` Effect connectors.Effect `json:"effect"` // Approvers are the people the request is put to, in escalation order. It // is empty, not nil, when only people with authority may answer. Approvers []string `json:"approvers"` Expires time.Time `json:"expires"` } var errUnbound = errors.New("the action's binding is incomplete") // Digest returns the hex SHA-256 of the binding's canonical JSON (RFC 8785) // under a domain prefix. It refuses a binding with a missing field: an // approval that doesn't name everything it covers covers nothing. func (b Binding) Digest() (string, error) { if err := b.complete(); err != nil { return "", err } raw, err := json.Marshal(b) if err != nil { return "", fmt.Errorf("encode binding: %w", err) } value := jsontext.Value(raw) if err := value.Canonicalize(jsontext.CanonicalizeRawInts(false)); err != nil { return "", fmt.Errorf("canonicalise binding: %w", err) } sum := sha256.Sum256(append([]byte(bindingDomain), value...)) return hex.EncodeToString(sum[:]), nil } func (b Binding) complete() error { missing := "" switch { case b.ID == uuid.Nil: missing = "id" case b.Org == "": missing = "organisation" case b.Session == uuid.Nil: missing = "conversation" case b.Turn == uuid.Nil: missing = "turn" case b.Owner == "": missing = "owner" case b.Request == uuid.Nil: missing = "approval request" case b.Connector == "" || b.Action == "": missing = "action" case len(bytes.TrimSpace(b.Input)) == 0: missing = "arguments" case b.Approvers == nil: missing = "approvers" case b.Expires.IsZero(): missing = "expiry" } if missing != "" { return fmt.Errorf("%w: no %s", errUnbound, missing) } return nil } // bindingFor describes a decision held for a turn. func bindingFor(orgID string, id, request uuid.UUID, t store.Turn, d judgement.Decision, approvers []string, expires time.Time) Binding { return Binding{ ID: id, Org: orgID, Session: t.SessionID, Turn: t.ID, Owner: t.Owner, Request: request, Connector: d.Action.Connector, Action: d.Action.Name, Input: connectors.Canonical(d.Action.Input), Target: d.Action.Target, Effect: d.Action.Effect, Approvers: approvers, Expires: expires.UTC(), } } // approverIDs are the people an escalation path asks, in order. func approverIDs(path []governance.PathStep) []string { out := make([]string, 0, len(path)) for _, st := range path { if st.Account != "" { out = append(out, st.Account) } } return out } // stale says why a held action's approval no longer covers what would run, or // returns nothing when it still does. The action carries the binding recorded // when it was held and its digest; fresh is the decision judged again now and // approvers the people the request would be put to now. Anything that can't // be checked counts as stale. func stale(a store.Action, answer approvals.Answer, held, fresh judgement.Decision, approvers []string, now time.Time) string { stored, why := recorded(a) if why != "" { return why } switch { case stored.ID != a.ID || stored.Turn != a.TurnID || stored.Owner != a.Owner || stored.Request != a.RequestID: return "its binding belongs to another action" case !answer.Approved || answer.RequestID != a.RequestID: return "the answer was given for another request" case !now.Before(stored.Expires): return "it expired before it ran" case stored.Connector != held.Action.Connector || stored.Action != held.Action.Name || !bytes.Equal(stored.Input, connectors.Canonical(held.Action.Input)): return "the held action differs from the one approved" } return changed(stored, fresh, approvers) } // recorded reads the binding stored with an action and checks it against its // digest. func recorded(a store.Action) (Binding, string) { var stored Binding if len(a.Binding) == 0 || a.BindingDigest == "" || json.Unmarshal(a.Binding, &stored) != nil { return Binding{}, "it carries no binding to check the approval against" } if sum, err := stored.Digest(); err != nil || sum != a.BindingDigest { return Binding{}, "its binding is incomplete or was altered" } return stored, "" } // changed names the first thing in the action as it stands now that differs // from what was approved. func changed(stored Binding, fresh judgement.Decision, approvers []string) string { switch { case stored.Connector != fresh.Action.Connector || stored.Action != fresh.Action.Name: return "its connector or action changed since it was approved" case !bytes.Equal(stored.Input, connectors.Canonical(fresh.Action.Input)): return "its arguments changed since it was approved" case stored.Target != fresh.Action.Target: return "its target changed since it was approved" case stored.Effect != fresh.Action.Effect: return "its effect changed since it was approved" case !slices.Equal(stored.Approvers, approvers): return "the people who may approve it changed since it was approved" } return "" }