Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6139699a9 | ||
|
|
6e0040fe89 |
@@ -0,0 +1,212 @@
|
||||
package notificationexecutor
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
capabilitydomain "git.cin.su/m/Assistant/modules/capability/domain"
|
||||
"git.cin.su/m/Assistant/modules/commit/ports"
|
||||
)
|
||||
|
||||
const maxResponseBytes = 16 << 10
|
||||
|
||||
var ErrInvalidNotification = errors.New("invalid prospective notification")
|
||||
|
||||
type Payload struct {
|
||||
ActionIntentID commitcontract.ActionIntentID `json:"action_intent_id"`
|
||||
TemplateCode string `json:"template_code"`
|
||||
ProspectiveItemID string `json:"prospective_item_id"`
|
||||
ExpectedRevision int64 `json:"expected_revision"`
|
||||
Title string `json:"title"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type DeliveryRequest struct {
|
||||
Payload
|
||||
RequestDigest string `json:"request_digest"`
|
||||
}
|
||||
|
||||
type Receipt struct {
|
||||
ReceiptID string `json:"receipt_id"`
|
||||
ActionIntentID commitcontract.ActionIntentID `json:"action_intent_id"`
|
||||
RequestDigest string `json:"request_digest"`
|
||||
AcceptedAt int64 `json:"accepted_at_unix_millis"`
|
||||
}
|
||||
|
||||
func Digest(payload Payload) (string, error) {
|
||||
if payload.ActionIntentID == "" || payload.TemplateCode != commitcontract.ProspectiveDeliveredTemplateV1 ||
|
||||
payload.ProspectiveItemID == "" || payload.ExpectedRevision < 1 || strings.TrimSpace(payload.Title) == "" ||
|
||||
strings.TrimSpace(payload.Message) == "" || len(payload.Title) > 160 || len(payload.Message) > 2048 {
|
||||
return "", ErrInvalidNotification
|
||||
}
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
sum := sha256.Sum256(encoded)
|
||||
return hex.EncodeToString(sum[:]), nil
|
||||
}
|
||||
|
||||
func PayloadFromAction(action commitcontract.AuthorizedAction) (Payload, error) {
|
||||
subject := action.Proposal.NotificationSubject
|
||||
if action.Proposal.CapabilityID != commitcontract.CapabilityProspectiveNotification ||
|
||||
action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification ||
|
||||
subject.BindingID == "" || subject.BindingRevision < 1 {
|
||||
return Payload{}, ErrInvalidNotification
|
||||
}
|
||||
payload := Payload{ActionIntentID: action.Proposal.IntentID, TemplateCode: subject.TemplateCode,
|
||||
ProspectiveItemID: string(subject.ProspectiveItemID), ExpectedRevision: int64(subject.ExpectedRevision),
|
||||
Title: subject.RenderedTitle, Message: subject.RenderedMessage}
|
||||
digest, err := Digest(payload)
|
||||
if err != nil || digest != subject.RequestDigest {
|
||||
return Payload{}, ErrInvalidNotification
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
type Executor struct {
|
||||
binding capability.Binding
|
||||
secret string
|
||||
client *http.Client
|
||||
executeAllowed bool
|
||||
}
|
||||
|
||||
func New(binding capability.Binding, secret string, client *http.Client) (*Executor, error) {
|
||||
if err := capabilitydomain.UsableBinding(binding); err != nil {
|
||||
return nil, ErrInvalidNotification
|
||||
}
|
||||
return newExecutor(binding, secret, client, true)
|
||||
}
|
||||
|
||||
func NewReconciler(binding capability.Binding, secret string, client *http.Client) (*Executor, error) {
|
||||
if err := capabilitydomain.ValidateBinding(binding); err != nil {
|
||||
return nil, ErrInvalidNotification
|
||||
}
|
||||
return newExecutor(binding, secret, client, false)
|
||||
}
|
||||
|
||||
func newExecutor(binding capability.Binding, secret string, client *http.Client, executeAllowed bool) (*Executor, error) {
|
||||
if strings.TrimSpace(secret) == "" || client == nil {
|
||||
return nil, ErrInvalidNotification
|
||||
}
|
||||
copyClient := *client
|
||||
copyClient.CheckRedirect = func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }
|
||||
return &Executor{binding: binding, secret: secret, client: ©Client, executeAllowed: executeAllowed}, nil
|
||||
}
|
||||
|
||||
func (e *Executor) Execute(action commitcontract.AuthorizedAction) ports.ExecutionResult {
|
||||
if !e.executeAllowed {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
payload, err := e.requestFor(action)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
body, err := json.Marshal(DeliveryRequest{Payload: payload, RequestDigest: action.Proposal.NotificationSubject.RequestDigest})
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
endpoint, err := e.endpoint(e.binding.DeliveryPath, string(action.Proposal.IntentID))
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodPut, endpoint, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+e.secret)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Accept", "application/json")
|
||||
response, err := e.client.Do(request)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusCreated {
|
||||
if response.StatusCode >= 400 && response.StatusCode < 500 && response.StatusCode != http.StatusRequestTimeout && response.StatusCode != http.StatusTooManyRequests {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
receipt, err := decodeReceipt(response.Body)
|
||||
if err != nil || !matchingReceipt(receipt, action) {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
return ports.ExecutionResult{Known: true, Succeeded: true}
|
||||
}
|
||||
|
||||
func (e *Executor) Reconcile(action commitcontract.AuthorizedAction) ports.ExecutionResult {
|
||||
if _, err := e.requestFor(action); err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
endpoint, err := e.endpoint(e.binding.ReceiptPath, string(action.Proposal.IntentID))
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
request, err := http.NewRequest(http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+e.secret)
|
||||
request.Header.Set("Accept", "application/json")
|
||||
response, err := e.client.Do(request)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
receipt, err := decodeReceipt(response.Body)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
if !matchingReceipt(receipt, action) {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
return ports.ExecutionResult{Known: true, Succeeded: true}
|
||||
}
|
||||
|
||||
func (e *Executor) requestFor(action commitcontract.AuthorizedAction) (Payload, error) {
|
||||
if action.Proposal.NotificationSubject.BindingID != e.binding.ID || action.Proposal.NotificationSubject.BindingRevision != e.binding.Revision ||
|
||||
action.PrincipalID != e.binding.OwnerPrincipalID {
|
||||
return Payload{}, ErrInvalidNotification
|
||||
}
|
||||
return PayloadFromAction(action)
|
||||
}
|
||||
|
||||
func (e *Executor) endpoint(path, intent string) (string, error) {
|
||||
base, err := url.Parse(e.binding.HTTPSOrigin)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
base.Path = path + "/" + url.PathEscape(intent)
|
||||
base.RawPath, base.RawQuery, base.Fragment = "", "", ""
|
||||
return base.String(), nil
|
||||
}
|
||||
|
||||
func decodeReceipt(reader io.Reader) (Receipt, error) {
|
||||
var receipt Receipt
|
||||
decoder := json.NewDecoder(io.LimitReader(reader, maxResponseBytes+1))
|
||||
if err := decoder.Decode(&receipt); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if receipt.ReceiptID == "" || receipt.ActionIntentID == "" || len(receipt.RequestDigest) != 64 || receipt.AcceptedAt <= 0 {
|
||||
return Receipt{}, fmt.Errorf("invalid receipt")
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func matchingReceipt(receipt Receipt, action commitcontract.AuthorizedAction) bool {
|
||||
return receipt.ActionIntentID == action.Proposal.IntentID && receipt.RequestDigest == action.Proposal.NotificationSubject.RequestDigest
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
package notificationexecutor
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
func testAction(t *testing.T) commitcontract.AuthorizedAction {
|
||||
t.Helper()
|
||||
payload := Payload{ActionIntentID: "intent-1", TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 2, Title: "Домовой", Message: "Пора вернуться к задаче"}
|
||||
digest, err := Digest(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return commitcontract.AuthorizedAction{PrincipalID: identity.PrincipalID("owner-1"), Proposal: commitcontract.ActionProposal{
|
||||
IntentID: payload.ActionIntentID, CapabilityID: commitcontract.CapabilityProspectiveNotification, Operation: commitcontract.OperationDeliverProspectiveNotification,
|
||||
NotificationSubject: commitcontract.ProspectiveNotificationSubject{ProspectiveItemID: "item-1", ExpectedRevision: 2, TemplateCode: payload.TemplateCode, BindingID: "binding-1", BindingRevision: 1, RenderedTitle: payload.Title, RenderedMessage: payload.Message, RequestDigest: digest},
|
||||
}}
|
||||
}
|
||||
|
||||
func testBinding(origin string) capability.Binding {
|
||||
return capability.Binding{ID: "binding-1", CapabilityID: commitcontract.CapabilityProspectiveNotification, OwnerPrincipalID: "owner-1", Revision: 1, State: capability.BindingActive, HTTPSOrigin: origin, DeliveryPath: "/delivery/v1/deliveries", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}
|
||||
}
|
||||
|
||||
func TestExecutorPutAndReconcileMatchReceipt(t *testing.T) {
|
||||
action := testAction(t)
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Authorization") != "Bearer secret" {
|
||||
t.Error("missing credential")
|
||||
}
|
||||
if r.Method == http.MethodPut && r.URL.Path != "/delivery/v1/deliveries/intent-1" {
|
||||
t.Errorf("bad put path %s", r.URL.Path)
|
||||
}
|
||||
if r.Method == http.MethodGet && r.URL.Path != "/delivery/v1/receipts/intent-1" {
|
||||
t.Errorf("bad get path %s", r.URL.Path)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Receipt{ReceiptID: "receipt-intent-1", ActionIntentID: "intent-1", RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
|
||||
}))
|
||||
defer server.Close()
|
||||
executor, err := New(testBinding(server.URL), "secret", server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result := executor.Execute(action); !result.Known || !result.Succeeded {
|
||||
t.Fatalf("execute: %+v", result)
|
||||
}
|
||||
if result := executor.Reconcile(action); !result.Known || !result.Succeeded {
|
||||
t.Fatalf("reconcile: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorAmbiguousAndIntegrityOutcomes(t *testing.T) {
|
||||
action := testAction(t)
|
||||
for name, handler := range map[string]http.HandlerFunc{
|
||||
"server error": func(w http.ResponseWriter, _ *http.Request) { http.Error(w, "no", http.StatusBadGateway) },
|
||||
"bad receipt": func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(Receipt{ReceiptID: "r", ActionIntentID: "other", RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
server := httptest.NewTLSServer(handler)
|
||||
defer server.Close()
|
||||
executor, err := New(testBinding(server.URL), "secret", server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result := executor.Execute(action); result.Known {
|
||||
t.Fatalf("must be unknown: %+v", result)
|
||||
}
|
||||
})
|
||||
}
|
||||
action.Proposal.NotificationSubject.RequestDigest = "bad"
|
||||
server := httptest.NewTLSServer(http.NotFoundHandler())
|
||||
defer server.Close()
|
||||
executor, err := New(testBinding(server.URL), "secret", server.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result := executor.Execute(action); !result.Known || result.Succeeded {
|
||||
t.Fatalf("invalid evidence must fail closed: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExecutorDoesNotFollowRedirect(t *testing.T) {
|
||||
action := testAction(t)
|
||||
targetCalls := 0
|
||||
target := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { targetCalls++ }))
|
||||
defer target.Close()
|
||||
redirect := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, target.URL, http.StatusTemporaryRedirect)
|
||||
}))
|
||||
defer redirect.Close()
|
||||
executor, err := New(testBinding(redirect.URL), "secret", redirect.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if result := executor.Execute(action); result.Known {
|
||||
t.Fatalf("redirect must be ambiguous: %+v", result)
|
||||
}
|
||||
if targetCalls != 0 {
|
||||
t.Fatal("redirect target was called")
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,13 @@ import (
|
||||
"fmt"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
var ErrCapabilityHealthNotFound = errors.New("capability health not found")
|
||||
var ErrCapabilityBindingNotFound = errors.New("capability binding not found")
|
||||
var ErrCapabilityBindingConflict = errors.New("capability binding conflict")
|
||||
|
||||
type CapabilityRepository struct{ pool *pgxpool.Pool }
|
||||
|
||||
@@ -56,3 +59,72 @@ func (r *CapabilityRepository) RebuildHealthProjection(ctx context.Context) (int
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
func (r *CapabilityRepository) SaveBinding(ctx context.Context, binding capability.Binding) error {
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
result, err := tx.Exec(ctx, `INSERT INTO capability.notification_bindings (
|
||||
binding_id,capability_id,owner_principal_id,revision,state,https_origin,delivery_path,receipt_path,
|
||||
protocol,secret_ref,verified_at_unix_millis,health)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT DO NOTHING`,
|
||||
binding.ID, binding.CapabilityID, binding.OwnerPrincipalID, binding.Revision, binding.State,
|
||||
binding.HTTPSOrigin, binding.DeliveryPath, binding.ReceiptPath, binding.Protocol, binding.SecretRef,
|
||||
binding.VerifiedAtUnixMillis, binding.Health)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if result.RowsAffected() == 0 {
|
||||
existing, loadErr := r.LoadBinding(ctx, binding.ID, binding.Revision)
|
||||
if loadErr != nil || existing != binding {
|
||||
return ErrCapabilityBindingConflict
|
||||
}
|
||||
}
|
||||
if binding.State == capability.BindingActive {
|
||||
result, err = tx.Exec(ctx, `INSERT INTO capability.notification_binding_heads (capability_id,owner_principal_id,binding_id,revision)
|
||||
VALUES ($1,$2,$3,$4) ON CONFLICT (capability_id,owner_principal_id) DO UPDATE SET binding_id=EXCLUDED.binding_id,revision=EXCLUDED.revision
|
||||
WHERE capability.notification_binding_heads.revision < EXCLUDED.revision`, binding.CapabilityID, binding.OwnerPrincipalID, binding.ID, binding.Revision)
|
||||
if err != nil || result.RowsAffected() != 1 {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return ErrCapabilityBindingConflict
|
||||
}
|
||||
} else {
|
||||
_, err = tx.Exec(ctx, `DELETE FROM capability.notification_binding_heads WHERE capability_id=$1 AND owner_principal_id=$2 AND binding_id=$3 AND revision < $4`, binding.CapabilityID, binding.OwnerPrincipalID, binding.ID, binding.Revision)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r *CapabilityRepository) LoadBinding(ctx context.Context, id capability.CapabilityBindingID, revision int64) (capability.Binding, error) {
|
||||
var binding capability.Binding
|
||||
err := r.pool.QueryRow(ctx, `SELECT binding_id,capability_id,owner_principal_id,revision,state,https_origin,delivery_path,receipt_path,
|
||||
protocol,secret_ref,verified_at_unix_millis,health FROM capability.notification_bindings WHERE binding_id=$1 AND revision=$2`, id, revision).
|
||||
Scan(&binding.ID, &binding.CapabilityID, &binding.OwnerPrincipalID, &binding.Revision, &binding.State,
|
||||
&binding.HTTPSOrigin, &binding.DeliveryPath, &binding.ReceiptPath, &binding.Protocol, &binding.SecretRef,
|
||||
&binding.VerifiedAtUnixMillis, &binding.Health)
|
||||
if err != nil {
|
||||
return capability.Binding{}, fmt.Errorf("load capability binding: %w", err)
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func (r *CapabilityRepository) LoadActiveBinding(ctx context.Context, capabilityID capability.CapabilityID, owner identity.PrincipalID) (capability.Binding, error) {
|
||||
var binding capability.Binding
|
||||
err := r.pool.QueryRow(ctx, `SELECT b.binding_id,b.capability_id,b.owner_principal_id,b.revision,b.state,b.https_origin,b.delivery_path,b.receipt_path,
|
||||
b.protocol,b.secret_ref,b.verified_at_unix_millis,b.health FROM capability.notification_binding_heads h
|
||||
JOIN capability.notification_bindings b ON b.binding_id=h.binding_id AND b.revision=h.revision
|
||||
WHERE h.capability_id=$1 AND h.owner_principal_id=$2 AND b.state=$3`, capabilityID, owner, capability.BindingActive).
|
||||
Scan(&binding.ID, &binding.CapabilityID, &binding.OwnerPrincipalID, &binding.Revision, &binding.State,
|
||||
&binding.HTTPSOrigin, &binding.DeliveryPath, &binding.ReceiptPath, &binding.Protocol, &binding.SecretRef,
|
||||
&binding.VerifiedAtUnixMillis, &binding.Health)
|
||||
if err != nil {
|
||||
return capability.Binding{}, fmt.Errorf("load active capability binding: %w", err)
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"reflect"
|
||||
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -30,6 +31,12 @@ func OpenCommit(ctx context.Context, c ContinuityConfig) (*CommitRepository, err
|
||||
}
|
||||
func (r *CommitRepository) Close() { r.pool.Close() }
|
||||
func (r *CommitRepository) SaveAuthorized(ctx context.Context, a commitcontract.AuthorizedAction) error {
|
||||
prospectiveItemID := a.Proposal.ContinuitySubject.ProspectiveItemID
|
||||
expectedRevision := a.Proposal.ContinuitySubject.ExpectedRevision
|
||||
if a.Proposal.Operation == commitcontract.OperationDeliverProspectiveNotification {
|
||||
prospectiveItemID = a.Proposal.NotificationSubject.ProspectiveItemID
|
||||
expectedRevision = a.Proposal.NotificationSubject.ExpectedRevision
|
||||
}
|
||||
tx, err := r.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -42,15 +49,19 @@ func (r *CommitRepository) SaveAuthorized(ctx context.Context, a commitcontract.
|
||||
authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
|
||||
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
|
||||
proposal_state,action_state,authorized_at_unix_millis,envelope_revision)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,1)
|
||||
proposal_state,action_state,authorized_at_unix_millis,envelope_revision,notification_template_code,
|
||||
capability_binding_id,capability_binding_revision,notification_title,notification_message,request_digest)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,$14,$15,$16,$17,$18,$19,$20,$21,1,$22,$23,$24,$25,$26,$27)
|
||||
ON CONFLICT DO NOTHING`,
|
||||
a.ID, a.Proposal.IntentID, a.Proposal.ActorID, a.PrincipalID, a.GrantID, a.GrantRevision, a.ScopeID,
|
||||
a.Proposal.Target.TaskID, a.Proposal.Target.GoalID, a.Proposal.Target.ScopeID, a.Proposal.Target.Revision,
|
||||
a.Proposal.CapabilityID, a.Proposal.Operation, a.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
a.Proposal.ContinuitySubject.ExpectedRevision, a.Proposal.ContinuitySubject.FromState,
|
||||
a.Proposal.CapabilityID, a.Proposal.Operation, prospectiveItemID,
|
||||
expectedRevision, a.Proposal.ContinuitySubject.FromState,
|
||||
a.Proposal.ContinuitySubject.ToState, a.Proposal.ContinuitySubject.EvidenceRef,
|
||||
a.Proposal.State, a.State, a.AuthorizedAtUnixMillis)
|
||||
a.Proposal.State, a.State, a.AuthorizedAtUnixMillis, a.Proposal.NotificationSubject.TemplateCode,
|
||||
a.Proposal.NotificationSubject.BindingID, a.Proposal.NotificationSubject.BindingRevision,
|
||||
a.Proposal.NotificationSubject.RenderedTitle, a.Proposal.NotificationSubject.RenderedMessage,
|
||||
a.Proposal.NotificationSubject.RequestDigest)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -128,7 +139,8 @@ func (r *CommitRepository) ListAuthorizedByOwner(ctx context.Context, actorID id
|
||||
rows, err := r.pool.Query(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
|
||||
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
|
||||
proposal_state,action_state,authorized_at_unix_millis
|
||||
proposal_state,action_state,authorized_at_unix_millis,notification_template_code,capability_binding_id,
|
||||
capability_binding_revision,notification_title,notification_message,request_digest
|
||||
FROM commit.authorized_action_envelopes
|
||||
WHERE actor_id=$1 AND principal_id=$2
|
||||
ORDER BY authorized_at_unix_millis DESC, authorized_action_id DESC LIMIT $3`, actorID, principalID, limit)
|
||||
@@ -163,7 +175,8 @@ func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcont
|
||||
err := scanAuthorized(querier.QueryRow(ctx, `SELECT authorized_action_id,action_intent_id,actor_id,principal_id,grant_id,grant_revision,scope_id,
|
||||
task_id,goal_id,task_scope_id,task_revision,capability_id,operation,prospective_item_id,
|
||||
expected_prospective_revision,prospective_from_state,prospective_to_state,evidence_ref,
|
||||
proposal_state,action_state,authorized_at_unix_millis
|
||||
proposal_state,action_state,authorized_at_unix_millis,notification_template_code,capability_binding_id,
|
||||
capability_binding_revision,notification_title,notification_message,request_digest
|
||||
FROM commit.authorized_action_envelopes WHERE authorized_action_id=$1`, id), &action)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return commitcontract.AuthorizedAction{}, ErrAuthorizedActionNotFound
|
||||
@@ -175,12 +188,21 @@ func loadAuthorized(ctx context.Context, querier commitRowQuerier, id commitcont
|
||||
}
|
||||
|
||||
func scanAuthorized(row commitRowScanner, action *commitcontract.AuthorizedAction) error {
|
||||
return row.Scan(
|
||||
err := row.Scan(
|
||||
&action.ID, &action.Proposal.IntentID, &action.Proposal.ActorID, &action.PrincipalID,
|
||||
&action.GrantID, &action.GrantRevision, &action.ScopeID, &action.Proposal.Target.TaskID,
|
||||
&action.Proposal.Target.GoalID, &action.Proposal.Target.ScopeID, &action.Proposal.Target.Revision,
|
||||
&action.Proposal.CapabilityID, &action.Proposal.Operation, &action.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
&action.Proposal.ContinuitySubject.ExpectedRevision, &action.Proposal.ContinuitySubject.FromState,
|
||||
&action.Proposal.ContinuitySubject.ToState, &action.Proposal.ContinuitySubject.EvidenceRef,
|
||||
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis)
|
||||
&action.Proposal.State, &action.State, &action.AuthorizedAtUnixMillis,
|
||||
&action.Proposal.NotificationSubject.TemplateCode, &action.Proposal.NotificationSubject.BindingID,
|
||||
&action.Proposal.NotificationSubject.BindingRevision, &action.Proposal.NotificationSubject.RenderedTitle,
|
||||
&action.Proposal.NotificationSubject.RenderedMessage, &action.Proposal.NotificationSubject.RequestDigest)
|
||||
if err == nil && action.Proposal.Operation == commitcontract.OperationDeliverProspectiveNotification {
|
||||
action.Proposal.NotificationSubject.ProspectiveItemID = action.Proposal.ContinuitySubject.ProspectiveItemID
|
||||
action.Proposal.NotificationSubject.ExpectedRevision = action.Proposal.ContinuitySubject.ExpectedRevision
|
||||
action.Proposal.ContinuitySubject = continuity.SatisfyDeliveredSubject{}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -8,8 +8,10 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
@@ -95,10 +97,38 @@ func (c creatorCoreClient) Binding(ctx context.Context, actor identity.ActorID,
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) ActiveCapabilityBinding(ctx context.Context, capabilityID capability.CapabilityID, owner identity.PrincipalID) (capability.Binding, error) {
|
||||
var binding capability.Binding
|
||||
target := *c.baseURL
|
||||
target.Path = "/v1/capability-bindings/active"
|
||||
query := target.Query()
|
||||
query.Set("capability_id", string(capabilityID))
|
||||
query.Set("owner_principal_id", string(owner))
|
||||
target.RawQuery = query.Encode()
|
||||
status, err := c.getURL(ctx, target, "", &binding)
|
||||
if err != nil || status != http.StatusOK {
|
||||
return capability.Binding{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) CapabilityBinding(ctx context.Context, id capability.CapabilityBindingID, revision int64) (capability.Binding, error) {
|
||||
var binding capability.Binding
|
||||
status, err := c.get(ctx, "/v1/capability-bindings/"+url.PathEscape(string(id))+"/revisions/"+strconv.FormatInt(revision, 10), "", &binding)
|
||||
if err != nil || status != http.StatusOK {
|
||||
return capability.Binding{}, errCreatorQueryUnavailable
|
||||
}
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) get(ctx context.Context, path, authorization string, destination any) (int, error) {
|
||||
target := *c.baseURL
|
||||
target.Path = path
|
||||
target.RawQuery = ""
|
||||
return c.getURL(ctx, target, authorization, destination)
|
||||
}
|
||||
|
||||
func (c creatorCoreClient) getURL(ctx context.Context, target url.URL, authorization string, destination any) (int, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, target.String(), nil)
|
||||
if err != nil {
|
||||
return 0, errCreatorQueryUnavailable
|
||||
|
||||
@@ -4,12 +4,16 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
@@ -25,6 +29,7 @@ type creatorSessionSource interface {
|
||||
Session(context.Context, string) (identity.CreatorSession, error)
|
||||
Task(context.Context, work.TaskID) (work.TaskTarget, error)
|
||||
Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error)
|
||||
ActiveCapabilityBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error)
|
||||
}
|
||||
|
||||
type creatorContinuitySource interface {
|
||||
@@ -60,6 +65,13 @@ type creatorSatisfyRequest struct {
|
||||
EvidenceRef string
|
||||
}
|
||||
|
||||
type creatorNotifyRequest struct {
|
||||
Target work.TaskTarget
|
||||
ProspectiveItemID continuity.ProspectiveItemID
|
||||
ExpectedRevision continuity.ProspectiveRevision
|
||||
Confirm bool
|
||||
}
|
||||
|
||||
type creatorActionResponse struct {
|
||||
AuthorizedActionID commitcontract.AuthorizedActionID
|
||||
ActionIntentID commitcontract.ActionIntentID
|
||||
@@ -83,6 +95,7 @@ type creatorActionHistoryResponse struct {
|
||||
|
||||
func registerCreatorCommandRoutes(mux *http.ServeMux, handler creatorCommandHandler) {
|
||||
mux.HandleFunc("POST /v1/creator/continuity/satisfy-delivered", handler.satisfyDelivered)
|
||||
mux.HandleFunc("POST /v1/creator/continuity/notify-delivered", handler.notifyDelivered)
|
||||
mux.HandleFunc("POST /v1/creator/authorized-actions/{id}/reconcile", handler.reconcile)
|
||||
mux.HandleFunc("GET /v1/creator/authorized-actions", handler.listAuthorizedActions)
|
||||
}
|
||||
@@ -113,9 +126,13 @@ func (h creatorCommandHandler) listAuthorizedActions(w http.ResponseWriter, r *h
|
||||
http.Error(w, "Commit history unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
prospectiveItemID := action.Proposal.ContinuitySubject.ProspectiveItemID
|
||||
if action.Proposal.Operation == commitcontract.OperationDeliverProspectiveNotification {
|
||||
prospectiveItemID = action.Proposal.NotificationSubject.ProspectiveItemID
|
||||
}
|
||||
item := creatorActionHistoryItem{
|
||||
AuthorizedActionID: action.ID, ActionIntentID: action.Proposal.IntentID,
|
||||
Operation: action.Proposal.Operation, ProspectiveItemID: action.Proposal.ContinuitySubject.ProspectiveItemID,
|
||||
Operation: action.Proposal.Operation, ProspectiveItemID: prospectiveItemID,
|
||||
State: action.State, AuthorizedAtUnixMillis: action.AuthorizedAtUnixMillis,
|
||||
}
|
||||
if found {
|
||||
@@ -129,6 +146,104 @@ func (h creatorCommandHandler) listAuthorizedActions(w http.ResponseWriter, r *h
|
||||
_ = json.NewEncoder(w).Encode(creatorActionHistoryResponse{Items: items})
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) notifyDelivered(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
session, ok := h.creatorSession(w, r, authorization)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var request creatorNotifyRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 16<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil || ensureCreatorEOF(decoder) != nil || !request.Confirm || request.Target.TaskID == "" || request.Target.GoalID == "" || request.Target.ScopeID == "" || request.Target.Revision == 0 || request.ProspectiveItemID == "" || request.ExpectedRevision == 0 {
|
||||
http.Error(w, "invalid Creator notification request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
item, err := h.continuity.Item(r.Context(), authorization, request.ProspectiveItemID)
|
||||
if errors.Is(err, errCreatorOwnerDenied) {
|
||||
http.Error(w, "prospective item denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if errors.Is(err, errCreatorSubjectMissing) {
|
||||
http.Error(w, "prospective item not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Continuity owner validation unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if item.OwnerPrincipalID != session.PrincipalID {
|
||||
http.Error(w, "prospective item denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if item.State != continuity.ProspectiveDelivered || item.Revision != request.ExpectedRevision || item.ScopeID != request.Target.ScopeID || item.GoalID != request.Target.GoalID {
|
||||
http.Error(w, "prospective item is stale or outside justification", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
target, err := h.core.Task(r.Context(), request.Target.TaskID)
|
||||
if err != nil || target != request.Target {
|
||||
http.Error(w, "work target is stale or unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
grant, scope, err := h.authority.LoadGrant(r.Context(), creatorGrantID)
|
||||
if err != nil {
|
||||
http.Error(w, "Creator authority unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
identityBinding, err := h.core.Binding(r.Context(), session.ActorID, session.PrincipalID)
|
||||
if err != nil {
|
||||
http.Error(w, "Creator identity binding unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
capabilityBinding, err := h.core.ActiveCapabilityBinding(r.Context(), commitcontract.CapabilityProspectiveNotification, session.PrincipalID)
|
||||
if err != nil {
|
||||
http.Error(w, "notification capability unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
intentID, authorizedID, attemptID, err := h.actionIDs()
|
||||
if err != nil {
|
||||
http.Error(w, "action identity unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
title := "Домовой: напоминание"
|
||||
message := fmt.Sprintf("Проспективная запись %s ожидает вашего внимания.", item.ID)
|
||||
payload := notificationexecutor.Payload{ActionIntentID: intentID, TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: string(item.ID), ExpectedRevision: int64(item.Revision), Title: title, Message: message}
|
||||
digest, err := notificationexecutor.Digest(payload)
|
||||
if err != nil {
|
||||
http.Error(w, "notification evidence unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
proposal := commitcontract.ActionProposal{IntentID: intentID, ActorID: session.ActorID, CapabilityID: commitcontract.CapabilityProspectiveNotification, Target: request.Target, Operation: commitcontract.OperationDeliverProspectiveNotification, NotificationSubject: commitcontract.ProspectiveNotificationSubject{ProspectiveItemID: item.ID, ExpectedRevision: item.Revision, TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, BindingID: capabilityBinding.ID, BindingRevision: capabilityBinding.Revision, RenderedTitle: title, RenderedMessage: message, RequestDigest: digest}}
|
||||
action, err := commitdomain.Authorize(proposal, commitdomain.AuthorizationContext{Binding: identityBinding, Scope: scope, Grant: grant}, authorityValidator{}, authorizedID, h.now().UnixMilli())
|
||||
if err != nil {
|
||||
http.Error(w, "Creator authorization denied", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err = h.repository.SaveAuthorized(r.Context(), action); err != nil {
|
||||
http.Error(w, "commit authorized action", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
attempt, operationErr := executeAuthorized(r.Context(), h.repository, h.executor, action, attemptID)
|
||||
if operationErr != nil && !errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
http.Error(w, "execute committed notification", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
status := http.StatusCreated
|
||||
if errors.Is(operationErr, commitdomain.ErrUnknownOutcome) {
|
||||
status = http.StatusAccepted
|
||||
}
|
||||
writeCreatorActionResponse(w, status, action, attempt)
|
||||
}
|
||||
|
||||
func ensureCreatorEOF(decoder *json.Decoder) error {
|
||||
var extra any
|
||||
err := decoder.Decode(&extra)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("trailing JSON")
|
||||
}
|
||||
|
||||
func (h creatorCommandHandler) satisfyDelivered(w http.ResponseWriter, r *http.Request) {
|
||||
authorization := r.Header.Get("Authorization")
|
||||
session, ok := h.creatorSession(w, r, authorization)
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/continuity"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
@@ -19,10 +20,12 @@ import (
|
||||
)
|
||||
|
||||
type fakeCreatorCore struct {
|
||||
session identity.CreatorSession
|
||||
target work.TaskTarget
|
||||
binding identity.PrincipalBinding
|
||||
sessionErr error
|
||||
session identity.CreatorSession
|
||||
target work.TaskTarget
|
||||
binding identity.PrincipalBinding
|
||||
capabilityBinding capability.Binding
|
||||
capabilityErr error
|
||||
sessionErr error
|
||||
}
|
||||
|
||||
func (f fakeCreatorCore) Session(context.Context, string) (identity.CreatorSession, error) {
|
||||
@@ -34,6 +37,9 @@ func (f fakeCreatorCore) Task(context.Context, work.TaskID) (work.TaskTarget, er
|
||||
func (f fakeCreatorCore) Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error) {
|
||||
return f.binding, nil
|
||||
}
|
||||
func (f fakeCreatorCore) ActiveCapabilityBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error) {
|
||||
return f.capabilityBinding, f.capabilityErr
|
||||
}
|
||||
|
||||
type fakeCreatorContinuity struct {
|
||||
item continuity.ProspectiveItem
|
||||
@@ -120,6 +126,41 @@ func TestCreatorCommandDerivesAuthorityAndActionFieldsServerSide(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorNotificationDerivesTypedEnvelopeAndLeavesContinuityState(t *testing.T) {
|
||||
handler, repository, executor := validCreatorCommandHandler()
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/continuity/notify-delivered", strings.NewReader(`{"Target":{"TaskID":"task-1","GoalID":"goal-1","ScopeID":"scope-1","Revision":3},"ProspectiveItemID":"prospective-1","ExpectedRevision":4,"Confirm":true}`))
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated || executor.calls != 1 {
|
||||
t.Fatalf("status=%d calls=%d body=%s", response.Code, executor.calls, response.Body.String())
|
||||
}
|
||||
action := repository.action
|
||||
subject := action.Proposal.NotificationSubject
|
||||
if action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification || action.Proposal.CapabilityID != commitcontract.CapabilityProspectiveNotification || subject.BindingID != "notification-binding" || subject.BindingRevision != 1 || len(subject.RequestDigest) != 64 || subject.RenderedTitle == "" || subject.RenderedMessage == "" || action.Proposal.ContinuitySubject.ProspectiveItemID != "" {
|
||||
t.Fatalf("invalid notification action: %#v", action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorNotificationRejectsMissingConfirmationAndHostileFields(t *testing.T) {
|
||||
for name, body := range map[string]string{"no confirmation": `{"Target":{"TaskID":"task-1","GoalID":"goal-1","ScopeID":"scope-1","Revision":3},"ProspectiveItemID":"prospective-1","ExpectedRevision":4}`, "hostile destination": `{"Target":{"TaskID":"task-1","GoalID":"goal-1","ScopeID":"scope-1","Revision":3},"ProspectiveItemID":"prospective-1","ExpectedRevision":4,"Confirm":true,"URL":"https://evil.invalid","Body":"arbitrary"}`} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
handler, repository, executor := validCreatorCommandHandler()
|
||||
mux := http.NewServeMux()
|
||||
registerCreatorCommandRoutes(mux, handler)
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/creator/continuity/notify-delivered", strings.NewReader(body))
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest || executor.calls != 0 || repository.action.ID != "" {
|
||||
t.Fatalf("status=%d calls=%d", response.Code, executor.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatorCommandRejectsSessionForeignOwnerStaleStateAndRevokedGrant(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -230,7 +271,7 @@ func TestCreatorActionHistoryRejectsSessionAndInvalidLimitBeforeQuery(t *testing
|
||||
func validCreatorCommandHandler() (creatorCommandHandler, *fakeExecutionRepository, *knownExecutor) {
|
||||
session := identity.CreatorSession{ActorID: "creator-actor", PrincipalID: "creator-principal", ExpiresAtUnix: 1000}
|
||||
target := work.TaskTarget{TaskID: "task-1", GoalID: "goal-1", ScopeID: "scope-1", Revision: 3}
|
||||
core := fakeCreatorCore{session: session, target: target, binding: identity.PrincipalBinding{ActorID: session.ActorID, PrincipalID: session.PrincipalID, Active: true}}
|
||||
core := fakeCreatorCore{session: session, target: target, binding: identity.PrincipalBinding{ActorID: session.ActorID, PrincipalID: session.PrincipalID, Active: true}, capabilityBinding: capability.Binding{ID: "notification-binding", CapabilityID: commitcontract.CapabilityProspectiveNotification, OwnerPrincipalID: session.PrincipalID, Revision: 1, State: capability.BindingActive, HTTPSOrigin: "https://assistent.cin.su", DeliveryPath: "/delivery/v1/deliveries", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "notification-write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}}
|
||||
item := continuity.ProspectiveItem{ID: "prospective-1", OwnerPrincipalID: session.PrincipalID, ScopeID: target.ScopeID, GoalID: target.GoalID, State: continuity.ProspectiveDelivered, Revision: 4}
|
||||
grant := authority.AuthorityGrant{ID: creatorGrantID, ActorID: session.ActorID, PrincipalID: session.PrincipalID, ScopeID: target.ScopeID, Class: authority.GrantClassCreator, Revision: 2, Active: true}
|
||||
repository := &fakeExecutionRepository{}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/continuityexecutor"
|
||||
@@ -59,13 +60,10 @@ func main() {
|
||||
if executorToken == "" {
|
||||
log.Fatal("COMMIT_EXECUTOR_TOKEN is required")
|
||||
}
|
||||
executor, err := continuityexecutor.New(envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"), executorToken, &http.Client{Timeout: 5 * time.Second})
|
||||
continuityExecutor, err := continuityexecutor.New(envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"), executorToken, &http.Client{Timeout: 5 * time.Second})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "commit-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
registerExecutionRoutes(mux, repository, executor, executor, executorToken)
|
||||
creatorHTTPClient := &http.Client{Timeout: 5 * time.Second}
|
||||
creatorCore, err := newCreatorCoreClient(coreURL, creatorHTTPClient)
|
||||
if err != nil {
|
||||
@@ -75,9 +73,21 @@ func main() {
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
notificationSecret, err := readCommitSecretFile("NOTIFICATION_WRITE_TOKEN_FILE")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
notificationSecretRef := os.Getenv("NOTIFICATION_WRITE_SECRET_REF")
|
||||
if notificationSecretRef == "" {
|
||||
log.Fatal("NOTIFICATION_WRITE_SECRET_REF is required")
|
||||
}
|
||||
dispatcher := operationDispatcher{continuityExecutor: continuityExecutor, continuityReconciler: continuityExecutor, bindings: creatorCore, secretRef: notificationSecretRef, secret: notificationSecret, client: creatorHTTPClient}
|
||||
mux := http.NewServeMux()
|
||||
mux.Handle("/healthz", health.Handler{Runtime: "commit-runtime", SemanticGeneration: 1, ArchitectureGeneration: 1})
|
||||
registerExecutionRoutes(mux, repository, dispatcher, dispatcher, executorToken)
|
||||
registerCreatorCommandRoutes(mux, creatorCommandHandler{
|
||||
core: creatorCore, continuity: creatorContinuity, authority: authorityRepository, repository: repository,
|
||||
executor: executor, reconciler: executor, newID: ids.New, now: time.Now,
|
||||
executor: dispatcher, reconciler: dispatcher, newID: ids.New, now: time.Now,
|
||||
})
|
||||
mux.HandleFunc("POST /v1/authorized-actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
var request authorizationRequest
|
||||
@@ -138,6 +148,22 @@ func main() {
|
||||
}
|
||||
}
|
||||
|
||||
func readCommitSecretFile(name string) (string, error) {
|
||||
path := os.Getenv(name)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
value, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", name, err)
|
||||
}
|
||||
secret := strings.TrimSpace(string(value))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", name)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
|
||||
func envOr(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/modules/commit/ports"
|
||||
)
|
||||
|
||||
type notificationBindingSource interface {
|
||||
ActiveCapabilityBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error)
|
||||
CapabilityBinding(context.Context, capability.CapabilityBindingID, int64) (capability.Binding, error)
|
||||
}
|
||||
|
||||
type operationDispatcher struct {
|
||||
continuityExecutor ports.Executor
|
||||
continuityReconciler ports.Reconciler
|
||||
bindings notificationBindingSource
|
||||
secretRef string
|
||||
secret string
|
||||
client *http.Client
|
||||
}
|
||||
|
||||
func (d operationDispatcher) Execute(action commitcontract.AuthorizedAction) ports.ExecutionResult {
|
||||
if action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification {
|
||||
return d.continuityExecutor.Execute(action)
|
||||
}
|
||||
subject := action.Proposal.NotificationSubject
|
||||
exact, err := d.bindings.CapabilityBinding(context.Background(), subject.BindingID, subject.BindingRevision)
|
||||
if err != nil || exact.SecretRef != d.secretRef {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
active, err := d.bindings.ActiveCapabilityBinding(context.Background(), action.Proposal.CapabilityID, action.PrincipalID)
|
||||
if err != nil || active != exact {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
executor, err := notificationexecutor.New(exact, d.secret, d.client)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{Known: true}
|
||||
}
|
||||
return executor.Execute(action)
|
||||
}
|
||||
|
||||
func (d operationDispatcher) Reconcile(action commitcontract.AuthorizedAction) ports.ExecutionResult {
|
||||
if action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification {
|
||||
return d.continuityReconciler.Reconcile(action)
|
||||
}
|
||||
subject := action.Proposal.NotificationSubject
|
||||
exact, err := d.bindings.CapabilityBinding(context.Background(), subject.BindingID, subject.BindingRevision)
|
||||
if err != nil || exact.SecretRef != d.secretRef {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
reconciler, err := notificationexecutor.NewReconciler(exact, d.secret, d.client)
|
||||
if err != nil {
|
||||
return ports.ExecutionResult{}
|
||||
}
|
||||
return reconciler.Reconcile(action)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
type fakeNotificationBindings struct {
|
||||
exact capability.Binding
|
||||
active capability.Binding
|
||||
exactErr error
|
||||
activeErr error
|
||||
}
|
||||
|
||||
func (f fakeNotificationBindings) CapabilityBinding(context.Context, capability.CapabilityBindingID, int64) (capability.Binding, error) {
|
||||
return f.exact, f.exactErr
|
||||
}
|
||||
func (f fakeNotificationBindings) ActiveCapabilityBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error) {
|
||||
return f.active, f.activeErr
|
||||
}
|
||||
|
||||
func dispatcherAction(t *testing.T, binding capability.Binding) commitcontract.AuthorizedAction {
|
||||
t.Helper()
|
||||
payload := notificationexecutor.Payload{ActionIntentID: "intent-1", TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 1, Title: "Домовой", Message: "Пора вернуться"}
|
||||
digest, err := notificationexecutor.Digest(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return commitcontract.AuthorizedAction{PrincipalID: binding.OwnerPrincipalID, Proposal: commitcontract.ActionProposal{IntentID: payload.ActionIntentID, CapabilityID: commitcontract.CapabilityProspectiveNotification, Operation: commitcontract.OperationDeliverProspectiveNotification, NotificationSubject: commitcontract.ProspectiveNotificationSubject{ProspectiveItemID: "item-1", ExpectedRevision: 1, TemplateCode: payload.TemplateCode, BindingID: binding.ID, BindingRevision: binding.Revision, RenderedTitle: payload.Title, RenderedMessage: payload.Message, RequestDigest: digest}}}
|
||||
}
|
||||
|
||||
func dispatcherBinding(origin string) capability.Binding {
|
||||
return capability.Binding{ID: "binding-1", CapabilityID: commitcontract.CapabilityProspectiveNotification, OwnerPrincipalID: "owner-1", Revision: 1, State: capability.BindingActive, HTTPSOrigin: origin, DeliveryPath: "/delivery/v1/deliveries", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}
|
||||
}
|
||||
|
||||
func TestOperationDispatcherRequiresExactCurrentBinding(t *testing.T) {
|
||||
var action commitcontract.AuthorizedAction
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(notificationexecutor.Receipt{ReceiptID: "receipt-1", ActionIntentID: action.Proposal.IntentID, RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
|
||||
}))
|
||||
defer server.Close()
|
||||
binding := dispatcherBinding(server.URL)
|
||||
action = dispatcherAction(t, binding)
|
||||
fallback := &knownExecutor{}
|
||||
dispatcher := operationDispatcher{continuityExecutor: fallback, continuityReconciler: fallback, bindings: fakeNotificationBindings{exact: binding, active: binding}, secretRef: "write-v1", secret: "secret", client: server.Client()}
|
||||
if result := dispatcher.Execute(action); !result.Known || !result.Succeeded {
|
||||
t.Fatalf("execute=%+v", result)
|
||||
}
|
||||
stale := binding
|
||||
stale.Revision = 2
|
||||
dispatcher.bindings = fakeNotificationBindings{exact: binding, active: stale}
|
||||
if result := dispatcher.Execute(action); !result.Known || result.Succeeded {
|
||||
t.Fatalf("stale binding=%+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationDispatcherReconcilesRetiredHistoricalBinding(t *testing.T) {
|
||||
var action commitcontract.AuthorizedAction
|
||||
server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodGet {
|
||||
t.Fatal("reconciliation mutated receiver")
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(notificationexecutor.Receipt{ReceiptID: "receipt-1", ActionIntentID: action.Proposal.IntentID, RequestDigest: action.Proposal.NotificationSubject.RequestDigest, AcceptedAt: 1})
|
||||
}))
|
||||
defer server.Close()
|
||||
binding := dispatcherBinding(server.URL)
|
||||
action = dispatcherAction(t, binding)
|
||||
binding.State = capability.BindingRetired
|
||||
binding.Revision = 1
|
||||
fallback := &knownExecutor{}
|
||||
dispatcher := operationDispatcher{continuityExecutor: fallback, continuityReconciler: fallback, bindings: fakeNotificationBindings{exact: binding}, secretRef: "write-v1", secret: "secret", client: server.Client()}
|
||||
if result := dispatcher.Reconcile(action); !result.Known || !result.Succeeded {
|
||||
t.Fatalf("reconcile=%+v", result)
|
||||
}
|
||||
}
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
@@ -183,6 +184,43 @@ func main() {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(status)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/capability-bindings/{id}/revisions/{revision}", func(w http.ResponseWriter, r *http.Request) {
|
||||
revision, err := strconv.ParseInt(r.PathValue("revision"), 10, 64)
|
||||
if err != nil || revision < 1 {
|
||||
http.Error(w, "invalid binding revision", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
binding, err := capabilityRepository.LoadBinding(r.Context(), capability.CapabilityBindingID(r.PathValue("id")), revision)
|
||||
if err != nil {
|
||||
http.Error(w, "capability binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err = capabilitydomain.ValidateBinding(binding); err != nil {
|
||||
http.Error(w, "capability binding invalid", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(binding)
|
||||
})
|
||||
mux.HandleFunc("GET /v1/capability-bindings/active", func(w http.ResponseWriter, r *http.Request) {
|
||||
capabilityID := capability.CapabilityID(r.URL.Query().Get("capability_id"))
|
||||
ownerID := identity.PrincipalID(r.URL.Query().Get("owner_principal_id"))
|
||||
if capabilityID == "" || ownerID == "" {
|
||||
http.Error(w, "invalid binding query", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
binding, err := capabilityRepository.LoadActiveBinding(r.Context(), capabilityID, ownerID)
|
||||
if err != nil {
|
||||
http.Error(w, "active capability binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err = capabilitydomain.UsableBinding(binding); err != nil {
|
||||
http.Error(w, "active capability binding unavailable", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_ = json.NewEncoder(w).Encode(binding)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/capabilities/health-projection/rebuild", func(w http.ResponseWriter, r *http.Request) {
|
||||
rebuilt, err := capabilityRepository.RebuildHealthProjection(r.Context())
|
||||
if err != nil {
|
||||
|
||||
@@ -159,6 +159,8 @@ func creatorRoute(method, path string) (routeTarget, string, bool) {
|
||||
return targetCommit, "/v1/creator/authorized-actions", true
|
||||
case method == http.MethodPost && path == "/api/actions/satisfy-delivered":
|
||||
return targetCommit, "/v1/creator/continuity/satisfy-delivered", true
|
||||
case method == http.MethodPost && path == "/api/actions/notify-delivered":
|
||||
return targetCommit, "/v1/creator/continuity/notify-delivered", true
|
||||
case method == http.MethodPost && strings.HasPrefix(path, "/api/actions/") && strings.HasSuffix(path, "/reconcile"):
|
||||
id := strings.TrimSuffix(strings.TrimPrefix(path, "/api/actions/"), "/reconcile")
|
||||
if validID(id) {
|
||||
|
||||
@@ -74,6 +74,7 @@ func TestGatewayDeniesInternalAndMutationRoutes(t *testing.T) {
|
||||
{http.MethodGet, "/api/tasks/../../healthz"},
|
||||
{http.MethodPost, "/api/actions/arbitrary"},
|
||||
{http.MethodGet, "/api/actions/satisfy-delivered"},
|
||||
{http.MethodGet, "/api/actions/notify-delivered"},
|
||||
} {
|
||||
request := httptest.NewRequest(test.method, test.path, nil)
|
||||
response := httptest.NewRecorder()
|
||||
@@ -158,6 +159,34 @@ func TestGatewayRoutesOnlyBoundedCreatorCommandsToCommit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayRoutesTypedNotificationCommandToCommit(t *testing.T) {
|
||||
commitRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/creator/continuity/notify-delivered" || r.Method != http.MethodPost {
|
||||
t.Fatalf("unexpected Commit target %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
text := string(body)
|
||||
if !strings.Contains(text, "prospective-1") || !strings.Contains(text, "Confirm") || strings.Contains(text, "URL") || strings.Contains(text, "CapabilityID") {
|
||||
t.Fatalf("unexpected notification body %s", text)
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_, _ = io.WriteString(w, `{"State":"SUCCEEDED"}`)
|
||||
}))
|
||||
defer commitRuntime.Close()
|
||||
handler, err := newHandler("http://core-runtime.invalid", "http://continuity-runtime.invalid", commitRuntime.URL, commitRuntime.Client())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/actions/notify-delivered", strings.NewReader(`{"ProspectiveItemID":"prospective-1","Confirm":true}`))
|
||||
request.Header.Set("Authorization", "Bearer bounded-session")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusCreated {
|
||||
t.Fatalf("response=%d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayRoutesCreatorActionHistoryToCommit(t *testing.T) {
|
||||
commitRuntime := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/creator/authorized-actions" || r.URL.RawQuery != "limit=25" || r.Method != http.MethodGet {
|
||||
|
||||
@@ -198,6 +198,11 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
||||
.action-result strong[data-state="FAILED"] { color: var(--bad); }
|
||||
.action-result strong[data-state="UNKNOWN_OUTCOME"] { color: var(--warn); }
|
||||
.action-result .secondary-button { min-width: 154px; margin: 0; padding: 0 14px; }
|
||||
.notification-command { grid-column: 1 / -1; padding: 14px 0 0; display: flex; align-items: center; justify-content: space-between; gap: 18px; border-top: 1px solid var(--line-soft); }
|
||||
.notification-command div { min-width: 0; }
|
||||
.notification-command strong { display: block; margin-bottom: 5px; color: var(--ink); font: 600 10px/1.2 var(--mono); letter-spacing: .06em; text-transform: uppercase; }
|
||||
.notification-command span { display: block; color: var(--muted); font-size: 11px; line-height: 1.45; }
|
||||
.notification-command .secondary-button { flex: 0 0 auto; min-width: 190px; margin: 0; }
|
||||
.confirmation-dialog { width: min(560px, calc(100vw - 32px)); padding: 0; border: 1px solid var(--line); border-radius: var(--radius); color: var(--ink); background: #111915; box-shadow: var(--shadow); }
|
||||
.confirmation-dialog::backdrop { background: rgba(3, 6, 5, .78); backdrop-filter: blur(5px); }
|
||||
.confirmation-dialog form { padding: 30px; }
|
||||
@@ -269,6 +274,8 @@ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px
|
||||
.commit-zone-copy { grid-column: auto; grid-row: auto; margin-bottom: 6px; }
|
||||
.action-result { grid-template-columns: 1fr; align-items: stretch; }
|
||||
.action-result .secondary-button { width: 100%; }
|
||||
.notification-command { align-items: stretch; flex-direction: column; }
|
||||
.notification-command .secondary-button { width: 100%; }
|
||||
.confirmation-dialog form { padding: 24px 20px; }
|
||||
.confirmation-grid { grid-template-columns: 1fr; }
|
||||
.confirmation-grid .wide { grid-column: auto; }
|
||||
|
||||
@@ -11,6 +11,7 @@ let toastTimer;
|
||||
let currentTask = null;
|
||||
let currentProspective = null;
|
||||
let pendingCommand = null;
|
||||
let pendingNotification = null;
|
||||
let lastAuthorizedActionID = "";
|
||||
|
||||
function setText(id, value, fallback = "—") {
|
||||
@@ -93,6 +94,7 @@ function endSession(message = "Сессия завершена.") {
|
||||
currentTask = null;
|
||||
currentProspective = null;
|
||||
pendingCommand = null;
|
||||
pendingNotification = null;
|
||||
lastAuthorizedActionID = "";
|
||||
notify(message);
|
||||
}
|
||||
@@ -426,6 +428,7 @@ async function loadCapability(capabilityID) {
|
||||
|
||||
function updateActionReadiness() {
|
||||
const button = byId("prepare-satisfaction");
|
||||
const notificationButton = byId("prepare-notification");
|
||||
if (!button) return;
|
||||
const evidence = byId("satisfaction-evidence").value.trim();
|
||||
let message = "Доступно только для доставленного ожидания с проверенной Work-задачей.";
|
||||
@@ -441,6 +444,19 @@ function updateActionReadiness() {
|
||||
}
|
||||
button.disabled = !ready;
|
||||
setText("action-readiness", message);
|
||||
|
||||
let notificationReady = false;
|
||||
let notificationMessage = "Доступно для доставленного ожидания с проверенной Work-задачей.";
|
||||
if (!currentProspective) notificationMessage = "Сначала выберите и загрузите ожидание.";
|
||||
else if (currentProspective.State !== "DELIVERED") notificationMessage = `Состояние ${currentProspective.State || "UNKNOWN"}: уведомление доступно только для DELIVERED.`;
|
||||
else if (!currentTask) notificationMessage = "Загрузите проверенную Work-задачу как обоснование.";
|
||||
else if (currentTask.GoalID !== currentProspective.GoalID || currentTask.ScopeID !== currentProspective.ScopeID) notificationMessage = "Цель или область Work-задачи не совпадает с ожиданием.";
|
||||
else {
|
||||
notificationReady = true;
|
||||
notificationMessage = `Готово: receiver получит фиксированный шаблон для ${currentProspective.ID} · rev ${currentProspective.Revision}.`;
|
||||
}
|
||||
notificationButton.disabled = !notificationReady;
|
||||
setText("notification-readiness", notificationMessage);
|
||||
}
|
||||
|
||||
byId("satisfaction-evidence").addEventListener("input", updateActionReadiness);
|
||||
@@ -473,6 +489,53 @@ byId("cancel-satisfaction").addEventListener("click", () => {
|
||||
byId("satisfaction-dialog").close();
|
||||
});
|
||||
|
||||
byId("prepare-notification").addEventListener("click", () => {
|
||||
updateActionReadiness();
|
||||
if (byId("prepare-notification").disabled || !currentTask || !currentProspective) return;
|
||||
pendingNotification = {
|
||||
Target: {TaskID: currentTask.TaskID, GoalID: currentTask.GoalID, ScopeID: currentTask.ScopeID, Revision: currentTask.Revision},
|
||||
ProspectiveItemID: currentProspective.ID,
|
||||
ExpectedRevision: currentProspective.Revision,
|
||||
Confirm: true,
|
||||
};
|
||||
setText("notify-confirm-prospective", pendingNotification.ProspectiveItemID);
|
||||
setText("notify-confirm-prospective-revision", pendingNotification.ExpectedRevision);
|
||||
setText("notify-confirm-task", pendingNotification.Target.TaskID);
|
||||
setText("notify-confirm-task-revision", pendingNotification.Target.Revision);
|
||||
setText("notification-confirmation-error", "", "");
|
||||
byId("notification-dialog").showModal();
|
||||
});
|
||||
|
||||
byId("cancel-notification").addEventListener("click", () => {
|
||||
pendingNotification = null;
|
||||
byId("notification-dialog").close();
|
||||
});
|
||||
|
||||
byId("confirm-notification").addEventListener("click", async () => {
|
||||
if (!pendingNotification) return;
|
||||
const command = pendingNotification;
|
||||
const button = byId("confirm-notification");
|
||||
const prepare = byId("prepare-notification");
|
||||
button.disabled = true;
|
||||
prepare.disabled = true;
|
||||
button.textContent = "Отправляю…";
|
||||
setText("notification-confirmation-error", "", "");
|
||||
try {
|
||||
const result = await request("/api/actions/notify-delivered", {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(command)});
|
||||
pendingNotification = null;
|
||||
byId("notification-dialog").close();
|
||||
renderActionResult(result);
|
||||
await loadActionHistory();
|
||||
notify(result.State === "SUCCEEDED" ? "Receiver принял уведомление." : "Исход отправки требует сверки.");
|
||||
} catch (error) {
|
||||
setText("notification-confirmation-error", error.message);
|
||||
} finally {
|
||||
button.disabled = false;
|
||||
button.textContent = "Подтверждаю отправку";
|
||||
updateActionReadiness();
|
||||
}
|
||||
});
|
||||
|
||||
byId("confirm-satisfaction").addEventListener("click", async () => {
|
||||
if (!pendingCommand) return;
|
||||
const command = pendingCommand;
|
||||
|
||||
@@ -164,6 +164,10 @@
|
||||
<button id="prepare-satisfaction" class="commit-button" type="button" disabled>
|
||||
<span>Отметить исполненным</span><span aria-hidden="true">→</span>
|
||||
</button>
|
||||
<div class="notification-command">
|
||||
<div><strong>Windows-напоминание</strong><span id="notification-readiness">Доступно для доставленного ожидания с проверенной Work-задачей.</span></div>
|
||||
<button id="prepare-notification" class="secondary-button" type="button" disabled>Отправить уведомление</button>
|
||||
</div>
|
||||
<div id="action-result" class="action-result" hidden>
|
||||
<div><span>ИСХОД</span><strong id="action-state">—</strong></div>
|
||||
<div><span>ACTION</span><code id="action-id">—</code></div>
|
||||
@@ -209,6 +213,26 @@
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<dialog id="notification-dialog" class="confirmation-dialog" aria-labelledby="notification-confirmation-title">
|
||||
<form method="dialog">
|
||||
<p class="eyebrow">commit / внешнее действие</p>
|
||||
<h2 id="notification-confirmation-title">Отправить напоминание?</h2>
|
||||
<p class="confirmation-copy">Домовой создаст неизменяемое авторизованное действие и передаст типизированное уведомление в закреплённый receiver. Состояние Continuity не изменится; доставка не означает прочтение.</p>
|
||||
<dl class="confirmation-grid">
|
||||
<div><dt>Ожидание</dt><dd id="notify-confirm-prospective">—</dd></div>
|
||||
<div><dt>Ревизия</dt><dd id="notify-confirm-prospective-revision">—</dd></div>
|
||||
<div><dt>Work-задача</dt><dd id="notify-confirm-task">—</dd></div>
|
||||
<div><dt>Ревизия Work</dt><dd id="notify-confirm-task-revision">—</dd></div>
|
||||
<div class="wide"><dt>Канал</dt><dd>Локальное уведомление Windows · закреплённый receiver</dd></div>
|
||||
</dl>
|
||||
<p id="notification-confirmation-error" class="form-error" role="alert"></p>
|
||||
<div class="confirmation-actions">
|
||||
<button id="cancel-notification" class="text-button" type="button">Отмена</button>
|
||||
<button id="confirm-notification" class="commit-button" type="button">Подтверждаю отправку</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
|
||||
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
|
||||
<script src="/assets/console.js" defer></script>
|
||||
</body>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
addr := envOr("LISTEN_ADDR", ":8085")
|
||||
writeToken, err := readSecretFile("RECEIVER_WRITE_TOKEN_FILE")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
readToken, err := readSecretFile("RECEIVER_READ_TOKEN_FILE")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
server, err := newReceiverServer(envOr("RECEIPT_DIRECTORY", "/var/lib/notification-receiver"), writeToken, readToken, time.Now)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
log.Printf("notification-receiver listening on %s", addr)
|
||||
if err = http.ListenAndServe(addr, server.routes()); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func readSecretFile(name string) (string, error) {
|
||||
path := os.Getenv(name)
|
||||
if path == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
value, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", name, err)
|
||||
}
|
||||
secret := strings.TrimSpace(string(value))
|
||||
if secret == "" {
|
||||
return "", fmt.Errorf("%s is empty", name)
|
||||
}
|
||||
return secret, nil
|
||||
}
|
||||
func envOr(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
)
|
||||
|
||||
const maxDeliveryBytes = 8 << 10
|
||||
|
||||
var safeIntent = regexp.MustCompile(`^[A-Za-z0-9_-]{1,128}$`)
|
||||
|
||||
type storedReceipt struct {
|
||||
notificationexecutor.Receipt
|
||||
Payload notificationexecutor.Payload `json:"payload"`
|
||||
}
|
||||
|
||||
type receiverServer struct {
|
||||
directory string
|
||||
writeToken string
|
||||
readToken string
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newReceiverServer(directory, writeToken, readToken string, now func() time.Time) (*receiverServer, error) {
|
||||
if directory == "" || strings.TrimSpace(writeToken) == "" || strings.TrimSpace(readToken) == "" ||
|
||||
writeToken == readToken || now == nil {
|
||||
return nil, errors.New("invalid receiver configuration")
|
||||
}
|
||||
if err := os.MkdirAll(directory, 0700); err != nil {
|
||||
return nil, fmt.Errorf("create receipt directory: %w", err)
|
||||
}
|
||||
return &receiverServer{directory: directory, writeToken: writeToken, readToken: readToken, now: now}, nil
|
||||
}
|
||||
|
||||
func (s *receiverServer) routes() http.Handler {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = io.WriteString(w, `{"status":"ok"}`)
|
||||
})
|
||||
mux.HandleFunc("PUT /delivery/v1/deliveries/{intent}", s.put)
|
||||
mux.HandleFunc("GET /delivery/v1/receipts/{intent}", s.get)
|
||||
mux.HandleFunc("GET /delivery/v1/receipts", s.list)
|
||||
return mux
|
||||
}
|
||||
|
||||
func (s *receiverServer) put(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.writeToken, r) {
|
||||
http.Error(w, "receiver writer denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
intent := r.PathValue("intent")
|
||||
if !safeIntent.MatchString(intent) {
|
||||
http.Error(w, "invalid action intent", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
var request notificationexecutor.DeliveryRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, maxDeliveryBytes))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil || string(request.ActionIntentID) != intent {
|
||||
http.Error(w, "invalid delivery", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := ensureEOF(decoder); err != nil {
|
||||
http.Error(w, "invalid delivery", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
digest, err := notificationexecutor.Digest(request.Payload)
|
||||
if err != nil || digest != request.RequestDigest {
|
||||
http.Error(w, "delivery digest mismatch", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
receipt := storedReceipt{Receipt: notificationexecutor.Receipt{ReceiptID: "receipt-" + intent, ActionIntentID: request.ActionIntentID, RequestDigest: digest, AcceptedAt: s.now().UnixMilli()}, Payload: request.Payload}
|
||||
created, existing, err := s.create(receipt)
|
||||
if err != nil {
|
||||
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !created {
|
||||
if existing.RequestDigest != digest {
|
||||
http.Error(w, "action intent digest conflict", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
receipt = existing
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if created {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(receipt)
|
||||
}
|
||||
|
||||
func (s *receiverServer) get(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.writeToken, r) && !tokenMatches(s.readToken, r) {
|
||||
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
intent := r.PathValue("intent")
|
||||
if !safeIntent.MatchString(intent) {
|
||||
http.Error(w, "invalid action intent", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
receipt, err := s.load(intent)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
http.Error(w, "receipt not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "receipt unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
writeStoredReceipt(w, receipt)
|
||||
}
|
||||
|
||||
func (s *receiverServer) list(w http.ResponseWriter, r *http.Request) {
|
||||
if !tokenMatches(s.readToken, r) {
|
||||
http.Error(w, "receiver reader denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
limit := 50
|
||||
if raw := r.URL.Query().Get("limit"); raw != "" {
|
||||
parsed, err := strconv.Atoi(raw)
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
http.Error(w, "invalid limit", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
entries, err := os.ReadDir(s.directory)
|
||||
if err != nil {
|
||||
http.Error(w, "receipts unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
receipts := make([]storedReceipt, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".json" {
|
||||
continue
|
||||
}
|
||||
receipt, loadErr := s.load(strings.TrimSuffix(entry.Name(), ".json"))
|
||||
if loadErr != nil {
|
||||
continue
|
||||
}
|
||||
receipts = append(receipts, receipt)
|
||||
}
|
||||
sort.Slice(receipts, func(i, j int) bool {
|
||||
if receipts[i].AcceptedAt == receipts[j].AcceptedAt {
|
||||
return receipts[i].ReceiptID > receipts[j].ReceiptID
|
||||
}
|
||||
return receipts[i].AcceptedAt > receipts[j].AcceptedAt
|
||||
})
|
||||
if len(receipts) > limit {
|
||||
receipts = receipts[:limit]
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Items []storedReceipt `json:"items"`
|
||||
}{Items: receipts})
|
||||
}
|
||||
|
||||
func (s *receiverServer) create(receipt storedReceipt) (bool, storedReceipt, error) {
|
||||
encoded, err := json.Marshal(receipt)
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
temporary, err := os.CreateTemp(s.directory, ".receipt-*.tmp")
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
temporaryName := temporary.Name()
|
||||
defer os.Remove(temporaryName)
|
||||
if err = temporary.Chmod(0600); err == nil {
|
||||
_, err = temporary.Write(encoded)
|
||||
}
|
||||
if err == nil {
|
||||
err = temporary.Sync()
|
||||
}
|
||||
closeErr := temporary.Close()
|
||||
if err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
target := s.path(string(receipt.ActionIntentID))
|
||||
if err = os.Link(temporaryName, target); err == nil {
|
||||
return true, storedReceipt{}, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrExist) {
|
||||
return false, storedReceipt{}, err
|
||||
}
|
||||
existing, err := s.load(string(receipt.ActionIntentID))
|
||||
return false, existing, err
|
||||
}
|
||||
|
||||
func (s *receiverServer) load(intent string) (storedReceipt, error) {
|
||||
var receipt storedReceipt
|
||||
file, err := os.Open(s.path(intent))
|
||||
if err != nil {
|
||||
return receipt, err
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, maxDeliveryBytes+1))
|
||||
if err = decoder.Decode(&receipt); err != nil {
|
||||
return storedReceipt{}, err
|
||||
}
|
||||
if string(receipt.ActionIntentID) != intent {
|
||||
return storedReceipt{}, errors.New("receipt identity mismatch")
|
||||
}
|
||||
return receipt, nil
|
||||
}
|
||||
|
||||
func (s *receiverServer) path(intent string) string {
|
||||
return filepath.Join(s.directory, intent+".json")
|
||||
}
|
||||
func tokenMatches(expected string, r *http.Request) bool {
|
||||
provided := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
return len(provided) == len(expected) && subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
|
||||
}
|
||||
func ensureEOF(decoder *json.Decoder) error {
|
||||
var extra any
|
||||
err := decoder.Decode(&extra)
|
||||
if errors.Is(err, io.EOF) {
|
||||
return nil
|
||||
}
|
||||
return errors.New("trailing JSON")
|
||||
}
|
||||
func writeStoredReceipt(w http.ResponseWriter, receipt storedReceipt) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
_ = json.NewEncoder(w).Encode(receipt)
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/adapters/notificationexecutor"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
)
|
||||
|
||||
func delivery(t *testing.T, intent, message string) notificationexecutor.DeliveryRequest {
|
||||
t.Helper()
|
||||
payload := notificationexecutor.Payload{ActionIntentID: commitcontract.ActionIntentID(intent), TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, ProspectiveItemID: "item-1", ExpectedRevision: 1, Title: "Домовой", Message: message}
|
||||
digest, err := notificationexecutor.Digest(payload)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return notificationexecutor.DeliveryRequest{Payload: payload, RequestDigest: digest}
|
||||
}
|
||||
|
||||
func request(t *testing.T, handler http.Handler, method, path, token string, value any) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
var body bytes.Buffer
|
||||
if value != nil {
|
||||
if err := json.NewEncoder(&body).Encode(value); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest(method, path, &body)
|
||||
if token != "" {
|
||||
r.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func TestReceiverIdempotencyConflictAndRestart(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
clock := func() time.Time { return time.UnixMilli(100) }
|
||||
server, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first := delivery(t, "intent-1", "message one")
|
||||
w := request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", first)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("repeat status %d", w.Code)
|
||||
}
|
||||
conflict := delivery(t, "intent-1", "different")
|
||||
w = request(t, server.routes(), http.MethodPut, "/delivery/v1/deliveries/intent-1", "write-secret", conflict)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("conflict status %d", w.Code)
|
||||
}
|
||||
restarted, err := newReceiverServer(directory, "write-secret", "read-secret", clock)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts/intent-1", "write-secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("restart get status %d", w.Code)
|
||||
}
|
||||
w = request(t, restarted.routes(), http.MethodGet, "/delivery/v1/receipts?limit=10", "read-secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("list status %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverSeparatesReadAndWriteAuthority(t *testing.T) {
|
||||
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
handler := server.routes()
|
||||
value := delivery(t, "intent-1", "message")
|
||||
if w := request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-1", "read-secret", value); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("reader wrote: %d", w.Code)
|
||||
}
|
||||
if w := request(t, handler, http.MethodGet, "/delivery/v1/receipts", "write-secret", nil); w.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("writer listed: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentDuplicateCreatesOneReceipt(t *testing.T) {
|
||||
server, err := newReceiverServer(t.TempDir(), "write-secret", "read-secret", time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
value := delivery(t, "intent-concurrent", "message")
|
||||
handler := server.routes()
|
||||
codes := make(chan int, 8)
|
||||
var group sync.WaitGroup
|
||||
for range 8 {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
codes <- request(t, handler, http.MethodPut, "/delivery/v1/deliveries/intent-concurrent", "write-secret", value).Code
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(codes)
|
||||
created := 0
|
||||
for code := range codes {
|
||||
if code == http.StatusCreated {
|
||||
created++
|
||||
} else if code != http.StatusOK {
|
||||
t.Fatalf("unexpected status %d", code)
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Fatalf("created=%d", created)
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,40 @@
|
||||
package capability
|
||||
|
||||
import "git.cin.su/m/Assistant/platform/ids"
|
||||
import (
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
type CapabilityID ids.ID
|
||||
type CapabilityBindingID ids.ID
|
||||
|
||||
type BindingState string
|
||||
type BindingProtocol string
|
||||
|
||||
const (
|
||||
BindingActive BindingState = "ACTIVE"
|
||||
BindingRetired BindingState = "RETIRED"
|
||||
|
||||
ProtocolIdempotentReceiptV1 BindingProtocol = "IDEMPOTENT_RECEIPT_V1"
|
||||
)
|
||||
|
||||
// Binding is Capability-owned correctness state. SecretRef is an opaque
|
||||
// lookup name; it must never contain credential bytes.
|
||||
type Binding struct {
|
||||
ID CapabilityBindingID
|
||||
CapabilityID CapabilityID
|
||||
OwnerPrincipalID identity.PrincipalID
|
||||
Revision int64
|
||||
State BindingState
|
||||
HTTPSOrigin string
|
||||
DeliveryPath string
|
||||
ReceiptPath string
|
||||
Protocol BindingProtocol
|
||||
SecretRef string
|
||||
VerifiedAtUnixMillis int64
|
||||
Health HealthState
|
||||
}
|
||||
|
||||
type HealthState string
|
||||
|
||||
const (
|
||||
|
||||
+29
-11
@@ -28,20 +28,38 @@ const (
|
||||
type ExternalOperation string
|
||||
|
||||
const (
|
||||
CapabilityTestExecutor capability.CapabilityID = "test-executor"
|
||||
CapabilityContinuityTransition capability.CapabilityID = "continuity-transition"
|
||||
OperationTestIdempotentEffect ExternalOperation = "test-idempotent-effect"
|
||||
OperationSatisfyDelivered ExternalOperation = "satisfy-delivered"
|
||||
CapabilityTestExecutor capability.CapabilityID = "test-executor"
|
||||
CapabilityContinuityTransition capability.CapabilityID = "continuity-transition"
|
||||
CapabilityProspectiveNotification capability.CapabilityID = "prospective-notification-delivery"
|
||||
OperationTestIdempotentEffect ExternalOperation = "test-idempotent-effect"
|
||||
OperationSatisfyDelivered ExternalOperation = "satisfy-delivered"
|
||||
OperationDeliverProspectiveNotification ExternalOperation = "deliver-prospective-notification-v1"
|
||||
)
|
||||
|
||||
const ProspectiveDeliveredTemplateV1 = "prospective-delivered-v1"
|
||||
|
||||
// ProspectiveNotificationSubject is immutable Commit evidence. Destination
|
||||
// data is resolved from the exact Capability binding revision, never from UI.
|
||||
type ProspectiveNotificationSubject struct {
|
||||
ProspectiveItemID continuity.ProspectiveItemID
|
||||
ExpectedRevision continuity.ProspectiveRevision
|
||||
TemplateCode string
|
||||
BindingID capability.CapabilityBindingID
|
||||
BindingRevision int64
|
||||
RenderedTitle string
|
||||
RenderedMessage string
|
||||
RequestDigest string
|
||||
}
|
||||
|
||||
type ActionProposal struct {
|
||||
IntentID ActionIntentID
|
||||
ActorID identity.ActorID
|
||||
CapabilityID capability.CapabilityID
|
||||
Target work.TaskTarget
|
||||
Operation ExternalOperation
|
||||
ContinuitySubject continuity.SatisfyDeliveredSubject
|
||||
State ActionState
|
||||
IntentID ActionIntentID
|
||||
ActorID identity.ActorID
|
||||
CapabilityID capability.CapabilityID
|
||||
Target work.TaskTarget
|
||||
Operation ExternalOperation
|
||||
ContinuitySubject continuity.SatisfyDeliveredSubject
|
||||
NotificationSubject ProspectiveNotificationSubject
|
||||
State ActionState
|
||||
}
|
||||
|
||||
type AuthorizedAction struct {
|
||||
|
||||
@@ -110,9 +110,20 @@ CREATE TABLE IF NOT EXISTS commit.authorized_action_envelopes (
|
||||
action_state TEXT NOT NULL,
|
||||
authorized_at_unix_millis BIGINT NOT NULL,
|
||||
envelope_revision BIGINT NOT NULL,
|
||||
notification_template_code TEXT NOT NULL DEFAULT '',
|
||||
capability_binding_id TEXT NOT NULL DEFAULT '',
|
||||
capability_binding_revision BIGINT NOT NULL DEFAULT 0,
|
||||
notification_title TEXT NOT NULL DEFAULT '',
|
||||
notification_message TEXT NOT NULL DEFAULT '',
|
||||
request_digest TEXT NOT NULL DEFAULT '',
|
||||
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CHECK (grant_revision > 0), CHECK (task_revision > 0),
|
||||
CHECK (authorized_at_unix_millis > 0), CHECK (envelope_revision = 1)
|
||||
CHECK (authorized_at_unix_millis > 0), CHECK (envelope_revision = 1),
|
||||
CHECK (operation <> 'deliver-prospective-notification-v1' OR (
|
||||
notification_template_code = 'prospective-delivered-v1' AND notification_title <> '' AND notification_message <> '' AND capability_binding_id <> '' AND
|
||||
capability_binding_revision > 0 AND request_digest ~ '^[0-9a-f]{64}$' AND
|
||||
expected_prospective_revision > 0 AND prospective_item_id <> ''
|
||||
))
|
||||
);
|
||||
RESET ROLE;
|
||||
|
||||
@@ -157,6 +168,23 @@ CREATE TABLE IF NOT EXISTS capability.health_projection (
|
||||
semantic_version INTEGER NOT NULL,
|
||||
observed_at_unix_millis BIGINT
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS capability.notification_bindings (
|
||||
binding_id TEXT NOT NULL, capability_id TEXT NOT NULL, owner_principal_id TEXT NOT NULL,
|
||||
revision BIGINT NOT NULL, state TEXT NOT NULL, https_origin TEXT NOT NULL,
|
||||
delivery_path TEXT NOT NULL, receipt_path TEXT NOT NULL, protocol TEXT NOT NULL,
|
||||
secret_ref TEXT NOT NULL, verified_at_unix_millis BIGINT NOT NULL, health TEXT NOT NULL,
|
||||
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (binding_id, revision),
|
||||
CHECK (revision > 0), CHECK (verified_at_unix_millis > 0),
|
||||
CHECK (state IN ('ACTIVE','RETIRED')), CHECK (health IN ('AVAILABLE','DEGRADED','UNAVAILABLE')),
|
||||
CHECK (protocol = 'IDEMPOTENT_RECEIPT_V1'), CHECK (https_origin LIKE 'https://%'),
|
||||
CHECK (delivery_path LIKE '/%'), CHECK (receipt_path LIKE '/%')
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS capability.notification_binding_heads (
|
||||
capability_id TEXT NOT NULL, owner_principal_id TEXT NOT NULL,
|
||||
binding_id TEXT NOT NULL, revision BIGINT NOT NULL,
|
||||
PRIMARY KEY (capability_id, owner_principal_id), CHECK (revision > 0)
|
||||
);
|
||||
RESET ROLE;
|
||||
|
||||
SET ROLE continuity_role;
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
BEGIN;
|
||||
SET ROLE capability_role;
|
||||
CREATE TABLE IF NOT EXISTS capability.notification_bindings (
|
||||
binding_id TEXT NOT NULL,
|
||||
capability_id TEXT NOT NULL,
|
||||
owner_principal_id TEXT NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
state TEXT NOT NULL,
|
||||
https_origin TEXT NOT NULL,
|
||||
delivery_path TEXT NOT NULL,
|
||||
receipt_path TEXT NOT NULL,
|
||||
protocol TEXT NOT NULL,
|
||||
secret_ref TEXT NOT NULL,
|
||||
verified_at_unix_millis BIGINT NOT NULL,
|
||||
health TEXT NOT NULL,
|
||||
recorded_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (binding_id, revision),
|
||||
CHECK (revision > 0),
|
||||
CHECK (verified_at_unix_millis > 0),
|
||||
CHECK (state IN ('ACTIVE','RETIRED')),
|
||||
CHECK (health IN ('AVAILABLE','DEGRADED','UNAVAILABLE')),
|
||||
CHECK (protocol = 'IDEMPOTENT_RECEIPT_V1'),
|
||||
CHECK (https_origin LIKE 'https://%'),
|
||||
CHECK (delivery_path LIKE '/%'),
|
||||
CHECK (receipt_path LIKE '/%')
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS capability.notification_binding_heads (
|
||||
capability_id TEXT NOT NULL,
|
||||
owner_principal_id TEXT NOT NULL,
|
||||
binding_id TEXT NOT NULL,
|
||||
revision BIGINT NOT NULL,
|
||||
PRIMARY KEY (capability_id, owner_principal_id),
|
||||
CHECK (revision > 0)
|
||||
);
|
||||
RESET ROLE;
|
||||
COMMIT;
|
||||
@@ -0,0 +1,22 @@
|
||||
BEGIN;
|
||||
SET ROLE commit_role;
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_template_code TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS capability_binding_id TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS capability_binding_revision BIGINT NOT NULL DEFAULT 0;
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_title TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS notification_message TEXT NOT NULL DEFAULT '';
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD COLUMN IF NOT EXISTS request_digest TEXT NOT NULL DEFAULT '';
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname='authorized_action_notification_evidence_v1' AND conrelid='commit.authorized_action_envelopes'::regclass) THEN
|
||||
ALTER TABLE commit.authorized_action_envelopes ADD CONSTRAINT authorized_action_notification_evidence_v1 CHECK (
|
||||
operation <> 'deliver-prospective-notification-v1' OR (
|
||||
notification_template_code = 'prospective-delivered-v1' AND notification_title <> '' AND notification_message <> '' AND
|
||||
capability_binding_id <> '' AND capability_binding_revision > 0 AND
|
||||
request_digest ~ '^[0-9a-f]{64}$' AND expected_prospective_revision > 0 AND prospective_item_id <> ''
|
||||
)
|
||||
) NOT VALID;
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE commit.authorized_action_envelopes VALIDATE CONSTRAINT authorized_action_notification_evidence_v1;
|
||||
RESET ROLE;
|
||||
COMMIT;
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"task_file": "dev/tasks/ARCH-000006-accept-prospective-notification-delivery.json",
|
||||
"task_id": "ARCH-000006",
|
||||
"task_file": "dev/tasks/DEV-000042-creator-notification-command.json",
|
||||
"task_id": "DEV-000042",
|
||||
"task_revision": 1
|
||||
}
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"task_id": "DEV-000041",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0005",
|
||||
"base_repo_revision": "45fb5f8709ef9f327c5e41e7f9adb0d7a7d06866",
|
||||
"risk_tier": "E",
|
||||
"intent": "Implement the non-user-facing foundation for ADR-0005: Capability-owned versioned receiver binding, typed Commit notification evidence, a durable idempotent receipt receiver, and a strict HTTPS executor/reconciler adapter without enabling a Creator mutation route or installing credentials.",
|
||||
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "INV-TOPO-001", "ADR-0005"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["capability", "commit"],
|
||||
"paths": [
|
||||
"contracts/capability/types.go",
|
||||
"contracts/commit/types.go",
|
||||
"modules/capability/domain/binding.go",
|
||||
"modules/capability/domain/binding_test.go",
|
||||
"modules/capability/ports/repository.go",
|
||||
"adapters/postgres/capability_repository.go",
|
||||
"adapters/postgres/capability_repository_test.go",
|
||||
"adapters/postgres/commit_repository.go",
|
||||
"adapters/notificationexecutor/executor.go",
|
||||
"adapters/notificationexecutor/executor_test.go",
|
||||
"cmd/core-runtime/main.go",
|
||||
"cmd/core-runtime/main_test.go",
|
||||
"cmd/notification-receiver/main.go",
|
||||
"cmd/notification-receiver/server.go",
|
||||
"cmd/notification-receiver/server_test.go",
|
||||
"database/migrations/010_capability_notification_binding.sql",
|
||||
"database/migrations/011_commit_notification_envelope.sql",
|
||||
"database/bootstrap/001_roles_and_schemas.sql",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000041-notification-delivery-foundation.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": [
|
||||
"architecture/**",
|
||||
"ci/**",
|
||||
".gitea/**",
|
||||
"modules/identity/**",
|
||||
"modules/authority/**",
|
||||
"modules/work/**",
|
||||
"modules/continuity/**",
|
||||
"cmd/creator-web/**",
|
||||
"deploy/**",
|
||||
"security/**"
|
||||
]
|
||||
},
|
||||
"allowed_architecture_delta": {
|
||||
"new_cross_module_dependencies": 0,
|
||||
"new_canonical_owners": 0,
|
||||
"new_privileges": 0,
|
||||
"new_third_party_dependencies": 0
|
||||
},
|
||||
"contracts": {
|
||||
"consume": ["contracts.identity@v1", "contracts.capability@v1", "contracts.commit@v1", "ADR-0005 fixed receipt protocol"],
|
||||
"may_change": ["CapabilityBinding V1", "Commit prospective notification evidence V1"]
|
||||
},
|
||||
"semantic_owner": "Capability owns binding state; Commit owns immutable action evidence; receiver storage is external adapter receipt state",
|
||||
"canonical_state": ["capability.notification_bindings", "future Commit envelope columns only; no action rows created by this task"],
|
||||
"state_transitions": ["CapabilityBinding ACTIVE to RETIRED with monotonic revision", "receiver receipt absent to immutable present"],
|
||||
"side_effects_and_privileges": ["receiver PUT writes only its isolated receipt directory", "receiver GET/list are read-only", "HTTPS adapter accepts only a validated fixed binding", "no credentials installed and no route exposed to Creator"],
|
||||
"persistence_and_migrations": ["add Capability-owned binding table", "add backward-compatible notification evidence columns to Commit envelope", "receiver uses atomic create and immutable receipt files"],
|
||||
"failure_retry_restart": ["same intent and digest returns the original receipt", "same intent with different digest is conflict", "timeout or malformed success is unknown", "GET reconciliation never writes", "restart rebuilds receiver truth from durable receipt files"],
|
||||
"assumptions": ["The public TLS reverse proxy is configured only in a later deployment task", "secret references are identifiers and never secret bytes", "docker-test remains prohibited"],
|
||||
"acceptance_scenarios": ["binding validation rejects HTTP, non-fixed paths, invalid revisions, unhealthy or retired state", "owner-local binding load cannot return a foreign principal binding", "receiver authorization separates writer and reader", "receiver survives restart and keeps one receipt per action intent", "executor disables redirects, bounds response size, verifies receipt identity and digest, and classifies ambiguous failures as unknown", "historical Commit rows remain readable after additive migration", "no Creator command can invoke the new executor in this task"],
|
||||
"required_tests": ["unit", "receiver restart and conflict", "TLS executor and reconciliation", "PostgreSQL repository contract where available", "architecture preflight", "exact diff scope", "go test", "go vet", "CI"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"task_id": "DEV-000042",
|
||||
"task_revision": 1,
|
||||
"architecture_revision": "ADR-0005",
|
||||
"base_repo_revision": "6e0040fe89c938549295798c77006877902a338d",
|
||||
"risk_tier": "E",
|
||||
"intent": "Enable the ADR-0005 typed prospective notification command through the authenticated Creator flow, exact CapabilityBinding validation, dynamic Commit Executor dispatch, and an explicit confirmation control in the Creator console without installing production credentials or deploying.",
|
||||
"requirement_ids": ["INV-AUTH-001", "INV-OWN-001", "INV-CONT-001", "ADR-0005"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["commit"],
|
||||
"paths": [
|
||||
"modules/commit/domain/commit.go",
|
||||
"modules/commit/domain/notification_test.go",
|
||||
"adapters/notificationexecutor/executor.go",
|
||||
"adapters/notificationexecutor/executor_test.go",
|
||||
"cmd/commit-runtime/creator_clients.go",
|
||||
"cmd/commit-runtime/creator_command.go",
|
||||
"cmd/commit-runtime/creator_command_test.go",
|
||||
"cmd/commit-runtime/main.go",
|
||||
"cmd/commit-runtime/notification_executor.go",
|
||||
"cmd/commit-runtime/notification_executor_test.go",
|
||||
"cmd/creator-web/server.go",
|
||||
"cmd/creator-web/server_test.go",
|
||||
"cmd/creator-web/static/index.html",
|
||||
"cmd/creator-web/static/assets/console.js",
|
||||
"cmd/creator-web/static/assets/console.css",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/DEV-000042-creator-notification-command.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": ["architecture/**", "ci/**", ".gitea/**", "database/**", "deploy/**", "security/**", "modules/identity/**", "modules/authority/**", "modules/work/**", "modules/continuity/**"]
|
||||
},
|
||||
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 0, "new_third_party_dependencies": 0},
|
||||
"contracts": {"consume": ["contracts.identity@v1", "contracts.authority@v1", "contracts.work@v1", "contracts.continuity@v1", "contracts.capability@v1", "contracts.commit@v1", "ADR-0005"], "may_change": []},
|
||||
"semantic_owner": "Commit owns action evidence and attempts; Capability owns binding; Continuity owns the unchanged ProspectiveItem; Creator UI is a replaceable projection",
|
||||
"canonical_state": ["existing Commit authorized action envelopes and attempts only"],
|
||||
"state_transitions": ["notification action AUTHORIZED to EXECUTING to SUCCEEDED, FAILED, or UNKNOWN_OUTCOME", "ProspectiveItem remains DELIVERED"],
|
||||
"side_effects_and_privileges": ["new Creator route may invoke only deliver-prospective-notification-v1 after explicit confirmation", "Executor resolves only the exact committed binding and configured external secret reference", "no credential installation or production call in this task"],
|
||||
"persistence_and_migrations": ["uses DEV-000041 additive schema; no migration in this task"],
|
||||
"failure_retry_restart": ["stale item, Work target, grant, binding, owner or digest fail closed", "ambiguous PUT records UNKNOWN_OUTCOME", "reconciliation uses GET only", "retired historical binding may reconcile but cannot execute a new send"],
|
||||
"assumptions": ["one configured write secret reference is sufficient for the initial receiver", "browser confirmation is explicit per notification request", "docker-test remains prohibited"],
|
||||
"acceptance_scenarios": ["browser cannot submit actor, principal, capability, operation, destination, template, body, IDs, headers or credentials", "confirmation=false is rejected", "foreign owner, non-DELIVERED or stale item, stale Work, invalid grant, and missing/unhealthy/revised binding are rejected before external execution", "server renders the fixed V1 message and digest", "dynamic executor dispatch leaves existing Continuity satisfaction unchanged", "action history identifies notification actions", "UI exposes clear pending/success/unknown/error states and remains usable on desktop/mobile"],
|
||||
"required_tests": ["domain authorization", "hostile request fields", "dynamic executor dispatch", "Creator HTTP", "gateway allowlist", "responsive browser", "browser console", "architecture preflight", "exact diff scope", "go test", "go vet", "CI"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_CONFLICT", "BLOCKED_BY_MISSING_CAPABILITY"]
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
)
|
||||
|
||||
var ErrInvalidBinding = errors.New("invalid capability binding")
|
||||
|
||||
func ValidateBinding(binding capability.Binding) error {
|
||||
if binding.ID == "" || binding.CapabilityID == "" || binding.OwnerPrincipalID == "" ||
|
||||
binding.Revision < 1 || binding.Protocol != capability.ProtocolIdempotentReceiptV1 ||
|
||||
binding.SecretRef == "" || binding.VerifiedAtUnixMillis <= 0 {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
if binding.State != capability.BindingActive && binding.State != capability.BindingRetired {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
if binding.Health != capability.HealthAvailable && binding.Health != capability.HealthDegraded && binding.Health != capability.HealthUnavailable {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
origin, err := url.Parse(binding.HTTPSOrigin)
|
||||
if err != nil || origin.Scheme != "https" || origin.Host == "" || origin.User != nil || origin.RawQuery != "" || origin.Fragment != "" || (origin.Path != "" && origin.Path != "/") {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
if !fixedPath(binding.DeliveryPath) || !fixedPath(binding.ReceiptPath) || binding.DeliveryPath == binding.ReceiptPath {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func UsableBinding(binding capability.Binding) error {
|
||||
if err := ValidateBinding(binding); err != nil || binding.State != capability.BindingActive || binding.Health != capability.HealthAvailable {
|
||||
return ErrInvalidBinding
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RetireBinding(binding capability.Binding) (capability.Binding, error) {
|
||||
if err := ValidateBinding(binding); err != nil || binding.State != capability.BindingActive {
|
||||
return capability.Binding{}, ErrInvalidBinding
|
||||
}
|
||||
binding.State = capability.BindingRetired
|
||||
binding.Revision++
|
||||
return binding, nil
|
||||
}
|
||||
|
||||
func fixedPath(value string) bool {
|
||||
return strings.HasPrefix(value, "/") && value != "/" && !strings.HasSuffix(value, "/") &&
|
||||
!strings.Contains(value, "//") && !strings.ContainsAny(value, "?#\\") && !strings.Contains(value, "..")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
func validBinding() capability.Binding {
|
||||
return capability.Binding{ID: "binding-1", CapabilityID: "prospective-notification-delivery", OwnerPrincipalID: identity.PrincipalID("owner-1"), Revision: 1, State: capability.BindingActive, HTTPSOrigin: "https://assistent.cin.su", DeliveryPath: "/delivery/v1/receipts", ReceiptPath: "/delivery/v1/receipts", Protocol: capability.ProtocolIdempotentReceiptV1, SecretRef: "notification-write-v1", VerifiedAtUnixMillis: 1, Health: capability.HealthAvailable}
|
||||
}
|
||||
|
||||
func TestValidateBinding(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.ReceiptPath = "/delivery/v1/lookup"
|
||||
if err := ValidateBinding(b); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, mutate := range []func(*capability.Binding){
|
||||
func(v *capability.Binding) { v.HTTPSOrigin = "http://assistent.cin.su" },
|
||||
func(v *capability.Binding) { v.DeliveryPath = "//evil" },
|
||||
func(v *capability.Binding) { v.SecretRef = "" },
|
||||
func(v *capability.Binding) { v.Revision = 0 },
|
||||
func(v *capability.Binding) { v.Health = capability.HealthDegraded },
|
||||
} {
|
||||
candidate := b
|
||||
mutate(&candidate)
|
||||
if err := UsableBinding(candidate); err == nil {
|
||||
t.Fatalf("expected rejection: %+v", candidate)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetireBindingIncrementsRevision(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.ReceiptPath = "/delivery/v1/lookup"
|
||||
retired, err := RetireBinding(b)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if retired.State != capability.BindingRetired || retired.Revision != 2 {
|
||||
t.Fatalf("unexpected retired binding: %+v", retired)
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,14 @@ import (
|
||||
"context"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/capability"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
SaveHealth(context.Context, capability.Health) error
|
||||
LoadHealth(context.Context, capability.CapabilityID) (capability.Health, error)
|
||||
RebuildHealthProjection(context.Context) (int64, error)
|
||||
SaveBinding(context.Context, capability.Binding) error
|
||||
LoadBinding(context.Context, capability.CapabilityBindingID, int64) (capability.Binding, error)
|
||||
LoadActiveBinding(context.Context, capability.CapabilityID, identity.PrincipalID) (capability.Binding, error)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
@@ -71,11 +72,22 @@ func allowedOperation(proposal commitcontract.ActionProposal, context Authorizat
|
||||
return subject.ProspectiveItemID != "" && subject.ExpectedRevision > 0 &&
|
||||
subject.FromState == continuity.ProspectiveDelivered && subject.ToState == continuity.ProspectiveSatisfied &&
|
||||
strings.TrimSpace(subject.EvidenceRef) != ""
|
||||
case context.Grant.Class == authority.GrantClassCreator && proposal.CapabilityID == commitcontract.CapabilityProspectiveNotification && proposal.Operation == commitcontract.OperationDeliverProspectiveNotification:
|
||||
subject := proposal.NotificationSubject
|
||||
return subject.ProspectiveItemID != "" && subject.ExpectedRevision > 0 &&
|
||||
subject.TemplateCode == commitcontract.ProspectiveDeliveredTemplateV1 && subject.BindingID != "" && subject.BindingRevision > 0 &&
|
||||
strings.TrimSpace(subject.RenderedTitle) != "" && len(subject.RenderedTitle) <= 160 &&
|
||||
strings.TrimSpace(subject.RenderedMessage) != "" && len(subject.RenderedMessage) <= 2048 && validDigest(subject.RequestDigest)
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func validDigest(value string) bool {
|
||||
decoded, err := hex.DecodeString(value)
|
||||
return err == nil && len(decoded) == 32 && value == strings.ToLower(value)
|
||||
}
|
||||
|
||||
// Execute records UNKNOWN_OUTCOME rather than silently retrying an ambiguous
|
||||
// external mutation.
|
||||
func Execute(action commitcontract.AuthorizedAction, attemptID commitcontract.ActionAttemptID, executor ports.Executor) (commitcontract.ActionAttempt, error) {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
commitcontract "git.cin.su/m/Assistant/contracts/commit"
|
||||
"git.cin.su/m/Assistant/contracts/work"
|
||||
)
|
||||
|
||||
type allowValidator struct{}
|
||||
|
||||
func (allowValidator) Validate(authority.AuthorizationContext) error { return nil }
|
||||
|
||||
func notificationProposal() commitcontract.ActionProposal {
|
||||
return commitcontract.ActionProposal{IntentID: "intent", ActorID: "actor", CapabilityID: commitcontract.CapabilityProspectiveNotification, Target: work.TaskTarget{TaskID: "task", GoalID: "goal", ScopeID: "scope", Revision: 1}, Operation: commitcontract.OperationDeliverProspectiveNotification, NotificationSubject: commitcontract.ProspectiveNotificationSubject{ProspectiveItemID: "item", ExpectedRevision: 1, TemplateCode: commitcontract.ProspectiveDeliveredTemplateV1, BindingID: "binding", BindingRevision: 1, RenderedTitle: "Домовой", RenderedMessage: "Пора вернуться", RequestDigest: strings.Repeat("a", 64)}}
|
||||
}
|
||||
func notificationContext() AuthorizationContext {
|
||||
var context AuthorizationContext
|
||||
context.Binding.ActorID, context.Binding.PrincipalID, context.Binding.Active = "actor", "owner", true
|
||||
context.Scope = authority.Scope{ID: "scope"}
|
||||
context.Grant = authority.AuthorityGrant{ID: "grant", ActorID: "actor", PrincipalID: "owner", ScopeID: "scope", Class: authority.GrantClassCreator, Revision: 1, Active: true}
|
||||
return context
|
||||
}
|
||||
|
||||
func TestAuthorizeProspectiveNotification(t *testing.T) {
|
||||
action, err := Authorize(notificationProposal(), notificationContext(), allowValidator{}, "authorized", 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if action.Proposal.Operation != commitcontract.OperationDeliverProspectiveNotification {
|
||||
t.Fatal("operation changed")
|
||||
}
|
||||
}
|
||||
func TestAuthorizeProspectiveNotificationRejectsInvalidEvidence(t *testing.T) {
|
||||
for name, mutate := range map[string]func(*commitcontract.ActionProposal){"binding": func(p *commitcontract.ActionProposal) { p.NotificationSubject.BindingID = "" }, "digest": func(p *commitcontract.ActionProposal) { p.NotificationSubject.RequestDigest = "AA" }, "message": func(p *commitcontract.ActionProposal) { p.NotificationSubject.RenderedMessage = "" }, "operation": func(p *commitcontract.ActionProposal) { p.Operation = "arbitrary-webhook" }} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
proposal := notificationProposal()
|
||||
mutate(&proposal)
|
||||
if _, err := Authorize(proposal, notificationContext(), allowValidator{}, "authorized", 1); err == nil {
|
||||
t.Fatal("expected denial")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user