merge: t2db.40 sources and signing into pg/foundation
Resolves against t2db.36: captures carry both event_type and unsigned (proto field 10), the State Store serves sources and event types from the Postgres EDA store, the capture row shows event type and signature together, and the staterpc sentinels map both ways from one table.
This commit is contained in:
63 files changed
+3839
-1753
No files matched your search
@@ -254,10 +254,8 @@ func (b *boot) stateStoreDeps(grants *staterpc.TaskGrants) staterpc.Deps {
|
||||
deps.Bindings = b.eda
|
||||
deps.BindingDispatcher = b.eda
|
||||
deps.PlaybookDispatcher = b.eda
|
||||
// Only the Postgres EDA store holds event types.
|
||||
if eventTypes, ok := any(b.eda).(storecontract.EventTypeStore); ok {
|
||||
deps.EventTypes = eventTypes
|
||||
}
|
||||
deps.EventTypes = b.eda
|
||||
deps.Sources = b.eda
|
||||
}
|
||||
// tool_call events project into the tool_calls collection on the same
|
||||
// event-capture store: this process legitimately owns both, so the
|
||||
|
||||
@@ -14,6 +14,8 @@ type eventCaptureStore interface {
|
||||
storecontract.BindingStore
|
||||
storecontract.BindingDispatcher
|
||||
storecontract.PlaybookDispatcher
|
||||
storecontract.EventTypeStore
|
||||
storecontract.SourceStore
|
||||
toolCallWriter
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
pb "github.com/samcharles93/archie-core/internal/contracts/state/v1"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
@@ -147,16 +147,27 @@ func TestStateStoreDepsServePlaybookDispatcher(t *testing.T) {
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
// The playbook ledger moved to the event-capture store with the rest of
|
||||
// the dispatch tables; the task store no longer serves it.
|
||||
eda := edastore.OpenTest(t)
|
||||
// The playbook ledger, sources and event types are served by the
|
||||
// event-capture store; the task store no longer serves them.
|
||||
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("open postgres: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if err := postgres.Migrate(t.Context(), pool, postgres.Migrations()); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
eda := postgres.NewEDA(pool, nil)
|
||||
b.eda = eda
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if deps.PlaybookDispatcher == nil {
|
||||
t.Fatal("stateStoreDeps leaves PlaybookDispatcher nil; the standalone State Store is the only production server for the playbook dispatch ledger")
|
||||
}
|
||||
if deps.PlaybookDispatcher != storecontract.PlaybookDispatcher(eda) {
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened *edastore.Store", deps.PlaybookDispatcher)
|
||||
t.Fatalf("PlaybookDispatcher = %T, want the opened event-capture store", deps.PlaybookDispatcher)
|
||||
}
|
||||
if deps.Sources == nil || deps.EventTypes == nil {
|
||||
t.Fatalf("stateStoreDeps Sources = %v, EventTypes = %v; want both served, or intake verifies nothing and nothing dispatches", deps.Sources, deps.EventTypes)
|
||||
}
|
||||
// A boot without a store must not fabricate one: nil keeps the RPCs honest
|
||||
// as unavailable rather than depending on a nil receiver.
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/pgtest"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/staterpc"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
@@ -173,11 +175,15 @@ func TestInsertEventSucceedsWhenProjectionFails(t *testing.T) {
|
||||
// around a nil writer.
|
||||
func TestStateStoreDepsProjectToolCalls(t *testing.T) {
|
||||
st := store.OpenTest(t)
|
||||
eda := edastore.OpenTest(t)
|
||||
pool, err := postgres.Open(t.Context(), pgtest.URL(t))
|
||||
if err != nil {
|
||||
t.Fatalf("open postgres: %v", err)
|
||||
}
|
||||
defer pool.Close()
|
||||
|
||||
b := newBootstrap()
|
||||
b.st = st
|
||||
b.eda = eda
|
||||
b.eda = postgres.NewEDA(pool, nil)
|
||||
deps := b.stateStoreDeps(&staterpc.TaskGrants{})
|
||||
if _, ok := deps.Tasks.(*toolCallProjectingTaskStore); !ok {
|
||||
t.Fatalf("deps.Tasks = %T, want the tool_call projecting decorator", deps.Tasks)
|
||||
|
||||
@@ -134,21 +134,25 @@ func wireTaskLogs(d deps, srv *webui.Server) {
|
||||
srv.TaskLogs = logs
|
||||
}
|
||||
|
||||
// wireCaptureSurfaces attaches the capture read and the intake receiver.
|
||||
// Both resolve from d.Store's contracts: CaptureStore backs the inspector's
|
||||
// list and the mapping preview's scan window, BindingDispatcher resolves the
|
||||
// armed binding whose secret HMAC-verifies a source. A store that does not
|
||||
// implement one degrades that half with a warning rather than aborting the
|
||||
// process, mirroring the daemon's own adapter selection.
|
||||
// wireCaptureSurfaces attaches the capture read, the source editor and the
|
||||
// intake receiver. All resolve from d.Store's contracts: CaptureStore backs
|
||||
// the inspector's list and the mapping preview's scan window, SourceStore
|
||||
// resolves the source whose signing setting verifies an event. A store that
|
||||
// does not implement one degrades that half with a warning rather than
|
||||
// aborting the process, mirroring the daemon's own adapter selection.
|
||||
func wireCaptureSurfaces(d deps, srv *webui.Server) {
|
||||
captures, hasCaptures := d.Store.(storecontract.CaptureStore)
|
||||
bindings, hasBindings := d.Store.(storecontract.BindingDispatcher)
|
||||
sources, hasSources := d.Store.(storecontract.SourceStore)
|
||||
if !hasCaptures {
|
||||
d.Log.Warn("capture storage unavailable: state store does not implement CaptureStore")
|
||||
return
|
||||
}
|
||||
if !hasBindings {
|
||||
d.Log.Warn("binding dispatcher unavailable: state store does not implement BindingDispatcher")
|
||||
var resolver captureintake.SourceResolver
|
||||
if hasSources {
|
||||
srv.Sources = sources
|
||||
resolver = sources
|
||||
} else {
|
||||
d.Log.Warn("source store unavailable: state store does not implement SourceStore; no capture will dispatch")
|
||||
}
|
||||
|
||||
capture := d.Options.Capture.withDefaults()
|
||||
@@ -157,7 +161,7 @@ func wireCaptureSurfaces(d deps, srv *webui.Server) {
|
||||
srv.CaptureIntake = &captureintake.Receiver{
|
||||
Captures: captures,
|
||||
Limiter: webhookguard.NewRateLimiter(capture.RatePerSecond, capture.RateBurst, time.Now),
|
||||
Bindings: bindings,
|
||||
Sources: resolver,
|
||||
Retention: capture.Retention,
|
||||
MaxEvents: capture.MaxEvents,
|
||||
MaxBodyBytes: int64(capture.MaxBodyBytes),
|
||||
|
||||
+1332
-741
File diff suppressed because it is too large.
Load diff
@@ -83,6 +83,11 @@ const (
|
||||
StateStoreService_UpdateBinding_FullMethodName = "/state.v1.StateStoreService/UpdateBinding"
|
||||
StateStoreService_DeleteBinding_FullMethodName = "/state.v1.StateStoreService/DeleteBinding"
|
||||
StateStoreService_ApproveBinding_FullMethodName = "/state.v1.StateStoreService/ApproveBinding"
|
||||
StateStoreService_InsertSource_FullMethodName = "/state.v1.StateStoreService/InsertSource"
|
||||
StateStoreService_GetSource_FullMethodName = "/state.v1.StateStoreService/GetSource"
|
||||
StateStoreService_ListSources_FullMethodName = "/state.v1.StateStoreService/ListSources"
|
||||
StateStoreService_SetSourceSigning_FullMethodName = "/state.v1.StateStoreService/SetSourceSigning"
|
||||
StateStoreService_SetSourceSecret_FullMethodName = "/state.v1.StateStoreService/SetSourceSecret"
|
||||
StateStoreService_ArmedBindingsForSource_FullMethodName = "/state.v1.StateStoreService/ArmedBindingsForSource"
|
||||
StateStoreService_RecordDispatch_FullMethodName = "/state.v1.StateStoreService/RecordDispatch"
|
||||
StateStoreService_RecordPlaybookDispatch_FullMethodName = "/state.v1.StateStoreService/RecordPlaybookDispatch"
|
||||
@@ -214,6 +219,13 @@ type StateStoreServiceClient interface {
|
||||
UpdateBinding(ctx context.Context, in *UpdateBindingRequest, opts ...grpc.CallOption) (*UpdateBindingResponse, error)
|
||||
DeleteBinding(ctx context.Context, in *DeleteBindingRequest, opts ...grpc.CallOption) (*DeleteBindingResponse, error)
|
||||
ApproveBinding(ctx context.Context, in *ApproveBindingRequest, opts ...grpc.CallOption) (*ApproveBindingResponse, error)
|
||||
// Source (event-automation.md "Sources"): the capture endpoint and its
|
||||
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
|
||||
InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error)
|
||||
GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error)
|
||||
ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error)
|
||||
SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error)
|
||||
SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error)
|
||||
// Dispatch
|
||||
ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error)
|
||||
RecordDispatch(ctx context.Context, in *RecordDispatchRequest, opts ...grpc.CallOption) (*RecordDispatchResponse, error)
|
||||
@@ -899,6 +911,56 @@ func (c *stateStoreServiceClient) ApproveBinding(ctx context.Context, in *Approv
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) InsertSource(ctx context.Context, in *InsertSourceRequest, opts ...grpc.CallOption) (*InsertSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(InsertSourceResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_InsertSource_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) GetSource(ctx context.Context, in *GetSourceRequest, opts ...grpc.CallOption) (*GetSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(GetSourceResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_GetSource_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ListSources(ctx context.Context, in *ListSourcesRequest, opts ...grpc.CallOption) (*ListSourcesResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ListSourcesResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_ListSources_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SetSourceSigning(ctx context.Context, in *SetSourceSigningRequest, opts ...grpc.CallOption) (*SetSourceSigningResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SetSourceSigningResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSigning_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) SetSourceSecret(ctx context.Context, in *SetSourceSecretRequest, opts ...grpc.CallOption) (*SetSourceSecretResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(SetSourceSecretResponse)
|
||||
err := c.cc.Invoke(ctx, StateStoreService_SetSourceSecret_FullMethodName, in, out, cOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (c *stateStoreServiceClient) ArmedBindingsForSource(ctx context.Context, in *ArmedBindingsForSourceRequest, opts ...grpc.CallOption) (*ArmedBindingsForSourceResponse, error) {
|
||||
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
|
||||
out := new(ArmedBindingsForSourceResponse)
|
||||
@@ -1101,6 +1163,13 @@ type StateStoreServiceServer interface {
|
||||
UpdateBinding(context.Context, *UpdateBindingRequest) (*UpdateBindingResponse, error)
|
||||
DeleteBinding(context.Context, *DeleteBindingRequest) (*DeleteBindingResponse, error)
|
||||
ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error)
|
||||
// Source (event-automation.md "Sources"): the capture endpoint and its
|
||||
// signing setting. Secrets travel in plaintext; the store encrypts at rest.
|
||||
InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error)
|
||||
GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error)
|
||||
ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error)
|
||||
SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error)
|
||||
SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error)
|
||||
// Dispatch
|
||||
ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error)
|
||||
RecordDispatch(context.Context, *RecordDispatchRequest) (*RecordDispatchResponse, error)
|
||||
@@ -1319,6 +1388,21 @@ func (UnimplementedStateStoreServiceServer) DeleteBinding(context.Context, *Dele
|
||||
func (UnimplementedStateStoreServiceServer) ApproveBinding(context.Context, *ApproveBindingRequest) (*ApproveBindingResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ApproveBinding not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) InsertSource(context.Context, *InsertSourceRequest) (*InsertSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method InsertSource not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) GetSource(context.Context, *GetSourceRequest) (*GetSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method GetSource not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ListSources(context.Context, *ListSourcesRequest) (*ListSourcesResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ListSources not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SetSourceSigning(context.Context, *SetSourceSigningRequest) (*SetSourceSigningResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetSourceSigning not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) SetSourceSecret(context.Context, *SetSourceSecretRequest) (*SetSourceSecretResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method SetSourceSecret not implemented")
|
||||
}
|
||||
func (UnimplementedStateStoreServiceServer) ArmedBindingsForSource(context.Context, *ArmedBindingsForSourceRequest) (*ArmedBindingsForSourceResponse, error) {
|
||||
return nil, status.Error(codes.Unimplemented, "method ArmedBindingsForSource not implemented")
|
||||
}
|
||||
@@ -2499,6 +2583,96 @@ func _StateStoreService_ApproveBinding_Handler(srv interface{}, ctx context.Cont
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_InsertSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(InsertSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).InsertSource(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_InsertSource_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).InsertSource(ctx, req.(*InsertSourceRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_GetSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(GetSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).GetSource(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_GetSource_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).GetSource(ctx, req.(*GetSourceRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ListSources_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ListSourcesRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).ListSources(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_ListSources_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).ListSources(ctx, req.(*ListSourcesRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SetSourceSigning_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetSourceSigningRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SetSourceSigning_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SetSourceSigning(ctx, req.(*SetSourceSigningRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_SetSourceSecret_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(SetSourceSecretRequest)
|
||||
if err := dec(in); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if interceptor == nil {
|
||||
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, in)
|
||||
}
|
||||
info := &grpc.UnaryServerInfo{
|
||||
Server: srv,
|
||||
FullMethod: StateStoreService_SetSourceSecret_FullMethodName,
|
||||
}
|
||||
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
|
||||
return srv.(StateStoreServiceServer).SetSourceSecret(ctx, req.(*SetSourceSecretRequest))
|
||||
}
|
||||
return interceptor(ctx, in, info, handler)
|
||||
}
|
||||
|
||||
func _StateStoreService_ArmedBindingsForSource_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
|
||||
in := new(ArmedBindingsForSourceRequest)
|
||||
if err := dec(in); err != nil {
|
||||
@@ -2873,6 +3047,26 @@ var StateStoreService_ServiceDesc = grpc.ServiceDesc{
|
||||
MethodName: "ApproveBinding",
|
||||
Handler: _StateStoreService_ApproveBinding_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "InsertSource",
|
||||
Handler: _StateStoreService_InsertSource_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "GetSource",
|
||||
Handler: _StateStoreService_GetSource_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ListSources",
|
||||
Handler: _StateStoreService_ListSources_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetSourceSigning",
|
||||
Handler: _StateStoreService_SetSourceSigning_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "SetSourceSecret",
|
||||
Handler: _StateStoreService_SetSourceSecret_Handler,
|
||||
},
|
||||
{
|
||||
MethodName: "ArmedBindingsForSource",
|
||||
Handler: _StateStoreService_ArmedBindingsForSource_Handler,
|
||||
|
||||
@@ -611,7 +611,7 @@ func (d *Daemon) cleanupExpiredStorage(ctx context.Context) {
|
||||
// single cycle's worst-case latency on a backlog.
|
||||
const bindingDispatchBatchLimit = 100
|
||||
|
||||
// dispatchBindings walks authenticated captures whose source has at
|
||||
// dispatchBindings walks dispatchable captures whose source has at
|
||||
// least one armed binding, evaluates each binding's matcher against
|
||||
// the capture, resolves fields through the binding's mapping, and
|
||||
// enqueues a task per matched (binding, capture) pair.
|
||||
@@ -662,7 +662,7 @@ func (d *Daemon) dispatchBindings(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
for _, b := range armed {
|
||||
if !b.Matcher.Matches(c.Source, c.Authenticated) {
|
||||
if !b.Matcher.Matches(c.Source, c.Dispatchable()) {
|
||||
continue
|
||||
}
|
||||
d.dispatchOneBinding(ctx, b, c)
|
||||
@@ -737,6 +737,16 @@ func (d *Daemon) dispatchOneBinding(ctx context.Context, b binding.Binding, c st
|
||||
d.Log.Warn("binding dispatch: record", "binding", b.ID, "capture", c.ID, "error", err)
|
||||
return
|
||||
}
|
||||
if c.Unsigned {
|
||||
if _, err := d.Store.InsertEvent(ctx, events.Event{
|
||||
TaskID: task.ID,
|
||||
Kind: events.KindUnsignedEvent,
|
||||
Detail: fmt.Sprintf("started by an unsigned event from source %q", c.Source),
|
||||
Data: map[string]any{"source": c.Source, "capture_id": c.ID, "binding_id": b.ID},
|
||||
}); err != nil {
|
||||
d.Log.Warn("binding dispatch: unsigned marker", "task", task.ID, "error", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// hasBlockingFailure reports whether any of the failures belongs to a
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package daemon
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -10,7 +11,9 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/config"
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
@@ -150,6 +153,48 @@ func TestDispatchBindingsSkipsUnauthenticatedCaptures(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// markUnsigned reports every undispatched capture as taken on an approved
|
||||
// unsigned source, which the legacy capture store cannot persist.
|
||||
type markUnsigned struct {
|
||||
storecontract.BindingDispatcher
|
||||
}
|
||||
|
||||
func (m markUnsigned) ListUndispatchedCaptures(ctx context.Context, sources []string, limit int) ([]store.CapturedEvent, error) {
|
||||
cs, err := m.BindingDispatcher.ListUndispatchedCaptures(ctx, sources, limit)
|
||||
for i := range cs {
|
||||
cs[i].Unsigned = true
|
||||
}
|
||||
return cs, err
|
||||
}
|
||||
|
||||
// An event on an approved unsigned source dispatches without a signature,
|
||||
// and the task it starts carries an unsigned_event on its timeline.
|
||||
func TestDispatchBindingsDispatchesUnsignedCaptureAndMarksTimeline(t *testing.T) {
|
||||
s := openDispatchTestStore(t)
|
||||
mappingID := seedMapping(t, s, "fw", mapping.Field{Name: "title", Path: "title", Type: mapping.TypeString})
|
||||
seedArmedBinding(t, s, "fw", mappingID)
|
||||
seedCapture(t, s, "fw", false, `{"title":"blocked"}`)
|
||||
|
||||
d := newDispatchDaemon(t, s)
|
||||
d.BindingDispatcher = markUnsigned{d.BindingDispatcher}
|
||||
d.dispatchBindings(t.Context())
|
||||
|
||||
tasks, err := s.Tasks(t.Context(), 10)
|
||||
if err != nil || len(tasks) != 1 {
|
||||
t.Fatalf("Tasks = %d (err %v), want 1", len(tasks), err)
|
||||
}
|
||||
evs, err := s.TaskEvents(t.Context(), tasks[0].ID)
|
||||
if err != nil {
|
||||
t.Fatalf("TaskEvents: %v", err)
|
||||
}
|
||||
for _, e := range evs {
|
||||
if e.Kind == events.KindUnsignedEvent {
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("task timeline has no %s event: %+v", events.KindUnsignedEvent, evs)
|
||||
}
|
||||
|
||||
// Test 33: a required field whose path is missing in the capture body
|
||||
// blocks the dispatch -- the failure path emits a
|
||||
// binding_dispatch_failure event and creates no task.
|
||||
@@ -305,7 +350,6 @@ func seedArmedBindingWithRepo(t *testing.T, s *dispatchStores, source, mappingID
|
||||
Workflow: "implement",
|
||||
Owner: owner,
|
||||
Repo: repo,
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding: %v", err)
|
||||
|
||||
@@ -38,9 +38,8 @@ type Matcher struct {
|
||||
//
|
||||
// Version is bumped on every UpdateBinding so a later edit cannot
|
||||
// silently rewrite the historical provenance of a task that already
|
||||
// fired. Secret is the HMAC-SHA256 shared secret a sender must sign with
|
||||
// for an event to be marked authenticated; it is never returned by
|
||||
// GET handlers.
|
||||
// fired. Signing belongs to the source the matcher names, not to the
|
||||
// binding (internal/domain/source).
|
||||
type Binding struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
@@ -57,52 +56,15 @@ type Binding struct {
|
||||
Repo string `json:"repo,omitempty"`
|
||||
Version int `json:"version"`
|
||||
Status Status `json:"status"`
|
||||
Secret string `json:"secret,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// minSecretLen is the floor for an acceptable shared secret. A trivially
|
||||
// short secret makes accidental binding to a known HMAC trivial; the
|
||||
// floor is chosen so a one-character typo cannot arm.
|
||||
const minSecretLen = 16
|
||||
|
||||
// Validate checks a binding is well-formed before it is newly persisted.
|
||||
// A non-empty Name, a non-empty Matcher.Source, a positive MappingID, a
|
||||
// non-empty Workflow, and a sufficiently long Secret are all required.
|
||||
// Workflow existence is checked at the API/store layer because the domain
|
||||
// package does not import the workflow registry. Use ValidateForUpdate
|
||||
// instead when editing an existing binding, where an empty Secret is a
|
||||
// meaningful "keep the current one," not a missing value.
|
||||
// Validate checks a binding is well-formed before it is persisted: a
|
||||
// non-empty Name, Matcher.Source, MappingID and Workflow, and a complete
|
||||
// owner/repo pin or none. Workflow existence is checked at the API/store
|
||||
// layer because the domain package does not import the workflow registry.
|
||||
func (b Binding) Validate() error {
|
||||
if err := b.validateCommon(); err != nil {
|
||||
return err
|
||||
}
|
||||
if len(b.Secret) < minSecretLen {
|
||||
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateForUpdate is Validate for the edit path: every other field is
|
||||
// checked identically, but Secret is only length-checked when the caller
|
||||
// actually supplied one. UpdateBinding's own store-layer contract already
|
||||
// treats an empty Secret as "preserve the existing one" (COALESCE against
|
||||
// NULLIF) -- rejecting that here at the validation gate before the store
|
||||
// ever sees it would make the store's own documented behavior
|
||||
// unreachable. A non-empty Secret (a genuine change) is still held to the
|
||||
// same floor Validate enforces.
|
||||
func (b Binding) ValidateForUpdate() error {
|
||||
if err := b.validateCommon(); err != nil {
|
||||
return err
|
||||
}
|
||||
if b.Secret != "" && len(b.Secret) < minSecretLen {
|
||||
return fmt.Errorf("binding: secret must be at least %d bytes", minSecretLen)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b Binding) validateCommon() error {
|
||||
if strings.TrimSpace(b.Name) == "" {
|
||||
return fmt.Errorf("binding: name is required")
|
||||
}
|
||||
@@ -121,18 +83,10 @@ func (b Binding) validateCommon() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Matches reports whether the given captured event would match this
|
||||
// binding's matcher. The Authenticated clause encodes t2db.5 point 1 --
|
||||
// an unauthenticated event can never trigger a binding, no matter how
|
||||
// well it would otherwise match.
|
||||
//
|
||||
// Note: the caller is expected to be the dispatch loop or the capture
|
||||
// intake receiver, both of which receive a CapturedEvent with the
|
||||
// Authenticated flag already set by HMAC verification. Matches is pure
|
||||
// and has no I/O.
|
||||
func (m Matcher) Matches(source string, authenticated bool) bool {
|
||||
if !authenticated {
|
||||
return false
|
||||
}
|
||||
return m.Source == source
|
||||
// Matches reports whether a captured event would trigger this binding. An
|
||||
// event that is not dispatchable (no valid signature, and not from an
|
||||
// approved unsigned source) never matches, however well it would otherwise.
|
||||
// Matches is pure and has no I/O.
|
||||
func (m Matcher) Matches(source string, dispatchable bool) bool {
|
||||
return dispatchable && m.Source == source
|
||||
}
|
||||
@@ -8,7 +8,6 @@ func validBinding() Binding {
|
||||
Matcher: Matcher{Source: "sentry"},
|
||||
MappingID: "m1",
|
||||
Workflow: "implement",
|
||||
Secret: "0123456789abcdef0123456789abcdef",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,47 +32,6 @@ func TestValidateAcceptsBothOwnerAndRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateRejectsPartialRepoPin: Owner and Repo are a pair. A
|
||||
// binding naming only one of them is ambiguous -- it isn't "no pin"
|
||||
// (that's both empty) and it isn't a complete pin, so it must be
|
||||
// rejected at validation time rather than silently guessing which
|
||||
// half was meant.
|
||||
// TestValidateForUpdateAcceptsEmptySecret is the fix for a real bug found
|
||||
// via browser testing (t2db.8): UpdateBinding's own documented contract
|
||||
// treats an empty Secret as "preserve the existing one" (COALESCE against
|
||||
// NULLIF), but the API handler validated with the create-time Validate,
|
||||
// which rejected any edit that didn't retype the full secret -- making
|
||||
// the store's own documented behavior unreachable.
|
||||
func TestValidateForUpdateAcceptsEmptySecret(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = ""
|
||||
if err := b.ValidateForUpdate(); err != nil {
|
||||
t.Fatalf("ValidateForUpdate() = %v, want nil for an empty (preserve-existing) secret", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateForUpdateStillEnforcesLengthOnANewSecret confirms the fix
|
||||
// isn't a blanket bypass: a genuinely-supplied short secret on update is
|
||||
// still rejected, same floor as create.
|
||||
func TestValidateForUpdateStillEnforcesLengthOnANewSecret(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = "short"
|
||||
if err := b.ValidateForUpdate(); err == nil {
|
||||
t.Fatal("ValidateForUpdate() = nil, want error for a too-short (but non-empty) secret")
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidateRejectsEmptySecretOnCreate pins that the fix is scoped to
|
||||
// update only -- Validate (used at create time, where there is no
|
||||
// existing secret to fall back to) still requires a real one.
|
||||
func TestValidateRejectsEmptySecretOnCreate(t *testing.T) {
|
||||
b := validBinding()
|
||||
b.Secret = ""
|
||||
if err := b.Validate(); err == nil {
|
||||
t.Fatal("Validate() = nil, want error for an empty secret at create time")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsPartialRepoPin(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -92,3 +50,21 @@ func TestValidateRejectsPartialRepoPin(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatcherMatchesOnlyDispatchableEventsFromItsSource(t *testing.T) {
|
||||
m := Matcher{Source: "sentry"}
|
||||
tests := []struct {
|
||||
source string
|
||||
dispatchable bool
|
||||
want bool
|
||||
}{
|
||||
{"sentry", true, true},
|
||||
{"sentry", false, false},
|
||||
{"other", true, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := m.Matches(tt.source, tt.dispatchable); got != tt.want {
|
||||
t.Errorf("Matches(%q, %v) = %v, want %v", tt.source, tt.dispatchable, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package source
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// NewPath returns a fresh UUIDv7 path: time-ordered, unguessable, and never
|
||||
// colliding with another source.
|
||||
func NewPath() (string, error) {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("source: generate path: %w", err)
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
// NewSecret returns a fresh 32-byte HMAC secret, hex encoded.
|
||||
func NewSecret() (string, error) {
|
||||
var b [MinSecretLen / 2]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", fmt.Errorf("source: generate secret: %w", err)
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
|
||||
// ValidatePath checks a custom path is URL-safe: RFC 3986 unreserved
|
||||
// characters only, so it needs no escaping, and never a dot segment.
|
||||
func ValidatePath(path string) error {
|
||||
if path == "" || len(path) > MaxPathLen || path == "." || path == ".." {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
for i := range len(path) {
|
||||
if !unreserved(path[i]) {
|
||||
return ErrInvalidPath
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unreserved(c byte) bool {
|
||||
switch {
|
||||
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9':
|
||||
return true
|
||||
}
|
||||
return c == '-' || c == '.' || c == '_' || c == '~'
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Package source owns the capture source: the endpoint one sender posts to,
|
||||
// and its signing setting. See docs/prds/event-automation.md "Sources".
|
||||
package source
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Signing is a source's signing state. A source is signed by default; turning
|
||||
// signing off is requested and then approved, the same two-step gate as
|
||||
// arming a binding, and only the approved state accepts unsigned events.
|
||||
type Signing string
|
||||
|
||||
const (
|
||||
SigningSigned Signing = "signed"
|
||||
SigningUnsignedPending Signing = "unsigned_pending_approval"
|
||||
SigningUnsigned Signing = "unsigned"
|
||||
)
|
||||
|
||||
// MaxPathLen bounds a custom path.
|
||||
const MaxPathLen = 128
|
||||
|
||||
// MinSecretLen is the length of a generated secret: 32 random bytes, hex.
|
||||
const MinSecretLen = 64
|
||||
|
||||
var (
|
||||
// ErrInvalidPath refuses a custom path that is not URL-safe.
|
||||
ErrInvalidPath = errors.New("source: path must be 1-128 URL-safe characters (A-Z a-z 0-9 - . _ ~), not a dot segment")
|
||||
// ErrSigningTransition refuses an approval with no pending request.
|
||||
ErrSigningTransition = errors.New("source: signing transition rejected")
|
||||
)
|
||||
|
||||
// Source is one capture endpoint. Path is its URL segment and its identity:
|
||||
// captures and binding matchers reference it, so it does not change after
|
||||
// creation. Secret is the HMAC key a signed sender signs with.
|
||||
type Source struct {
|
||||
Path string `json:"path"`
|
||||
Signing Signing `json:"signing"`
|
||||
Secret string `json:"secret,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// New builds a signed source with a generated secret. An empty customPath
|
||||
// gets a UUIDv7 path; a non-empty one must be URL-safe. Uniqueness is the
|
||||
// store's to enforce.
|
||||
func New(customPath string) (Source, error) {
|
||||
path := customPath
|
||||
if path == "" {
|
||||
generated, err := NewPath()
|
||||
if err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
path = generated
|
||||
} else if err := ValidatePath(path); err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
secret, err := NewSecret()
|
||||
if err != nil {
|
||||
return Source{}, err
|
||||
}
|
||||
return Source{Path: path, Signing: SigningSigned, Secret: secret}, nil
|
||||
}
|
||||
|
||||
// Unsigned reports whether events on this source dispatch without a
|
||||
// signature. Only an approved request counts.
|
||||
func (s *Source) Unsigned() bool { return s.Signing == SigningUnsigned }
|
||||
|
||||
// RequestUnsigned asks to turn signing off. The source stays signed until
|
||||
// ApproveUnsigned.
|
||||
func (s *Source) RequestUnsigned() error {
|
||||
if s.Signing == SigningSigned {
|
||||
s.Signing = SigningUnsignedPending
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ApproveUnsigned is the only transition that turns signing off.
|
||||
func (s *Source) ApproveUnsigned() error {
|
||||
if s.Signing != SigningUnsignedPending {
|
||||
return ErrSigningTransition
|
||||
}
|
||||
s.Signing = SigningUnsigned
|
||||
return nil
|
||||
}
|
||||
|
||||
// RequireSigning turns signing back on. It needs no approval: it only
|
||||
// narrows what dispatches.
|
||||
func (s *Source) RequireSigning() error {
|
||||
s.Signing = SigningSigned
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
package source
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestNewDefaultsToSignedUUIDv7Path(t *testing.T) {
|
||||
s, err := New("")
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
id, err := uuid.Parse(s.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("path %q is not a UUID: %v", s.Path, err)
|
||||
}
|
||||
if id.Version() != 7 {
|
||||
t.Fatalf("path version = %d, want 7", id.Version())
|
||||
}
|
||||
if s.Signing != SigningSigned {
|
||||
t.Fatalf("signing = %q, want %q", s.Signing, SigningSigned)
|
||||
}
|
||||
if len(s.Secret) < MinSecretLen {
|
||||
t.Fatalf("secret length = %d, want >= %d", len(s.Secret), MinSecretLen)
|
||||
}
|
||||
other, err := New("")
|
||||
if err != nil {
|
||||
t.Fatalf("New() error = %v", err)
|
||||
}
|
||||
if other.Path == s.Path || other.Secret == s.Secret {
|
||||
t.Fatal("two new sources share a path or a secret")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAcceptsOrRefusesCustomPath(t *testing.T) {
|
||||
tests := []struct {
|
||||
path string
|
||||
ok bool
|
||||
}{
|
||||
{"sentry", true},
|
||||
{"fire-wall_01.v2~x", true},
|
||||
{"a/b", false},
|
||||
{"with space", false},
|
||||
{"percent%20", false},
|
||||
{"..", false},
|
||||
{".", false},
|
||||
{strings.Repeat("a", MaxPathLen+1), false},
|
||||
{"ünicode", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.path, func(t *testing.T) {
|
||||
s, err := New(tt.path)
|
||||
if tt.ok {
|
||||
if err != nil || s.Path != tt.path {
|
||||
t.Fatalf("New(%q) = %q, %v; want path kept", tt.path, s.Path, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, ErrInvalidPath) {
|
||||
t.Fatalf("New(%q) error = %v, want ErrInvalidPath", tt.path, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSigningTransitions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
from Signing
|
||||
action func(*Source) error
|
||||
want Signing
|
||||
wantErr bool
|
||||
}{
|
||||
{"request unsigned waits for approval", SigningSigned, (*Source).RequestUnsigned, SigningUnsignedPending, false},
|
||||
{"approve pending", SigningUnsignedPending, (*Source).ApproveUnsigned, SigningUnsigned, false},
|
||||
{"approve without request", SigningSigned, (*Source).ApproveUnsigned, SigningSigned, true},
|
||||
{"approve twice", SigningUnsigned, (*Source).ApproveUnsigned, SigningUnsigned, true},
|
||||
{"resign from unsigned", SigningUnsigned, (*Source).RequireSigning, SigningSigned, false},
|
||||
{"resign from pending", SigningUnsignedPending, (*Source).RequireSigning, SigningSigned, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := Source{Path: "p", Signing: tt.from}
|
||||
err := tt.action(&s)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("err = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if s.Signing != tt.want {
|
||||
t.Fatalf("signing = %q, want %q", s.Signing, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnsignedOnlyOnceApproved(t *testing.T) {
|
||||
for signing, want := range map[Signing]bool{
|
||||
SigningSigned: false,
|
||||
SigningUnsignedPending: false,
|
||||
SigningUnsigned: true,
|
||||
} {
|
||||
if got := (&Source{Signing: signing}).Unsigned(); got != want {
|
||||
t.Errorf("Unsigned() for %q = %v, want %v", signing, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
@@ -205,6 +206,20 @@ type BindingStore interface {
|
||||
ApproveBinding(ctx context.Context, id string) error
|
||||
}
|
||||
|
||||
// SourceStore persists capture sources and their signing setting
|
||||
// (docs/prds/event-automation.md "Sources"). The path is the key and never
|
||||
// changes. Secrets cross this surface in plaintext; the store encrypts them
|
||||
// at rest. Signing transitions are decided by the source domain and written
|
||||
// with an expected-from guard, so two operators cannot race an approval.
|
||||
type SourceStore interface {
|
||||
InsertSource(ctx context.Context, s source.Source) error
|
||||
// GetSource returns (nil, nil) for an unknown path.
|
||||
GetSource(ctx context.Context, path string) (*source.Source, error)
|
||||
ListSources(ctx context.Context) ([]source.Source, error)
|
||||
SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error
|
||||
SetSourceSecret(ctx context.Context, path, secret string) error
|
||||
}
|
||||
|
||||
// BindingDispatcher is the dispatch-loop surface over the bindings store:
|
||||
// look up armed bindings for HMAC verification, list captures that still
|
||||
// need dispatching, and record the at-most-once ledger row. The
|
||||
@@ -288,8 +303,15 @@ type CapturedEvent struct {
|
||||
// when it arrived, or empty when it matched none. An unidentified capture
|
||||
// is never dispatched.
|
||||
EventType string `json:"event_type"`
|
||||
// Unsigned marks an event that arrived on an approved unsigned source.
|
||||
// It dispatches without Authenticated and is flagged wherever it shows.
|
||||
Unsigned bool `json:"unsigned"`
|
||||
}
|
||||
|
||||
// Dispatchable reports whether a binding may start a task from this event:
|
||||
// a valid signature, or a source approved to take unsigned events.
|
||||
func (c CapturedEvent) Dispatchable() bool { return c.Authenticated || c.Unsigned }
|
||||
|
||||
// ConfigSnapshot is the running configuration as the dashboard renders it,
|
||||
// published by whoever owns configuration for whoever displays it.
|
||||
//
|
||||
@@ -389,6 +411,13 @@ var (
|
||||
ErrMappingNotFound = errors.New("store: mapping not found")
|
||||
// ErrEventTypeNotFound is returned when an event type ID does not exist.
|
||||
ErrEventTypeNotFound = errors.New("store: event type not found")
|
||||
// ErrSourceNotFound is returned when a source path does not exist.
|
||||
ErrSourceNotFound = errors.New("store: source not found")
|
||||
// ErrSourcePathTaken is returned when a new source's path is in use.
|
||||
ErrSourcePathTaken = errors.New("store: source path already taken")
|
||||
// ErrSourceSigningStale is returned when a signing write's expected
|
||||
// from state does not match the stored one.
|
||||
ErrSourceSigningStale = errors.New("store: source signing does not match expected state")
|
||||
|
||||
// ErrResourceNotFound is returned when a control-plane resource kind has
|
||||
// no stored document. It is in-process only (not on the gRPC wire): the
|
||||
|
||||
@@ -114,6 +114,11 @@ const (
|
||||
KindBindingChanged = "binding_changed"
|
||||
KindMappingChanged = "mapping_changed"
|
||||
|
||||
// KindUnsignedEvent marks a task started by an event from an approved
|
||||
// unsigned source, so its timeline shows that nothing authenticated
|
||||
// the sender. data: source, capture_id, binding_id.
|
||||
KindUnsignedEvent = "unsigned_event"
|
||||
|
||||
// KindUpdateReport carries the phase-2 outcome of a dashboard-initiated
|
||||
// update -- whether the restarted daemon came back up healthy and on
|
||||
// the version it claimed, relayed once on the boot that finds the
|
||||
|
||||
@@ -15,14 +15,13 @@ package captureintake
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/webhookguard"
|
||||
@@ -42,10 +41,10 @@ type Receiver struct {
|
||||
// is read. Nil disables rate limiting, which composition never does in
|
||||
// production.
|
||||
Limiter *webhookguard.RateLimiter
|
||||
// Bindings resolves the armed binding whose secret authenticates a
|
||||
// source. Nil disables per-source HMAC verification and every event
|
||||
// records as authenticated=false.
|
||||
Bindings storecontract.BindingDispatcher
|
||||
// Sources resolves the source a path names and its signing setting.
|
||||
// Nil disables verification: every event records as neither
|
||||
// authenticated nor unsigned, so none dispatches.
|
||||
Sources SourceResolver
|
||||
// Retention and MaxEvents are passed straight to InsertCapture's
|
||||
// prune-on-write bounds. See config.CaptureConfig.
|
||||
Retention time.Duration
|
||||
@@ -61,23 +60,28 @@ type Receiver struct {
|
||||
Log *slog.Logger
|
||||
}
|
||||
|
||||
// SourceResolver is the one SourceStore read intake needs.
|
||||
type SourceResolver interface {
|
||||
GetSource(ctx context.Context, path string) (*source.Source, error)
|
||||
}
|
||||
|
||||
// Register mounts the receiver on mux.
|
||||
func (rc *Receiver) Register(mux *http.ServeMux) {
|
||||
mux.HandleFunc(Path, rc.ServeHTTP)
|
||||
}
|
||||
|
||||
// ServeHTTP accepts an inbound webhook POST and persists it. If a binding is
|
||||
// armed for this source the body must also carry a valid HMAC signature; only
|
||||
// correctly-signed events are recorded as authenticated (t2db.5 point 1). An
|
||||
// unauthenticated event is still captured, visible in the inspector, and
|
||||
// marked unauthenticated -- the dispatch loop's auth check
|
||||
// (binding.Matcher.Matches) is the actual gate against false task creation.
|
||||
// ServeHTTP accepts an inbound webhook POST and persists it. On a signed
|
||||
// source only a valid HMAC under the source's secret marks the event
|
||||
// authenticated; on an approved unsigned source every event is marked
|
||||
// unsigned. Anything else is still captured and visible in the inspector,
|
||||
// but is neither, so the dispatch loop's check (binding.Matcher.Matches over
|
||||
// CapturedEvent.Dispatchable) never starts a task from it.
|
||||
func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if rc.Captures == nil {
|
||||
http.Error(w, "capture not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
source := r.PathValue("source")
|
||||
path := r.PathValue("source")
|
||||
|
||||
// webhookguard.RateLimiter's bucket map assumes a bounded, operator-
|
||||
// registered key space (see its doc comment) -- it is never evicted, and
|
||||
@@ -92,10 +96,7 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
armed, ok := rc.armedBindings(w, r, source)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
src := rc.resolveSource(r, path)
|
||||
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytesOrFallback(rc.MaxBodyBytes))
|
||||
body, err := io.ReadAll(r.Body)
|
||||
@@ -106,20 +107,8 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// HMAC verification -- only when exactly one binding is armed for this
|
||||
// source. Mirrors channels/webhook/webhook.go's header precedence:
|
||||
// GitHub-style X-Hub-Signature-256 first, X-Signature-256 fallback.
|
||||
// Empty header + non-empty secret is never valid (VerifyHMAC's own
|
||||
// guard), so an absent signature with an armed binding lands here as
|
||||
// authenticated=false rather than authenticated=true.
|
||||
authenticated := false
|
||||
if len(armed) == 1 {
|
||||
sig := r.Header.Get("X-Hub-Signature-256")
|
||||
if sig == "" {
|
||||
sig = r.Header.Get("X-Signature-256")
|
||||
}
|
||||
authenticated = webhookguard.VerifyHMAC(body, sig, armed[0].Secret)
|
||||
}
|
||||
// Verified on the raw bytes, before redaction parses them.
|
||||
authenticated, unsigned := verify(src, r.Header, body)
|
||||
|
||||
headers, _ := json.Marshal(r.Header)
|
||||
redactedHeaders, err := webhookguard.RedactPayload(headers)
|
||||
@@ -137,16 +126,17 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
c := storecontract.CapturedEvent{
|
||||
ReceivedAt: time.Now().UTC(),
|
||||
Source: source,
|
||||
Source: path,
|
||||
RemoteAddr: r.RemoteAddr,
|
||||
ContentType: r.Header.Get("Content-Type"),
|
||||
Headers: string(redactedHeaders),
|
||||
Body: string(redactedBody),
|
||||
Authenticated: authenticated,
|
||||
Unsigned: unsigned,
|
||||
}
|
||||
id, err := rc.Captures.InsertCapture(r.Context(), c, rc.Retention, rc.MaxEvents)
|
||||
if err != nil {
|
||||
rc.logger().Error("capture insert", "err", err, "source", source)
|
||||
rc.logger().Error("capture insert", "err", err, "source", path)
|
||||
http.Error(w, "capture failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
@@ -161,42 +151,49 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if rc.Publish != nil {
|
||||
rc.Publish(r.Context(), events.Event{
|
||||
Kind: "capture",
|
||||
Detail: "capture from " + source,
|
||||
Data: map[string]any{"id": id, "source": source},
|
||||
Detail: "capture from " + path,
|
||||
Data: map[string]any{"id": id, "source": path, "unsigned": unsigned},
|
||||
})
|
||||
}
|
||||
|
||||
w.WriteHeader(http.StatusAccepted)
|
||||
}
|
||||
|
||||
// armedBindings resolves the bindings armed for source before the body is
|
||||
// read. A lookup error is logged and treated as "no armed binding" -- the
|
||||
// dispatch loop's auth check is the actual gate, so failing closed here would
|
||||
// amplify a transient store hiccup into a capture outage for every
|
||||
// sender-not-yet-bound flow. If a future phase wants fail-closed semantics,
|
||||
// that is a separate decision and should not silently land here.
|
||||
//
|
||||
// Two armed bindings for one source would race over every inbound webhook for
|
||||
// that source: the write-time overlap check should make this state
|
||||
// impossible, but the dispatch loop needs a single binding per capture, so
|
||||
// the overlap surfaces as 409 at capture time (belt-and-braces TOCTOU guard
|
||||
// -- see the store's ApproveBinding).
|
||||
func (rc *Receiver) armedBindings(w http.ResponseWriter, r *http.Request, source string) ([]binding.Binding, bool) {
|
||||
if rc.Bindings == nil {
|
||||
return nil, true
|
||||
// resolveSource looks up the source a path names. A lookup error is logged
|
||||
// and treated as an unknown source: the event is still captured but cannot
|
||||
// dispatch, so failing open here costs no safety, while failing closed would
|
||||
// turn a transient store hiccup into a capture outage.
|
||||
func (rc *Receiver) resolveSource(r *http.Request, path string) *source.Source {
|
||||
if rc.Sources == nil {
|
||||
return nil
|
||||
}
|
||||
armed, err := rc.Bindings.ArmedBindingsForSource(r.Context(), source)
|
||||
src, err := rc.Sources.GetSource(r.Context(), path)
|
||||
if err != nil {
|
||||
rc.logger().Warn("armed bindings lookup", "source", source, "err", err)
|
||||
return nil, true
|
||||
rc.logger().Warn("source lookup", "source", path, "err", err)
|
||||
return nil
|
||||
}
|
||||
if len(armed) > 1 {
|
||||
http.Error(w,
|
||||
fmt.Sprintf("multiple armed bindings for source %q -- overlap rejected", source),
|
||||
http.StatusConflict)
|
||||
return nil, false
|
||||
return src
|
||||
}
|
||||
|
||||
// verify decides how an event on src may dispatch. An approved unsigned
|
||||
// source marks it unsigned. Otherwise a valid HMAC under the source's secret
|
||||
// authenticates it: X-Hub-Signature-256 first, X-Signature-256 as fallback.
|
||||
// A source with no secret yet authenticates nothing, since an empty key is
|
||||
// one anybody can sign with.
|
||||
func verify(src *source.Source, h http.Header, body []byte) (authenticated, unsigned bool) {
|
||||
switch {
|
||||
case src == nil:
|
||||
return false, false
|
||||
case src.Unsigned():
|
||||
return false, true
|
||||
case src.Secret == "":
|
||||
return false, false
|
||||
}
|
||||
return armed, true
|
||||
sig := h.Get("X-Hub-Signature-256")
|
||||
if sig == "" {
|
||||
sig = h.Get("X-Signature-256")
|
||||
}
|
||||
return webhookguard.VerifyHMAC(body, sig, src.Secret), false
|
||||
}
|
||||
|
||||
func (rc *Receiver) logger() *slog.Logger {
|
||||
|
||||
@@ -13,7 +13,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
@@ -74,92 +74,6 @@ func captureTestServer(t *testing.T) testReceiver {
|
||||
}
|
||||
}
|
||||
|
||||
// stubBindingStore injects a configurable armed-binding lookup result so
|
||||
// handleCapture tests can exercise the single-binding HMAC path and the
|
||||
// belt-and-braces 409-on-multiple path without seeding the real store
|
||||
// (which would either run into the overlap-rejection guard or require
|
||||
// bypassing the draft -> pending_approval -> armed lifecycle). The 409
|
||||
// path exists exactly for the case where the write-time check was
|
||||
// bypassed somehow, so simulating that case directly is the most honest
|
||||
// way to cover it.
|
||||
type stubBindingStore struct {
|
||||
armedBySource map[string][]binding.Binding
|
||||
lookupErr error
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ArmedBindingsForSource(_ context.Context, source string) ([]binding.Binding, error) {
|
||||
if s.lookupErr != nil {
|
||||
return nil, s.lookupErr
|
||||
}
|
||||
return s.armedBySource[source], nil
|
||||
}
|
||||
|
||||
// handleCapture only touches ArmedBindingsForSource on the binding
|
||||
// surface. The rest of BindingStore is stubbed so the type satisfies the
|
||||
// interface and Phase C's other handlers can be exercised elsewhere.
|
||||
func (s *stubBindingStore) InsertBinding(_ context.Context, _ binding.Binding) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) GetBinding(_ context.Context, _ int64) (*binding.Binding, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ListBindings(_ context.Context) ([]binding.Binding, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) UpdateBinding(_ context.Context, _ binding.Binding) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) DeleteBinding(_ context.Context, _ int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ApproveBinding(_ context.Context, _ int64) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) RecordDispatch(
|
||||
_ context.Context,
|
||||
_ string,
|
||||
_ int64,
|
||||
_ string,
|
||||
_ int64,
|
||||
) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stubBindingStore) ListUndispatchedCaptures(_ context.Context, _ []string, _ int) ([]store.CapturedEvent, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// captureBindingServer builds a Server with both a real CaptureStore (so
|
||||
// ListCaptures can read back what handleCapture persisted) and a stub
|
||||
// BindingDispatcher configured with one armed binding for the given
|
||||
// source. The mapping/workflow fields are placeholders -- handleCapture
|
||||
// never reads them, only the Secret.
|
||||
func captureBindingServer(t *testing.T, secret, source string) testReceiver {
|
||||
t.Helper()
|
||||
srv := captureTestServer(t)
|
||||
srv.Bindings = &stubBindingStore{
|
||||
armedBySource: map[string][]binding.Binding{
|
||||
source: {{
|
||||
ID: "rbind0000000001",
|
||||
Name: "test",
|
||||
Matcher: binding.Matcher{Source: source},
|
||||
MappingID: "rmap00000000001",
|
||||
Workflow: "implement",
|
||||
Version: 1,
|
||||
Status: binding.StatusArmed,
|
||||
Secret: secret,
|
||||
}},
|
||||
},
|
||||
}
|
||||
return srv
|
||||
}
|
||||
|
||||
// hmacSHA256 returns the GitHub-style "sha256=<hex>" signature for body
|
||||
// under secret, the same form webhookguard.VerifyHMAC accepts.
|
||||
func hmacSHA256(secret, body string) string {
|
||||
@@ -440,230 +354,99 @@ func TestHandleCaptureStorageFailureIs500(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureMarksAuthenticatedWhenHMACMatches is the green half of
|
||||
// the t2db.5 point 1 wiring: a capture POST signed with the armed
|
||||
// binding's secret must be recorded with Authenticated=true so the
|
||||
// dispatch loop's binding.Matcher.Matches check (which gates on
|
||||
// authenticated) can fire.
|
||||
func TestHandleCaptureMarksAuthenticatedWhenHMACMatches(t *testing.T) {
|
||||
const secret = "abcdefghijklmnop" // exactly 16 bytes (binding.Validate floor)
|
||||
srv := captureBindingServer(t, secret, "github")
|
||||
body := `{"action":"opened"}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-Hub-Signature-256", hmacSHA256(secret, body))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusAccepted, w.Body.String())
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(got))
|
||||
}
|
||||
if !got[0].Authenticated {
|
||||
t.Errorf("Authenticated = false, want true (signature matched armed binding's secret)")
|
||||
}
|
||||
// stubSources resolves a fixed set of sources, or fails every lookup.
|
||||
type stubSources struct {
|
||||
byPath map[string]source.Source
|
||||
err error
|
||||
}
|
||||
|
||||
// TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches covers the
|
||||
// negative side of the HMAC verification: a body signed with the WRONG
|
||||
// secret is still captured (per t2db.5 point 1 -- captures must remain
|
||||
// inspectable even when auth fails) but flagged as unauthenticated so
|
||||
// the dispatch loop's auth gate can drop it.
|
||||
func TestHandleCaptureMarksUnauthenticatedWhenHMACMismatches(t *testing.T) {
|
||||
func (s stubSources) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
if s.err != nil {
|
||||
return nil, s.err
|
||||
}
|
||||
src, ok := s.byPath[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &src, nil
|
||||
}
|
||||
|
||||
// memCaptures records inserted captures, including the Unsigned flag the
|
||||
// legacy store does not persist.
|
||||
type memCaptures struct{ rows []store.CapturedEvent }
|
||||
|
||||
func (m *memCaptures) InsertCapture(_ context.Context, c store.CapturedEvent, _ time.Duration, _ int) (string, error) {
|
||||
m.rows = append(m.rows, c)
|
||||
return "c", nil
|
||||
}
|
||||
|
||||
func (m *memCaptures) ListCaptures(context.Context, int) ([]store.CapturedEvent, error) {
|
||||
return m.rows, nil
|
||||
}
|
||||
|
||||
// TestHandleCaptureSigning pins the source signing rule: a signed source
|
||||
// authenticates only a valid X-Hub-Signature-256 or X-Signature-256 HMAC
|
||||
// under its secret; an approved unsigned source marks every event unsigned;
|
||||
// anything else is captured and neither authenticated nor unsigned, so it
|
||||
// never dispatches.
|
||||
func TestHandleCaptureSigning(t *testing.T) {
|
||||
const secret = "abcdefghijklmnop"
|
||||
srv := captureBindingServer(t, secret, "github")
|
||||
body := `{"action":"opened"}`
|
||||
wrong := hmacSHA256("not-the-real-secret-aaaaaaaaa", body)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
req.Header.Set("X-Hub-Signature-256", wrong)
|
||||
w := httptest.NewRecorder()
|
||||
const body = `{"action":"opened"}`
|
||||
signed := source.Source{Path: "github", Signing: source.SigningSigned, Secret: secret}
|
||||
pending := source.Source{Path: "github", Signing: source.SigningUnsignedPending, Secret: secret}
|
||||
unsigned := source.Source{Path: "github", Signing: source.SigningUnsigned, Secret: secret}
|
||||
noSecret := source.Source{Path: "github", Signing: source.SigningSigned}
|
||||
tests := []struct {
|
||||
name string
|
||||
sources SourceResolver
|
||||
header, sig string
|
||||
authenticated bool
|
||||
unsigned bool
|
||||
}{
|
||||
{"signed, valid hub signature", sources(signed), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"signed, valid fallback signature", sources(signed), "X-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"signed, wrong signature", sources(signed), "X-Hub-Signature-256", hmacSHA256("not-the-real-secret", body), false, false},
|
||||
{"signed, no signature", sources(signed), "", "", false, false},
|
||||
{"signed, no secret yet", sources(noSecret), "X-Hub-Signature-256", hmacSHA256("", body), false, false},
|
||||
{"unsigned request not yet approved", sources(pending), "", "", false, false},
|
||||
{"unsigned request not yet approved, signed event", sources(pending), "X-Hub-Signature-256", hmacSHA256(secret, body), true, false},
|
||||
{"approved unsigned", sources(unsigned), "", "", false, true},
|
||||
{"unknown source", sources(), "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
|
||||
{"lookup error fails open at capture", stubSources{err: errors.New("db locked")}, "", "", false, false},
|
||||
{"no source store", nil, "X-Hub-Signature-256", hmacSHA256(secret, body), false, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
captures := &memCaptures{}
|
||||
rc := &Receiver{Log: slog.New(slog.DiscardHandler), Captures: captures, Sources: tt.sources}
|
||||
mux := http.NewServeMux()
|
||||
rc.Register(mux)
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
if tt.header != "" {
|
||||
req.Header.Set(tt.header, tt.sig)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
mux.ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d (a mismatched signature must still produce a capture, not reject the request)", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(got))
|
||||
}
|
||||
if got[0].Authenticated {
|
||||
t.Errorf("Authenticated = true, want false (signature did not match armed binding's secret)")
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
if len(captures.rows) != 1 {
|
||||
t.Fatalf("captured rows = %d, want 1", len(captures.rows))
|
||||
}
|
||||
got := captures.rows[0]
|
||||
if got.Authenticated != tt.authenticated || got.Unsigned != tt.unsigned {
|
||||
t.Fatalf("authenticated, unsigned = %v, %v; want %v, %v", got.Authenticated, got.Unsigned, tt.authenticated, tt.unsigned)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureWithNoSignatureMarksUnauthenticated covers the
|
||||
// "sender forgot the header" case: the binding is armed, the secret is
|
||||
// registered, but the request carries no signature at all. The handler
|
||||
// must fall through to authenticated=false (the empty-signature guard
|
||||
// in webhookguard.VerifyHMAC). Captures are still recorded -- the
|
||||
// operator can see the unsigned attempt in the inspector.
|
||||
func TestHandleCaptureWithNoSignatureMarksUnauthenticated(t *testing.T) {
|
||||
const secret = "abcdefghijklmnop"
|
||||
srv := captureBindingServer(t, secret, "github")
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
// Deliberately no X-Hub-Signature-256 / X-Signature-256 header.
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Authenticated {
|
||||
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureWithMultipleArmedBindingsReturns409 covers the
|
||||
// belt-and-braces TOCTOU guard: two armed bindings for the same source
|
||||
// would race over every inbound webhook for that source, so the
|
||||
// capture-time handler returns 409 Conflict instead of silently picking
|
||||
// a winner. The store's overlap check should make this impossible in
|
||||
// practice; the 409 is the safety net. The stub injects the state
|
||||
// directly to exercise that safety net.
|
||||
func TestHandleCaptureWithMultipleArmedBindingsReturns409(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Bindings = &stubBindingStore{
|
||||
armedBySource: map[string][]binding.Binding{
|
||||
"github": {
|
||||
{ID: "rbind0000000001", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "abcdefghijklmnop"},
|
||||
{ID: "rbind0000000002", Matcher: binding.Matcher{Source: "github"}, Status: binding.StatusArmed, Secret: "qrstuvwxyz123456"},
|
||||
},
|
||||
},
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d (multiple armed bindings must surface as 409 at capture time)", w.Code, http.StatusConflict)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 0 {
|
||||
t.Fatalf("captured rows = %d, want 0 (a 409 must never persist a row)", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureAcceptsWhenNoArmedBindingExists documents the
|
||||
// "source has never been bound" path: Bindings is wired but
|
||||
// ArmedBindingsForSource returns an empty slice. The handler must
|
||||
// still capture, with authenticated=false -- there is no armed binding
|
||||
// to check against, so HMAC is meaningless, but the event itself is
|
||||
// still worth recording for the inspector.
|
||||
func TestHandleCaptureAcceptsWhenNoArmedBindingExists(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Bindings = &stubBindingStore{armedBySource: map[string][]binding.Binding{}}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Authenticated {
|
||||
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureAcceptsWithBindingsNil pins the legacy backwards-
|
||||
// compatibility behaviour: Bindings is nil (composition never wired the
|
||||
// binding surface, or the dashboard is running without the feature).
|
||||
// handleCapture must behave as it did before this phase landed -- still
|
||||
// capture, still record authenticated=false.
|
||||
func TestHandleCaptureAcceptsWithBindingsNil(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
if srv.Bindings != nil {
|
||||
t.Fatalf("captureTestServer must not wire Bindings by default for this test")
|
||||
}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Authenticated {
|
||||
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture pins the
|
||||
// documented fail-open posture: if ArmedBindingsForSource errors, the
|
||||
// capture still goes through (the dispatch loop's auth check is the
|
||||
// actual gate). A transient store hiccup must not amplify into a
|
||||
// capture outage for sends-that-haven't-been-bound-yet.
|
||||
func TestHandleCaptureBindingsLookupErrorFailsOpenAtCapture(t *testing.T) {
|
||||
srv := captureTestServer(t)
|
||||
srv.Bindings = &stubBindingStore{lookupErr: errors.New("db locked")}
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(`{}`))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d (a transient lookup error must not fail closed at capture)", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || got[0].Authenticated {
|
||||
t.Fatalf("captured = %+v, want 1 row with Authenticated=false", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleCaptureAcceptsXSignature256FallbackHeader pins the second
|
||||
// header in the precedence list: when X-Hub-Signature-256 is absent but
|
||||
// X-Signature-256 is present, the fallback is honoured. Mirrors
|
||||
// channels/webhook/webhook.go's header precedence.
|
||||
func TestHandleCaptureAcceptsXSignature256FallbackHeader(t *testing.T) {
|
||||
const secret = "abcdefghijklmnop"
|
||||
srv := captureBindingServer(t, secret, "github")
|
||||
body := `{"action":"opened"}`
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhooks/capture/github", strings.NewReader(body))
|
||||
// No X-Hub-Signature-256; signature is in X-Signature-256 only.
|
||||
req.Header.Set("X-Signature-256", hmacSHA256(secret, body))
|
||||
w := httptest.NewRecorder()
|
||||
|
||||
srv.Handler().ServeHTTP(w, req)
|
||||
|
||||
if w.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want %d", w.Code, http.StatusAccepted)
|
||||
}
|
||||
got, err := srv.store.ListCaptures(t.Context(), 10)
|
||||
if err != nil {
|
||||
t.Fatalf("ListCaptures: %v", err)
|
||||
}
|
||||
if len(got) != 1 || !got[0].Authenticated {
|
||||
t.Fatalf("captured = %+v, want 1 row with Authenticated=true (X-Signature-256 fallback must work)", got)
|
||||
func sources(list ...source.Source) stubSources {
|
||||
byPath := map[string]source.Source{}
|
||||
for _, s := range list {
|
||||
byPath[s.Path] = s
|
||||
}
|
||||
return stubSources{byPath: byPath}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ package edastore
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
@@ -122,111 +121,6 @@ func TestBindingCipherDerivesDistinctKeys(t *testing.T) {
|
||||
}
|
||||
|
||||
// openWithCipher builds a store whose binding secrets are encrypted at rest.
|
||||
func openWithCipher(t *testing.T, cipher BindingCipher) *Store {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
s, err := Open(Config{
|
||||
DBPath: filepath.Join(dir, "eda.sqlite"),
|
||||
DataDir: filepath.Join(dir, "pb_data"),
|
||||
Cipher: cipher,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Open() error = %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func sampleBinding() bindingInput {
|
||||
return bindingInput{Name: "n", Source: "sentry", Workflow: "implement", Secret: "supersecretvalue0123"}
|
||||
}
|
||||
|
||||
// TestBindingSecretIsEncryptedAtRest pins that the plaintext secret never
|
||||
// reaches the database file. Reading the column directly is the point: a
|
||||
// round-trip through the store would decrypt and prove nothing.
|
||||
func TestBindingSecretIsEncryptedAtRest(t *testing.T) {
|
||||
cipher, err := NewBindingCipher(testBindingKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored == in.Secret {
|
||||
t.Fatal("secret is stored as plaintext; it must be encrypted at rest")
|
||||
}
|
||||
if !strings.Contains(stored, ":") {
|
||||
t.Errorf("stored secret %q does not look like a cipher envelope", stored)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBindingSecretDecryptsOnRead pins the other half: what was encrypted
|
||||
// comes back as the original plaintext.
|
||||
func TestBindingSecretDecryptsOnRead(t *testing.T) {
|
||||
cipher, _ := NewBindingCipher(testBindingKey, nil)
|
||||
s := openWithCipher(t, cipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret = %q, want %q", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNoCipherKeepsPlaintext pins the behaviour that predates encryption: a
|
||||
// deployment with no configured key still works, storing plaintext.
|
||||
func TestNoCipherKeepsPlaintext(t *testing.T) {
|
||||
s := openWithCipher(t, nil)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
var stored string
|
||||
if err := s.App().DB().NewQuery("SELECT secret FROM " + CollBindings + " WHERE id = {:id}").
|
||||
Bind(map[string]any{"id": id}).Row(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
if stored != in.Secret {
|
||||
t.Errorf("stored secret = %q, want the plaintext %q with no cipher configured", stored, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRotatedKeyStillReadsOldRows pins key rotation: a secret written under
|
||||
// the previous key must stay readable once a new active key is installed,
|
||||
// otherwise a rotation silently bricks every armed binding.
|
||||
func TestRotatedKeyStillReadsOldRows(t *testing.T) {
|
||||
const oldKey = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210"
|
||||
oldCipher, _ := NewBindingCipher(oldKey, nil)
|
||||
s := openWithCipher(t, oldCipher)
|
||||
in := sampleBinding()
|
||||
id := insertBinding(t, s, in)
|
||||
|
||||
rotated, err := NewBindingCipher(testBindingKey, []string{oldKey})
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher(rotated) error = %v", err)
|
||||
}
|
||||
s.cipher = rotated
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() after rotation error = %v", err)
|
||||
}
|
||||
if got.Secret != in.Secret {
|
||||
t.Errorf("Secret after rotation = %q, want %q: the previous key must still decrypt", got.Secret, in.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// tamperEnvelope flips one byte inside the ciphertext region so Decrypt must
|
||||
// fail authentication rather than return altered plaintext.
|
||||
func tamperEnvelope(t *testing.T, envelope string) string {
|
||||
t.Helper()
|
||||
parts := strings.SplitN(envelope, ":", 4)
|
||||
|
||||
@@ -133,17 +133,9 @@ func (s *Store) bindingValue(r *core.Record) (binding.Binding, error) {
|
||||
Repo: r.GetString("repo"),
|
||||
Version: r.GetInt("version"),
|
||||
Status: binding.Status(r.GetString("status")),
|
||||
Secret: r.GetString("secret"),
|
||||
CreatedAt: r.GetDateTime("created_at").Time(),
|
||||
UpdatedAt: r.GetDateTime("updated_at").Time(),
|
||||
}
|
||||
if s.cipher != nil && b.Secret != "" {
|
||||
plain, err := s.cipher.Decrypt(b.Secret)
|
||||
if err != nil {
|
||||
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
|
||||
}
|
||||
b.Secret = plain
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
@@ -154,20 +146,6 @@ func (s *Store) applyBinding(r *core.Record, b binding.Binding) error {
|
||||
r.Set("workflow", b.Workflow)
|
||||
r.Set("owner", b.Owner)
|
||||
r.Set("repo", b.Repo)
|
||||
// An empty secret means "keep the stored one". An edit form that does not
|
||||
// echo the secret back must not silently disarm the binding by erasing it.
|
||||
if b.Secret == "" {
|
||||
return nil
|
||||
}
|
||||
secret := b.Secret
|
||||
if s.cipher != nil {
|
||||
encrypted, err := s.cipher.Encrypt(secret)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: encrypt binding secret: %w", err)
|
||||
}
|
||||
secret = encrypted
|
||||
}
|
||||
r.Set("secret", secret)
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ type bindingInput struct {
|
||||
Name string
|
||||
Source string
|
||||
Workflow string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func insertBinding(t *testing.T, s *Store, in bindingInput) string {
|
||||
@@ -21,7 +20,6 @@ func insertBinding(t *testing.T, s *Store, in bindingInput) string {
|
||||
Name: in.Name,
|
||||
Matcher: binding.Matcher{Source: in.Source},
|
||||
Workflow: in.Workflow,
|
||||
Secret: in.Secret,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
|
||||
@@ -284,6 +284,13 @@ func importInto(ctx context.Context, tx pgx.Tx, present []domain, sources map[st
|
||||
return Report{}, err
|
||||
}
|
||||
}
|
||||
// Sources are derived, not imported: the migration derived them from an
|
||||
// empty target, so derive again from what was just loaded.
|
||||
if sources["eda"] != nil {
|
||||
if err := postgresdb.New(tx).DeriveSources(ctx); err != nil {
|
||||
return Report{}, fmt.Errorf("legacy import: derive sources: %w", err)
|
||||
}
|
||||
}
|
||||
if gw := sources["gateway"]; gw != nil {
|
||||
var err error
|
||||
if report.UnindexedMessages, err = unindexedMessages(ctx, gw, loaded); err != nil {
|
||||
|
||||
@@ -281,7 +281,7 @@ func TestImportCopiesEverySourceAndLeavesThemUntouched(t *testing.T) {
|
||||
}{
|
||||
{"SELECT review_cursor FROM tasks WHERE id = 1", &reviewCursor},
|
||||
{"SELECT value FROM resource_history WHERE id = 1", &value},
|
||||
{"SELECT secret FROM bindings WHERE id = 'rbind1'", &gotSecret},
|
||||
{"SELECT secret FROM sources WHERE path = 'gh'", &gotSecret},
|
||||
{"SELECT headers FROM captures WHERE id = 'rcap2'", &headers},
|
||||
{"SELECT result FROM tool_calls WHERE id = 'rtool1'", &result},
|
||||
{"SELECT configured FROM channel_status WHERE id = 'tg'", &configured},
|
||||
|
||||
@@ -24,10 +24,12 @@ var droppedColumns = map[string]bool{
|
||||
}
|
||||
|
||||
// newColumns are target columns added after the legacy stores, with no
|
||||
// legacy value to carry. Imported rows take the column default: an imported
|
||||
// capture has no event type, so it stays unidentified and never dispatches.
|
||||
// legacy value to carry; an imported row takes the column default. An
|
||||
// imported capture has no event type, so it stays unidentified and never
|
||||
// dispatches, and no legacy source could take unsigned events.
|
||||
var newColumns = map[string]bool{
|
||||
"captures.event_type": true,
|
||||
"captures.unsigned": true,
|
||||
}
|
||||
|
||||
// targetKeys override a table's legacy key where the target has no column
|
||||
|
||||
@@ -44,7 +44,7 @@ type EDA struct {
|
||||
notify func(events.Event)
|
||||
}
|
||||
|
||||
// NewEDA builds an EDA store over pool. A nil cipher keeps binding secrets in
|
||||
// NewEDA builds an EDA store over pool. A nil cipher keeps source secrets in
|
||||
// plaintext (the behaviour that predates the option); the caller resolves the
|
||||
// keyring through edastore.NewBindingCipher, exactly as the PocketBase store
|
||||
// does. The pool is owned by the caller, not this store.
|
||||
@@ -98,6 +98,7 @@ func (s *EDA) InsertCapture(ctx context.Context, c storecontract.CapturedEvent,
|
||||
Headers: c.Headers,
|
||||
Body: c.Body,
|
||||
Authenticated: c.Authenticated,
|
||||
Unsigned: c.Unsigned,
|
||||
ReceivedAt: received.UTC(),
|
||||
EventType: eventType,
|
||||
}); err != nil {
|
||||
@@ -134,6 +135,7 @@ func captureValue(r postgresdb.Capture) storecontract.CapturedEvent {
|
||||
Body: r.Body,
|
||||
Authenticated: r.Authenticated,
|
||||
EventType: r.EventType,
|
||||
Unsigned: r.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -284,19 +286,10 @@ func (s *EDA) DeleteMapping(ctx context.Context, id string) error {
|
||||
|
||||
// --- bindings ---
|
||||
|
||||
func (s *EDA) encryptSecret(secret string) (string, error) {
|
||||
if s.cipher == nil {
|
||||
return secret, nil
|
||||
}
|
||||
encrypted, err := s.cipher.Encrypt(secret)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: encrypt binding secret: %w", err)
|
||||
}
|
||||
return encrypted, nil
|
||||
}
|
||||
|
||||
func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
|
||||
b := binding.Binding{
|
||||
// bindingValue takes GetBindingRow; the list queries' rows share its fields
|
||||
// and convert to it.
|
||||
func bindingValue(r postgresdb.GetBindingRow) binding.Binding {
|
||||
return binding.Binding{
|
||||
ID: r.ID,
|
||||
Name: r.Name,
|
||||
Matcher: binding.Matcher{Source: r.Source},
|
||||
@@ -306,18 +299,9 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
|
||||
Repo: r.Repo,
|
||||
Version: int(r.Version),
|
||||
Status: binding.Status(r.Status),
|
||||
Secret: r.Secret,
|
||||
CreatedAt: r.CreatedAt,
|
||||
UpdatedAt: r.UpdatedAt,
|
||||
}
|
||||
if s.cipher != nil && b.Secret != "" {
|
||||
plain, err := s.cipher.Decrypt(b.Secret)
|
||||
if err != nil {
|
||||
return binding.Binding{}, fmt.Errorf("edastore: decrypt binding secret: %w", err)
|
||||
}
|
||||
b.Secret = plain
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// InsertBinding stores a new binding as pending_approval. "One binding per
|
||||
@@ -325,14 +309,6 @@ func (s *EDA) bindingValue(r postgresdb.Binding) (binding.Binding, error) {
|
||||
// second insert for the same source is refused by the database and surfaced
|
||||
// here as ErrBindingOverlap.
|
||||
func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, error) {
|
||||
secret := b.Secret
|
||||
if secret != "" {
|
||||
var err error
|
||||
secret, err = s.encryptSecret(secret)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
}
|
||||
id := newRecordID()
|
||||
err := s.q.InsertBinding(ctx, postgresdb.InsertBindingParams{
|
||||
ID: id,
|
||||
@@ -343,7 +319,6 @@ func (s *EDA) InsertBinding(ctx context.Context, b binding.Binding) (string, err
|
||||
Owner: b.Owner,
|
||||
Repo: b.Repo,
|
||||
Status: string(binding.StatusPendingApproval),
|
||||
Secret: secret,
|
||||
})
|
||||
if isUniqueViolation(err) {
|
||||
return "", storecontract.ErrBindingOverlap
|
||||
@@ -365,10 +340,7 @@ func (s *EDA) GetBinding(ctx context.Context, id string) (*binding.Binding, erro
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := s.bindingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b := bindingValue(r)
|
||||
return &b, nil
|
||||
}
|
||||
|
||||
@@ -379,11 +351,7 @@ func (s *EDA) ListBindings(ctx context.Context) ([]binding.Binding, error) {
|
||||
}
|
||||
out := make([]binding.Binding, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
b, err := s.bindingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, b)
|
||||
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -396,28 +364,14 @@ func (s *EDA) ArmedBindingsForSource(ctx context.Context, source string) ([]bind
|
||||
}
|
||||
out := make([]binding.Binding, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
b, err := s.bindingValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, b)
|
||||
out = append(out, bindingValue(postgresdb.GetBindingRow(r)))
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// UpdateBinding rewrites a binding's editable fields, bumps its version and
|
||||
// drops it back to pending_approval. An empty secret means "keep the stored
|
||||
// one" (the CASE in the query), so an edit form that does not echo the secret
|
||||
// cannot blank an armed binding's HMAC key.
|
||||
// drops it back to pending_approval.
|
||||
func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
|
||||
secret := b.Secret
|
||||
if secret != "" {
|
||||
var err error
|
||||
secret, err = s.encryptSecret(secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
n, err := s.q.UpdateBinding(ctx, postgresdb.UpdateBindingParams{
|
||||
ID: b.ID,
|
||||
Name: b.Name,
|
||||
@@ -427,7 +381,6 @@ func (s *EDA) UpdateBinding(ctx context.Context, b binding.Binding) error {
|
||||
Owner: b.Owner,
|
||||
Repo: b.Repo,
|
||||
Status: string(binding.StatusPendingApproval),
|
||||
Secret: secret,
|
||||
})
|
||||
if isUniqueViolation(err) {
|
||||
return storecontract.ErrBindingOverlap
|
||||
|
||||
@@ -128,79 +128,6 @@ func TestConcurrentInsertBindingSameSource(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Hazard 1: UpdateBinding with an empty secret must leave the stored envelope
|
||||
// untouched, so an edit form that does not echo the secret cannot blank an
|
||||
// armed binding's HMAC key.
|
||||
func TestUpdateBindingEmptySecretPreservesStored(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
|
||||
secretID, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
before := readRawSecret(t, pool, secretID)
|
||||
|
||||
// Edit with an empty secret: the stored envelope must not change.
|
||||
if err := s.UpdateBinding(t.Context(), binding.Binding{
|
||||
ID: secretID, Name: "renamed", Matcher: binding.Matcher{Source: "src-secret"}, Workflow: "escalate",
|
||||
}); err != nil {
|
||||
t.Fatalf("UpdateBinding() error = %v", err)
|
||||
}
|
||||
after := readRawSecret(t, pool, secretID)
|
||||
if after != before {
|
||||
t.Fatalf("stored secret changed on empty-secret edit: %q -> %q", before, after)
|
||||
}
|
||||
if after == "" {
|
||||
t.Fatal("stored secret is empty after an empty-secret edit; the binding was silently disarmed")
|
||||
}
|
||||
}
|
||||
|
||||
func readRawSecret(t *testing.T, pool *pgxpool.Pool, id string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
if err := pool.QueryRow(t.Context(), "SELECT secret FROM bindings WHERE id = $1", id).Scan(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// The cipher path must keep decrypt-in-store: what is stored is an envelope,
|
||||
// what reads back is the plaintext HMAC key the intake verifies with.
|
||||
func TestBindingSecretEncryptedAtRestAndDecryptedOnRead(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
|
||||
id, err := s.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "n", Matcher: binding.Matcher{Source: "src-cipher"}, Workflow: "implement",
|
||||
Secret: "supersecretvalue0123",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("InsertBinding() error = %v", err)
|
||||
}
|
||||
stored := readRawSecret(t, pool, id)
|
||||
if stored == "supersecretvalue0123" {
|
||||
t.Fatal("secret is stored plaintext; it must be encrypted at rest")
|
||||
}
|
||||
|
||||
got, err := s.GetBinding(t.Context(), id)
|
||||
if err != nil {
|
||||
t.Fatalf("GetBinding() error = %v", err)
|
||||
}
|
||||
if got.Secret != "supersecretvalue0123" {
|
||||
t.Errorf("Secret = %q, want the plaintext on read: the wire carries plaintext, so decrypt must happen in the store", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// The lifecycle gate survives the port: pending_approval -> armed, and only
|
||||
// from pending_approval.
|
||||
func TestBindingLifecycle(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
-- Capture sources own signing (docs/prds/event-automation.md "Sources").
|
||||
--
|
||||
-- * path is the key. It is the URL segment a sender posts to and the string
|
||||
-- captures.source and bindings.source already carry, so existing rows keep
|
||||
-- resolving without a rewrite. It never changes after creation.
|
||||
-- * signing is signed by default. Turning it off is a request
|
||||
-- (unsigned_pending_approval) that only an approval makes effective.
|
||||
-- * secret holds the cipher envelope when a bindings encryption key is
|
||||
-- configured, plaintext otherwise, exactly as bindings.secret did.
|
||||
-- * captures.unsigned marks an event taken on an approved unsigned source.
|
||||
-- * bindings.secret is no longer read. It stays so the one-time legacy
|
||||
-- import can load it and derive_sources can move it onto the source.
|
||||
--
|
||||
-- derive_sources creates a source for every source string bindings and
|
||||
-- captures already use. A bound source takes its binding's secret (one binding
|
||||
-- per source is schema-enforced), so a signed sender keeps authenticating. A
|
||||
-- capture-only source gets no secret and dispatches nothing until the
|
||||
-- operator generates one. The legacy import calls it again after loading.
|
||||
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE sources (
|
||||
path text PRIMARY KEY,
|
||||
signing text NOT NULL DEFAULT 'signed'
|
||||
CHECK (signing IN ('signed', 'unsigned_pending_approval', 'unsigned')),
|
||||
secret text NOT NULL DEFAULT '',
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
ALTER TABLE captures ADD COLUMN unsigned boolean NOT NULL DEFAULT false;
|
||||
|
||||
-- +goose StatementBegin
|
||||
CREATE FUNCTION derive_sources() RETURNS void LANGUAGE sql AS $$
|
||||
INSERT INTO sources (path, secret)
|
||||
SELECT source, secret FROM bindings WHERE source <> ''
|
||||
ON CONFLICT (path) DO NOTHING;
|
||||
INSERT INTO sources (path)
|
||||
SELECT DISTINCT source FROM captures WHERE source <> ''
|
||||
ON CONFLICT (path) DO NOTHING;
|
||||
$$;
|
||||
-- +goose StatementEnd
|
||||
|
||||
SELECT derive_sources();
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP FUNCTION derive_sources();
|
||||
ALTER TABLE captures DROP COLUMN unsigned;
|
||||
DROP TABLE sources;
|
||||
@@ -11,19 +11,33 @@ import (
|
||||
)
|
||||
|
||||
const armedBindingsForSource = `-- name: ArmedBindingsForSource :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC
|
||||
`
|
||||
|
||||
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]Binding, error) {
|
||||
type ArmedBindingsForSourceRow struct {
|
||||
ID string
|
||||
Name string
|
||||
Source string
|
||||
Mapping string
|
||||
Workflow string
|
||||
Owner string
|
||||
Repo string
|
||||
Version int64
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]ArmedBindingsForSourceRow, error) {
|
||||
rows, err := q.db.Query(ctx, armedBindingsForSource, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Binding
|
||||
var items []ArmedBindingsForSourceRow
|
||||
for rows.Next() {
|
||||
var i Binding
|
||||
var i ArmedBindingsForSourceRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
@@ -34,7 +48,6 @@ func (q *Queries) ArmedBindingsForSource(ctx context.Context, source string) ([]
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
@@ -113,6 +126,15 @@ func (q *Queries) DeletePlaybookDispatches(ctx context.Context, playbookID strin
|
||||
return err
|
||||
}
|
||||
|
||||
const deriveSources = `-- name: DeriveSources :exec
|
||||
SELECT derive_sources()
|
||||
`
|
||||
|
||||
func (q *Queries) DeriveSources(ctx context.Context) error {
|
||||
_, err := q.db.Exec(ctx, deriveSources)
|
||||
return err
|
||||
}
|
||||
|
||||
const eventTypesForSource = `-- name: EventTypesForSource :many
|
||||
SELECT id, source, name, rule, schema, created_at, updated_at
|
||||
FROM event_types WHERE source = $1 ORDER BY name
|
||||
@@ -147,13 +169,27 @@ func (q *Queries) EventTypesForSource(ctx context.Context, source string) ([]Eve
|
||||
}
|
||||
|
||||
const getBinding = `-- name: GetBinding :one
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
type GetBindingRow struct {
|
||||
ID string
|
||||
Name string
|
||||
Source string
|
||||
Mapping string
|
||||
Workflow string
|
||||
Owner string
|
||||
Repo string
|
||||
Version int64
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetBinding(ctx context.Context, id string) (GetBindingRow, error) {
|
||||
row := q.db.QueryRow(ctx, getBinding, id)
|
||||
var i Binding
|
||||
var i GetBindingRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
@@ -164,7 +200,6 @@ func (q *Queries) GetBinding(ctx context.Context, id string) (Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
@@ -210,9 +245,26 @@ func (q *Queries) GetMapping(ctx context.Context, id string) (Mapping, error) {
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSource = `-- name: GetSource :one
|
||||
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetSource(ctx context.Context, path string) (Source, error) {
|
||||
row := q.db.QueryRow(ctx, getSource, path)
|
||||
var i Source
|
||||
err := row.Scan(
|
||||
&i.Path,
|
||||
&i.Signing,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertBinding = `-- name: InsertBinding :exec
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9)
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8)
|
||||
`
|
||||
|
||||
type InsertBindingParams struct {
|
||||
@@ -224,7 +276,6 @@ type InsertBindingParams struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Status string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) error {
|
||||
@@ -237,7 +288,6 @@ func (q *Queries) InsertBinding(ctx context.Context, arg InsertBindingParams) er
|
||||
arg.Owner,
|
||||
arg.Repo,
|
||||
arg.Status,
|
||||
arg.Secret,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -266,8 +316,8 @@ func (q *Queries) InsertBindingDispatch(ctx context.Context, arg InsertBindingDi
|
||||
|
||||
const insertCapture = `-- name: InsertCapture :exec
|
||||
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
`
|
||||
|
||||
type InsertCaptureParams struct {
|
||||
@@ -279,6 +329,7 @@ type InsertCaptureParams struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
EventType string
|
||||
}
|
||||
|
||||
@@ -293,6 +344,7 @@ func (q *Queries) InsertCapture(ctx context.Context, arg InsertCaptureParams) er
|
||||
arg.Body,
|
||||
arg.Authenticated,
|
||||
arg.ReceivedAt,
|
||||
arg.Unsigned,
|
||||
arg.EventType,
|
||||
)
|
||||
return err
|
||||
@@ -366,6 +418,21 @@ func (q *Queries) InsertPlaybookDispatch(ctx context.Context, arg InsertPlaybook
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSource = `-- name: InsertSource :exec
|
||||
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3)
|
||||
`
|
||||
|
||||
type InsertSourceParams struct {
|
||||
Path string
|
||||
Signing string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSource(ctx context.Context, arg InsertSourceParams) error {
|
||||
_, err := q.db.Exec(ctx, insertSource, arg.Path, arg.Signing, arg.Secret)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertToolCall = `-- name: InsertToolCall :exec
|
||||
INSERT INTO tool_calls (id, task_id, attempt, tool, result, error, called_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
@@ -395,19 +462,33 @@ func (q *Queries) InsertToolCall(ctx context.Context, arg InsertToolCallParams)
|
||||
}
|
||||
|
||||
const listBindings = `-- name: ListBindings :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings ORDER BY created_at DESC
|
||||
`
|
||||
|
||||
func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
type ListBindingsRow struct {
|
||||
ID string
|
||||
Name string
|
||||
Source string
|
||||
Mapping string
|
||||
Workflow string
|
||||
Owner string
|
||||
Repo string
|
||||
Version int64
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListBindings(ctx context.Context) ([]ListBindingsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listBindings)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Binding
|
||||
var items []ListBindingsRow
|
||||
for rows.Next() {
|
||||
var i Binding
|
||||
var i ListBindingsRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Name,
|
||||
@@ -418,7 +499,6 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
&i.Repo,
|
||||
&i.Version,
|
||||
&i.Status,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
@@ -433,7 +513,7 @@ func (q *Queries) ListBindings(ctx context.Context) ([]Binding, error) {
|
||||
}
|
||||
|
||||
const listCaptures = `-- name: ListCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1
|
||||
@@ -457,6 +537,7 @@ func (q *Queries) ListCaptures(ctx context.Context, limit int32) ([]Capture, err
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.Unsigned,
|
||||
&i.EventType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
@@ -534,8 +615,38 @@ func (q *Queries) ListMappings(ctx context.Context) ([]Mapping, error) {
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listSources = `-- name: ListSources :many
|
||||
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path
|
||||
`
|
||||
|
||||
func (q *Queries) ListSources(ctx context.Context) ([]Source, error) {
|
||||
rows, err := q.db.Query(ctx, listSources)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []Source
|
||||
for rows.Next() {
|
||||
var i Source
|
||||
if err := rows.Scan(
|
||||
&i.Path,
|
||||
&i.Signing,
|
||||
&i.Secret,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listUndispatchedCaptures = `-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
|
||||
FROM captures
|
||||
WHERE source = ANY($1::text[])
|
||||
-- An unidentified capture is never dispatched.
|
||||
@@ -568,6 +679,7 @@ func (q *Queries) ListUndispatchedCaptures(ctx context.Context, arg ListUndispat
|
||||
&i.Body,
|
||||
&i.Authenticated,
|
||||
&i.ReceivedAt,
|
||||
&i.Unsigned,
|
||||
&i.EventType,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
@@ -603,6 +715,53 @@ func (q *Queries) SetBindingArmed(ctx context.Context, id string) (int64, error)
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const setSourceSecret = `-- name: SetSourceSecret :execrows
|
||||
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1
|
||||
`
|
||||
|
||||
type SetSourceSecretParams struct {
|
||||
Path string
|
||||
Secret string
|
||||
}
|
||||
|
||||
func (q *Queries) SetSourceSecret(ctx context.Context, arg SetSourceSecretParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, setSourceSecret, arg.Path, arg.Secret)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const setSourceSigning = `-- name: SetSourceSigning :execrows
|
||||
UPDATE sources SET signing = $1, updated_at = now()
|
||||
WHERE path = $2 AND signing = $3
|
||||
`
|
||||
|
||||
type SetSourceSigningParams struct {
|
||||
ToSigning string
|
||||
Path string
|
||||
FromSigning string
|
||||
}
|
||||
|
||||
func (q *Queries) SetSourceSigning(ctx context.Context, arg SetSourceSigningParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, setSourceSigning, arg.ToSigning, arg.Path, arg.FromSigning)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
|
||||
const sourceExists = `-- name: SourceExists :one
|
||||
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1)
|
||||
`
|
||||
|
||||
func (q *Queries) SourceExists(ctx context.Context, path string) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, sourceExists, path)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const taskToolCalls = `-- name: TaskToolCalls :many
|
||||
SELECT id, task_id, attempt, tool, result, error, called_at
|
||||
FROM tool_calls WHERE task_id = $1 ORDER BY called_at ASC
|
||||
@@ -649,9 +808,7 @@ func (q *Queries) TaskToolCalls(ctx context.Context, taskID int64) ([]TaskToolCa
|
||||
const updateBinding = `-- name: UpdateBinding :execrows
|
||||
UPDATE bindings
|
||||
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
|
||||
version = version + 1, status = $8,
|
||||
secret = CASE WHEN $9::text = '' THEN secret ELSE $9 END,
|
||||
updated_at = now()
|
||||
version = version + 1, status = $8, updated_at = now()
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
@@ -664,12 +821,8 @@ type UpdateBindingParams struct {
|
||||
Owner string
|
||||
Repo string
|
||||
Status string
|
||||
Secret string
|
||||
}
|
||||
|
||||
// An empty secret means "keep the stored one": the CASE leaves the column
|
||||
// untouched so an edit form that does not echo the secret cannot blank an
|
||||
// armed binding's HMAC key.
|
||||
func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updateBinding,
|
||||
arg.ID,
|
||||
@@ -680,7 +833,6 @@ func (q *Queries) UpdateBinding(ctx context.Context, arg UpdateBindingParams) (i
|
||||
arg.Owner,
|
||||
arg.Repo,
|
||||
arg.Status,
|
||||
arg.Secret,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
@@ -48,6 +48,7 @@ type Capture struct {
|
||||
Body string
|
||||
Authenticated bool
|
||||
ReceivedAt time.Time
|
||||
Unsigned bool
|
||||
EventType string
|
||||
}
|
||||
|
||||
@@ -200,6 +201,14 @@ type Session struct {
|
||||
LastActiveAt int64
|
||||
}
|
||||
|
||||
type Source struct {
|
||||
Path string
|
||||
Signing string
|
||||
Secret string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Task struct {
|
||||
ID int64
|
||||
Owner string
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
-- EDA queries: captures, mappings, bindings, dispatch ledgers, tool_calls.
|
||||
|
||||
-- name: InsertCapture :exec
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9);
|
||||
INSERT INTO captures (id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10);
|
||||
|
||||
-- name: ListCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
|
||||
FROM captures
|
||||
ORDER BY received_at DESC
|
||||
LIMIT $1;
|
||||
|
||||
-- name: ListUndispatchedCaptures :many
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, event_type
|
||||
SELECT id, source, remote_addr, content_type, headers, body, authenticated, received_at, unsigned, event_type
|
||||
FROM captures
|
||||
WHERE source = ANY(@sources::text[])
|
||||
-- An unidentified capture is never dispatched.
|
||||
@@ -49,30 +49,25 @@ WHERE id = $1;
|
||||
DELETE FROM mappings WHERE id = $1;
|
||||
|
||||
-- name: InsertBinding :exec
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status, secret)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8, $9);
|
||||
INSERT INTO bindings (id, name, source, mapping, workflow, owner, repo, version, status)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, 1, $8);
|
||||
|
||||
-- name: GetBinding :one
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings WHERE id = $1;
|
||||
|
||||
-- name: ListBindings :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings ORDER BY created_at DESC;
|
||||
|
||||
-- name: ArmedBindingsForSource :many
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, secret, created_at, updated_at
|
||||
SELECT id, name, source, mapping, workflow, owner, repo, version, status, created_at, updated_at
|
||||
FROM bindings WHERE source = $1 AND status = 'armed' ORDER BY created_at DESC;
|
||||
|
||||
-- name: UpdateBinding :execrows
|
||||
-- An empty secret means "keep the stored one": the CASE leaves the column
|
||||
-- untouched so an edit form that does not echo the secret cannot blank an
|
||||
-- armed binding's HMAC key.
|
||||
UPDATE bindings
|
||||
SET name = $2, source = $3, mapping = $4, workflow = $5, owner = $6, repo = $7,
|
||||
version = version + 1, status = $8,
|
||||
secret = CASE WHEN sqlc.arg(secret)::text = '' THEN secret ELSE sqlc.arg(secret) END,
|
||||
updated_at = now()
|
||||
version = version + 1, status = $8, updated_at = now()
|
||||
WHERE id = $1;
|
||||
|
||||
-- name: SetBindingArmed :execrows
|
||||
@@ -126,3 +121,24 @@ DELETE FROM event_types WHERE id = $1;
|
||||
-- Serialises saves per source so two concurrent saves cannot each pass the
|
||||
-- overlap check against a set that excludes the other.
|
||||
SELECT pg_advisory_xact_lock(hashtext('event_types:' || sqlc.arg(source)::text));
|
||||
-- name: InsertSource :exec
|
||||
INSERT INTO sources (path, signing, secret) VALUES ($1, $2, $3);
|
||||
|
||||
-- name: GetSource :one
|
||||
SELECT path, signing, secret, created_at, updated_at FROM sources WHERE path = $1;
|
||||
|
||||
-- name: ListSources :many
|
||||
SELECT path, signing, secret, created_at, updated_at FROM sources ORDER BY created_at DESC, path;
|
||||
|
||||
-- name: SetSourceSigning :execrows
|
||||
UPDATE sources SET signing = sqlc.arg(to_signing), updated_at = now()
|
||||
WHERE path = sqlc.arg(path) AND signing = sqlc.arg(from_signing);
|
||||
|
||||
-- name: SetSourceSecret :execrows
|
||||
UPDATE sources SET secret = $2, updated_at = now() WHERE path = $1;
|
||||
|
||||
-- name: SourceExists :one
|
||||
SELECT EXISTS (SELECT 1 FROM sources WHERE path = $1);
|
||||
|
||||
-- name: DeriveSources :exec
|
||||
SELECT derive_sources();
|
||||
@@ -0,0 +1,130 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
|
||||
)
|
||||
|
||||
var _ storecontract.SourceStore = (*EDA)(nil)
|
||||
|
||||
// InsertSource stores a new source. The path is the primary key, so a taken
|
||||
// path is refused by the database and surfaced as ErrSourcePathTaken.
|
||||
func (s *EDA) InsertSource(ctx context.Context, src source.Source) error {
|
||||
secret, err := s.sealSecret(src.Secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = s.q.InsertSource(ctx, postgresdb.InsertSourceParams{
|
||||
Path: src.Path, Signing: string(src.Signing), Secret: secret,
|
||||
})
|
||||
if isUniqueViolation(err) {
|
||||
return storecontract.ErrSourcePathTaken
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: insert source: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSource returns (nil, nil) for an unknown path.
|
||||
func (s *EDA) GetSource(ctx context.Context, path string) (*source.Source, error) {
|
||||
r, err := s.q.GetSource(ctx, path)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: get source: %w", err)
|
||||
}
|
||||
src, err := s.sourceValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &src, nil
|
||||
}
|
||||
|
||||
func (s *EDA) ListSources(ctx context.Context) ([]source.Source, error) {
|
||||
rows, err := s.q.ListSources(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("edastore: list sources: %w", err)
|
||||
}
|
||||
out := make([]source.Source, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
src, err := s.sourceValue(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, src)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// SetSourceSigning moves a source from one signing state to another, and
|
||||
// refuses when the stored state is no longer from.
|
||||
func (s *EDA) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
|
||||
n, err := s.q.SetSourceSigning(ctx, postgresdb.SetSourceSigningParams{
|
||||
Path: path, FromSigning: string(from), ToSigning: string(to),
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: set source signing: %w", err)
|
||||
}
|
||||
if n == 1 {
|
||||
return nil
|
||||
}
|
||||
exists, err := s.q.SourceExists(ctx, path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: set source signing: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
return storecontract.ErrSourceSigningStale
|
||||
}
|
||||
|
||||
func (s *EDA) SetSourceSecret(ctx context.Context, path, secret string) error {
|
||||
sealed, err := s.sealSecret(secret)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := s.q.SetSourceSecret(ctx, postgresdb.SetSourceSecretParams{Path: path, Secret: sealed})
|
||||
if err != nil {
|
||||
return fmt.Errorf("edastore: set source secret: %w", err)
|
||||
}
|
||||
if n == 0 {
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sealSecret encrypts a non-empty secret when a cipher is configured.
|
||||
func (s *EDA) sealSecret(secret string) (string, error) {
|
||||
if s.cipher == nil || secret == "" {
|
||||
return secret, nil
|
||||
}
|
||||
sealed, err := s.cipher.Encrypt(secret)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("edastore: encrypt source secret: %w", err)
|
||||
}
|
||||
return sealed, nil
|
||||
}
|
||||
|
||||
func (s *EDA) sourceValue(r postgresdb.Source) (source.Source, error) {
|
||||
secret := r.Secret
|
||||
if s.cipher != nil && secret != "" {
|
||||
plain, err := s.cipher.Decrypt(secret)
|
||||
if err != nil {
|
||||
return source.Source{}, fmt.Errorf("edastore: decrypt source secret: %w", err)
|
||||
}
|
||||
secret = plain
|
||||
}
|
||||
return source.Source{
|
||||
Path: r.Path, Signing: source.Signing(r.Signing), Secret: secret,
|
||||
CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/infrastructure/edastore"
|
||||
)
|
||||
|
||||
func readRawSourceSecret(t *testing.T, pool *pgxpool.Pool, path string) string {
|
||||
t.Helper()
|
||||
var stored string
|
||||
if err := pool.QueryRow(t.Context(), "SELECT secret FROM sources WHERE path = $1", path).Scan(&stored); err != nil {
|
||||
t.Fatalf("read raw secret: %v", err)
|
||||
}
|
||||
return stored
|
||||
}
|
||||
|
||||
// A new source keeps its generated path, is signed, stores its secret as a
|
||||
// cipher envelope and reads it back as plaintext.
|
||||
func TestSourceRoundTripEncryptsSecret(t *testing.T) {
|
||||
cipher, err := edastore.NewBindingCipher(edaTestKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("NewBindingCipher() error = %v", err)
|
||||
}
|
||||
pool, s := edaWithCipher(t, cipher)
|
||||
in, err := source.New("")
|
||||
if err != nil {
|
||||
t.Fatalf("source.New() error = %v", err)
|
||||
}
|
||||
if err := s.InsertSource(t.Context(), in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if raw := readRawSourceSecret(t, pool, in.Path); raw == in.Secret || raw == "" {
|
||||
t.Fatalf("stored secret = %q, want a cipher envelope", raw)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), in.Path)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("GetSource() = %v, %v", got, err)
|
||||
}
|
||||
if got.Path != in.Path || got.Signing != source.SigningSigned || got.Secret != in.Secret {
|
||||
t.Fatalf("GetSource() = %+v, want path %q signed with the plaintext secret", got, in.Path)
|
||||
}
|
||||
list, err := s.ListSources(t.Context())
|
||||
if err != nil || len(list) != 1 || list[0].Secret != in.Secret {
|
||||
t.Fatalf("ListSources() = %+v, %v", list, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceWritesRefuseBadState(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
taken := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k"}
|
||||
if err := s.InsertSource(t.Context(), taken); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
write func() error
|
||||
want error
|
||||
}{
|
||||
{"taken custom path", func() error { return s.InsertSource(t.Context(), taken) }, storecontract.ErrSourcePathTaken},
|
||||
{"stale signing", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "sentry", source.SigningUnsignedPending, source.SigningUnsigned)
|
||||
}, storecontract.ErrSourceSigningStale},
|
||||
{"signing on unknown path", func() error {
|
||||
return s.SetSourceSigning(t.Context(), "nope", source.SigningSigned, source.SigningUnsignedPending)
|
||||
}, storecontract.ErrSourceNotFound},
|
||||
{"secret on unknown path", func() error { return s.SetSourceSecret(t.Context(), "nope", "k") }, storecontract.ErrSourceNotFound},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.write(); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "nope")
|
||||
if err != nil || got != nil {
|
||||
t.Fatalf("GetSource(unknown) = %v, %v; want nil, nil", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceSigningAndSecretWrites(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
if err := s.InsertSource(t.Context(), source.Source{Path: "fw", Signing: source.SigningSigned}); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSigning(t.Context(), "fw", source.SigningSigned, source.SigningUnsignedPending); err != nil {
|
||||
t.Fatalf("SetSourceSigning() error = %v", err)
|
||||
}
|
||||
if err := s.SetSourceSecret(t.Context(), "fw", "newsecret"); err != nil {
|
||||
t.Fatalf("SetSourceSecret() error = %v", err)
|
||||
}
|
||||
got, err := s.GetSource(t.Context(), "fw")
|
||||
if err != nil || got.Signing != source.SigningUnsignedPending || got.Secret != "newsecret" {
|
||||
t.Fatalf("GetSource() = %+v, %v", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureUnsignedRoundTrip(t *testing.T) {
|
||||
s := edaFor(t)
|
||||
// Only an identified capture is listed for dispatch; a catch-all type
|
||||
// identifies every event on the source.
|
||||
if _, err := s.InsertEventType(t.Context(), eventtype.EventType{Source: "fw", Name: "any"}); err != nil {
|
||||
t.Fatalf("InsertEventType() error = %v", err)
|
||||
}
|
||||
if _, err := s.InsertCapture(t.Context(), storecontract.CapturedEvent{Source: "fw", Unsigned: true}, 0, 0); err != nil {
|
||||
t.Fatalf("InsertCapture() error = %v", err)
|
||||
}
|
||||
for name, list := range map[string]func() ([]storecontract.CapturedEvent, error){
|
||||
"ListCaptures": func() ([]storecontract.CapturedEvent, error) { return s.ListCaptures(t.Context(), 10) },
|
||||
"ListUndispatchedCaptures": func() ([]storecontract.CapturedEvent, error) {
|
||||
return s.ListUndispatchedCaptures(t.Context(), []string{"fw"}, 10)
|
||||
},
|
||||
} {
|
||||
got, err := list()
|
||||
if err != nil || len(got) != 1 || !got[0].Unsigned {
|
||||
t.Errorf("%s() = %+v, %v; want one unsigned capture", name, got, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Existing source strings become sources: a bound source takes its binding's
|
||||
// secret, a capture-only source gets none, and an existing source is kept.
|
||||
func TestDeriveSourcesFromExistingRows(t *testing.T) {
|
||||
pool, q := migrated(t)
|
||||
ctx := t.Context()
|
||||
for _, stmt := range []string{
|
||||
`INSERT INTO bindings (id, name, source, secret) VALUES ('b1', 'n', 'sentry', 'envelope')`,
|
||||
`INSERT INTO captures (id, source, received_at) VALUES ('c1', 'sentry', now()), ('c2', 'firewall', now()), ('c3', 'kept', now())`,
|
||||
`INSERT INTO sources (path, signing, secret) VALUES ('kept', 'unsigned', 'x')`,
|
||||
} {
|
||||
if _, err := pool.Exec(ctx, stmt); err != nil {
|
||||
t.Fatalf("%s: %v", stmt, err)
|
||||
}
|
||||
}
|
||||
if err := q.DeriveSources(ctx); err != nil {
|
||||
t.Fatalf("DeriveSources() error = %v", err)
|
||||
}
|
||||
want := map[string][2]string{
|
||||
"sentry": {"signed", "envelope"},
|
||||
"firewall": {"signed", ""},
|
||||
"kept": {"unsigned", "x"},
|
||||
}
|
||||
rows, err := q.ListSources(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ListSources() error = %v", err)
|
||||
}
|
||||
if len(rows) != len(want) {
|
||||
t.Fatalf("derived %d sources, want %d: %+v", len(rows), len(want), rows)
|
||||
}
|
||||
for _, r := range rows {
|
||||
if w := want[r.Path]; w != [2]string{r.Signing, r.Secret} {
|
||||
t.Errorf("source %q = (%s, %q), want %v", r.Path, r.Signing, r.Secret, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -33,14 +33,14 @@ func TestCaptureListsExceedUnaryMessageLimit(t *testing.T) {
|
||||
// public draft -> pending_approval -> armed lifecycle.
|
||||
id, err := eda.InsertBinding(t.Context(), binding.Binding{
|
||||
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := eda.UpdateBinding(t.Context(), binding.Binding{
|
||||
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -47,6 +48,7 @@ var (
|
||||
_ storecontract.CaptureStore = (*Client)(nil)
|
||||
_ storecontract.MappingStore = (*Client)(nil)
|
||||
_ storecontract.BindingStore = (*Client)(nil)
|
||||
_ storecontract.SourceStore = (*Client)(nil)
|
||||
_ storecontract.BindingDispatcher = (*Client)(nil)
|
||||
_ storecontract.BindingTaskCreator = (*Client)(nil)
|
||||
_ storecontract.PlaybookDispatcher = (*Client)(nil)
|
||||
@@ -460,6 +462,43 @@ func (c *Client) ApproveBinding(ctx context.Context, id string) error {
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// Source
|
||||
|
||||
func (c *Client) InsertSource(ctx context.Context, s source.Source) error {
|
||||
_, err := c.client.InsertSource(ctx, &pb.InsertSourceRequest{Source: sourceProto(s)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) GetSource(ctx context.Context, path string) (*source.Source, error) {
|
||||
r, err := c.client.GetSource(ctx, &pb.GetSourceRequest{Path: path})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
if !r.Found {
|
||||
return nil, nil
|
||||
}
|
||||
v := sourceValue(r.Source)
|
||||
return &v, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListSources(ctx context.Context) ([]source.Source, error) {
|
||||
r, err := c.client.ListSources(ctx, &pb.ListSourcesRequest{})
|
||||
if err != nil {
|
||||
return nil, unmapError(err)
|
||||
}
|
||||
return mapValues(r.Sources, sourceValue), nil
|
||||
}
|
||||
|
||||
func (c *Client) SetSourceSigning(ctx context.Context, path string, from, to source.Signing) error {
|
||||
_, err := c.client.SetSourceSigning(ctx, &pb.SetSourceSigningRequest{Path: path, From: string(from), To: string(to)})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
func (c *Client) SetSourceSecret(ctx context.Context, path, secret string) error {
|
||||
_, err := c.client.SetSourceSecret(ctx, &pb.SetSourceSecretRequest{Path: path, Secret: secret})
|
||||
return unmapError(err)
|
||||
}
|
||||
|
||||
// Dispatch
|
||||
|
||||
func (c *Client) ArmedBindingsForSource(ctx context.Context, source string) ([]binding.Binding, error) {
|
||||
|
||||
@@ -384,14 +384,14 @@ func TestStateStoreConformance(t *testing.T) {
|
||||
// ErrAlreadyDispatched.
|
||||
bindingID, err := ec.InsertBinding(ctx, binding.Binding{
|
||||
Name: "b1", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
Workflow: "implement",
|
||||
})
|
||||
if err != nil || bindingID == "" {
|
||||
t.Fatalf("InsertBinding: %v %v", bindingID, err)
|
||||
}
|
||||
_, err = ec.InsertBinding(ctx, binding.Binding{
|
||||
Name: "b2", Matcher: binding.Matcher{Source: "sentry"}, MappingID: mappingID,
|
||||
Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
Workflow: "implement",
|
||||
})
|
||||
if !errors.Is(err, store.ErrBindingOverlap) {
|
||||
t.Fatalf("InsertBinding overlap = %v, want ErrBindingOverlap", err)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/store"
|
||||
)
|
||||
|
||||
@@ -81,6 +82,9 @@ func TestUnmapErrorSentinelFidelity(t *testing.T) {
|
||||
{name: "binding overlap", store: store.ErrBindingOverlap, rehyd: store.ErrBindingOverlap},
|
||||
{name: "binding transition", store: store.ErrBindingTransition, rehyd: store.ErrBindingTransition},
|
||||
{name: "already dispatched", store: store.ErrAlreadyDispatched, rehyd: store.ErrAlreadyDispatched},
|
||||
{name: "source not found", store: storecontract.ErrSourceNotFound, rehyd: storecontract.ErrSourceNotFound},
|
||||
{name: "source path taken", store: storecontract.ErrSourcePathTaken, rehyd: storecontract.ErrSourcePathTaken},
|
||||
{name: "source signing stale", store: storecontract.ErrSourceSigningStale, rehyd: storecontract.ErrSourceSigningStale},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/logging"
|
||||
)
|
||||
@@ -35,6 +36,7 @@ var (
|
||||
errApplyStatusUnavailable = status.Error(codes.Unavailable, "apply status store unavailable")
|
||||
errMappingUnavailable = status.Error(codes.Unavailable, "mapping store unavailable")
|
||||
errBindingUnavailable = status.Error(codes.Unavailable, "binding store unavailable")
|
||||
errSourceUnavailable = status.Error(codes.Unavailable, "source store unavailable")
|
||||
errBindingDispatchUnavailable = status.Error(codes.Unavailable, "binding dispatcher unavailable")
|
||||
errBindingTaskCreatorUnavailable = status.Error(codes.Unavailable, "binding task creator unavailable")
|
||||
errPlaybookDispatcherUnavailable = status.Error(codes.Unavailable, "playbook dispatcher unavailable")
|
||||
@@ -78,6 +80,7 @@ type Deps struct {
|
||||
Mappings storecontract.MappingStore
|
||||
EventTypes storecontract.EventTypeStore
|
||||
Bindings storecontract.BindingStore
|
||||
Sources storecontract.SourceStore
|
||||
BindingDispatcher storecontract.BindingDispatcher
|
||||
BindingTaskCreator storecontract.BindingTaskCreator
|
||||
// PlaybookDispatcher is the side-effecting-action idempotency ledger
|
||||
@@ -647,6 +650,75 @@ func (s *server) ApproveBinding(ctx context.Context, r *pb.ApproveBindingRequest
|
||||
return &pb.ApproveBindingResponse{}, nil
|
||||
}
|
||||
|
||||
// Source
|
||||
|
||||
func (s *server) sources() (storecontract.SourceStore, error) {
|
||||
if s.deps.Sources == nil {
|
||||
return nil, errSourceUnavailable
|
||||
}
|
||||
return s.deps.Sources, nil
|
||||
}
|
||||
|
||||
func (s *server) InsertSource(ctx context.Context, r *pb.InsertSourceRequest) (*pb.InsertSourceResponse, error) {
|
||||
ss, err := s.sources()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ss.InsertSource(ctx, sourceValue(r.Source)); err != nil {
|
||||
return nil, s.logErr("InsertSource", err)
|
||||
}
|
||||
return &pb.InsertSourceResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) GetSource(ctx context.Context, r *pb.GetSourceRequest) (*pb.GetSourceResponse, error) {
|
||||
ss, err := s.sources()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
src, err := ss.GetSource(ctx, r.Path)
|
||||
if err != nil {
|
||||
return nil, s.logErr("GetSource", err)
|
||||
}
|
||||
if src == nil {
|
||||
return &pb.GetSourceResponse{}, nil
|
||||
}
|
||||
return &pb.GetSourceResponse{Source: sourceProto(*src), Found: true}, nil
|
||||
}
|
||||
|
||||
func (s *server) ListSources(ctx context.Context, _ *pb.ListSourcesRequest) (*pb.ListSourcesResponse, error) {
|
||||
ss, err := s.sources()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list, err := ss.ListSources(ctx)
|
||||
if err != nil {
|
||||
return nil, s.logErr("ListSources", err)
|
||||
}
|
||||
return &pb.ListSourcesResponse{Sources: mapValues(list, sourceProto)}, nil
|
||||
}
|
||||
|
||||
func (s *server) SetSourceSigning(ctx context.Context, r *pb.SetSourceSigningRequest) (*pb.SetSourceSigningResponse, error) {
|
||||
ss, err := s.sources()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ss.SetSourceSigning(ctx, r.Path, source.Signing(r.From), source.Signing(r.To)); err != nil {
|
||||
return nil, s.logErr("SetSourceSigning", err)
|
||||
}
|
||||
return &pb.SetSourceSigningResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *server) SetSourceSecret(ctx context.Context, r *pb.SetSourceSecretRequest) (*pb.SetSourceSecretResponse, error) {
|
||||
ss, err := s.sources()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := ss.SetSourceSecret(ctx, r.Path, r.Secret); err != nil {
|
||||
return nil, s.logErr("SetSourceSecret", err)
|
||||
}
|
||||
return &pb.SetSourceSecretResponse{}, nil
|
||||
}
|
||||
|
||||
// Dispatch
|
||||
|
||||
func (s *server) ArmedBindingsForSource(ctx context.Context, r *pb.ArmedBindingsForSourceRequest) (*pb.ArmedBindingsForSourceResponse, error) {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
package staterpc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/grpc/test/bufconn"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// memSources is an in-memory SourceStore with the Postgres store's error
|
||||
// contract, so the wire test checks the adapter rather than a database.
|
||||
type memSources map[string]source.Source
|
||||
|
||||
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
|
||||
if _, ok := m[s.Path]; ok {
|
||||
return storecontract.ErrSourcePathTaken
|
||||
}
|
||||
m[s.Path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
|
||||
out := make([]source.Source, 0, len(m))
|
||||
for _, s := range m {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
|
||||
s, ok := m[path]
|
||||
switch {
|
||||
case !ok:
|
||||
return storecontract.ErrSourceNotFound
|
||||
case s.Signing != from:
|
||||
return storecontract.ErrSourceSigningStale
|
||||
}
|
||||
s.Signing = to
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
s.Secret = secret
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func remoteSources(t *testing.T, sources storecontract.SourceStore) *Client {
|
||||
t.Helper()
|
||||
listener := bufconn.Listen(1 << 20)
|
||||
server := grpc.NewServer()
|
||||
RegisterServer(server, Deps{Sources: sources})
|
||||
go func() { _ = server.Serve(listener) }()
|
||||
t.Cleanup(func() { server.Stop(); _ = listener.Close() })
|
||||
conn, err := grpc.NewClient("passthrough:///state",
|
||||
grpc.WithTransportCredentials(insecure.NewCredentials()),
|
||||
grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return listener.DialContext(ctx) }))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = conn.Close() })
|
||||
return NewClient(conn)
|
||||
}
|
||||
|
||||
func TestSourceStoreOverTheWire(t *testing.T) {
|
||||
ctx := t.Context()
|
||||
c := remoteSources(t, memSources{})
|
||||
stamp := time.Date(2026, 9, 24, 9, 0, 0, 0, time.UTC)
|
||||
in := source.Source{Path: "sentry", Signing: source.SigningSigned, Secret: "k", CreatedAt: stamp, UpdatedAt: stamp}
|
||||
if err := c.InsertSource(ctx, in); err != nil {
|
||||
t.Fatalf("InsertSource() error = %v", err)
|
||||
}
|
||||
got, err := c.GetSource(ctx, "sentry")
|
||||
if err != nil || got == nil || *got != in {
|
||||
t.Fatalf("GetSource() = %+v, %v; want %+v", got, err, in)
|
||||
}
|
||||
if missing, err := c.GetSource(ctx, "nope"); err != nil || missing != nil {
|
||||
t.Fatalf("GetSource(unknown) = %+v, %v; want nil, nil", missing, err)
|
||||
}
|
||||
if err := c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsignedPending); err != nil {
|
||||
t.Fatalf("SetSourceSigning() error = %v", err)
|
||||
}
|
||||
if err := c.SetSourceSecret(ctx, "sentry", "k2"); err != nil {
|
||||
t.Fatalf("SetSourceSecret() error = %v", err)
|
||||
}
|
||||
list, err := c.ListSources(ctx)
|
||||
if err != nil || len(list) != 1 || list[0].Signing != source.SigningUnsignedPending || list[0].Secret != "k2" {
|
||||
t.Fatalf("ListSources() = %+v, %v", list, err)
|
||||
}
|
||||
|
||||
errs := []struct {
|
||||
name string
|
||||
call func() error
|
||||
want error
|
||||
}{
|
||||
{"taken path", func() error { return c.InsertSource(ctx, in) }, storecontract.ErrSourcePathTaken},
|
||||
{"stale signing", func() error {
|
||||
return c.SetSourceSigning(ctx, "sentry", source.SigningSigned, source.SigningUnsigned)
|
||||
}, storecontract.ErrSourceSigningStale},
|
||||
{"unknown path", func() error { return c.SetSourceSecret(ctx, "nope", "k") }, storecontract.ErrSourceNotFound},
|
||||
}
|
||||
for _, tt := range errs {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if err := tt.call(); !errors.Is(err, tt.want) {
|
||||
t.Fatalf("error = %v, want %v", err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceStoreUnavailableWithoutBackend(t *testing.T) {
|
||||
c := remoteSources(t, nil)
|
||||
_, err := c.ListSources(t.Context())
|
||||
if status.Code(err) != codes.Unavailable {
|
||||
t.Fatalf("ListSources() with no backend = %v, want Unavailable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCapturedEventUnsignedSurvivesTheWire(t *testing.T) {
|
||||
in := storecontract.CapturedEvent{ID: "c", Source: "fw", Unsigned: true}
|
||||
if got := capturedEventValue(capturedEventProto(in)); got != in {
|
||||
t.Fatalf("round trip = %+v, want %+v", got, in)
|
||||
}
|
||||
}
|
||||
@@ -97,14 +97,14 @@ func TestCaptureStreamsCarryTheAdminToken(t *testing.T) {
|
||||
// public draft -> pending_approval -> armed lifecycle.
|
||||
id, err := admin.InsertBinding(ctx, binding.Binding{
|
||||
Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := admin.UpdateBinding(ctx, binding.Binding{
|
||||
ID: id, Name: "large binding", Matcher: binding.Matcher{Source: "large"},
|
||||
MappingID: mappingID, Workflow: "implement", Secret: "0123456789abcdef0123456789abcdef",
|
||||
MappingID: mappingID, Workflow: "implement",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
"github.com/samcharles93/archie-core/internal/domain/eventtype"
|
||||
"github.com/samcharles93/archie-core/internal/domain/mapping"
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
"github.com/samcharles93/archie-core/internal/domain/workflow/task"
|
||||
"github.com/samcharles93/archie-core/internal/events"
|
||||
@@ -151,6 +152,7 @@ func capturedEventProto(c storecontract.CapturedEvent) *pb.CapturedEvent {
|
||||
Id: c.ID, ReceivedAt: timestamp(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
|
||||
Unsigned: c.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -162,6 +164,24 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
|
||||
ID: c.Id, ReceivedAt: timeValue(c.ReceivedAt), Source: c.Source,
|
||||
RemoteAddr: c.RemoteAddr, ContentType: c.ContentType, Headers: c.Headers,
|
||||
Body: c.Body, Authenticated: c.Authenticated, EventType: c.EventType,
|
||||
Unsigned: c.Unsigned,
|
||||
}
|
||||
}
|
||||
|
||||
func sourceProto(s source.Source) *pb.Source {
|
||||
return &pb.Source{
|
||||
Path: s.Path, Signing: string(s.Signing), Secret: s.Secret,
|
||||
CreatedAt: timestamp(s.CreatedAt), UpdatedAt: timestamp(s.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func sourceValue(s *pb.Source) source.Source {
|
||||
if s == nil {
|
||||
return source.Source{}
|
||||
}
|
||||
return source.Source{
|
||||
Path: s.Path, Signing: source.Signing(s.Signing), Secret: s.Secret,
|
||||
CreatedAt: timeValue(s.CreatedAt), UpdatedAt: timeValue(s.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -199,7 +219,7 @@ func bindingProto(b binding.Binding) *pb.Binding {
|
||||
return &pb.Binding{
|
||||
Id: b.ID, Name: b.Name, Matcher: &pb.BindingMatcher{Source: b.Matcher.Source},
|
||||
MappingId: b.MappingID, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int64(b.Version), Status: string(b.Status), Secret: b.Secret,
|
||||
Version: int64(b.Version), Status: string(b.Status),
|
||||
CreatedAt: timestamp(b.CreatedAt), UpdatedAt: timestamp(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -215,7 +235,7 @@ func bindingValue(b *pb.Binding) binding.Binding {
|
||||
return binding.Binding{
|
||||
ID: b.Id, Name: b.Name, Matcher: binding.Matcher{Source: source},
|
||||
MappingID: b.MappingId, Workflow: b.Workflow, Owner: b.Owner, Repo: b.Repo,
|
||||
Version: int(b.Version), Status: binding.Status(b.Status), Secret: b.Secret,
|
||||
Version: int(b.Version), Status: binding.Status(b.Status),
|
||||
CreatedAt: timeValue(b.CreatedAt), UpdatedAt: timeValue(b.UpdatedAt),
|
||||
}
|
||||
}
|
||||
@@ -274,6 +294,9 @@ const (
|
||||
msgBindingOverlap = "binding overlap"
|
||||
msgBindingTransition = "binding transition rejected"
|
||||
msgAlreadyDispatched = "already dispatched"
|
||||
msgSourceNotFound = "source not found"
|
||||
msgSourcePathTaken = "source path taken"
|
||||
msgSourceSigning = "source signing stale"
|
||||
msgInternal = "state store: internal error"
|
||||
// msgTaskLogsUnavailable is the public phrase for "this service has no
|
||||
// task-log reader". It is a wire contract like the sentinels above: the
|
||||
@@ -306,28 +329,12 @@ func mapError(err error) error {
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return status.Error(codes.DeadlineExceeded, context.DeadlineExceeded.Error())
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrStaleTransition):
|
||||
return status.Error(codes.FailedPrecondition, msgStaleTransition)
|
||||
case errors.Is(err, storecontract.ErrBindingNotFound):
|
||||
return status.Error(codes.NotFound, msgBindingNotFound)
|
||||
case errors.Is(err, storecontract.ErrMappingNotFound):
|
||||
return status.Error(codes.NotFound, msgMappingNotFound)
|
||||
case errors.Is(err, storecontract.ErrEventTypeNotFound):
|
||||
return status.Error(codes.NotFound, msgEventTypeNotFound)
|
||||
case errors.Is(err, eventtype.ErrOverlap):
|
||||
return status.Error(codes.FailedPrecondition, msgEventTypeOverlap)
|
||||
case errors.Is(err, eventtype.ErrInvalid):
|
||||
return status.Error(codes.InvalidArgument, msgEventTypeInvalid)
|
||||
case errors.Is(err, storecontract.ErrBindingOverlap):
|
||||
return status.Error(codes.FailedPrecondition, msgBindingOverlap)
|
||||
case errors.Is(err, storecontract.ErrBindingTransition):
|
||||
return status.Error(codes.FailedPrecondition, msgBindingTransition)
|
||||
case errors.Is(err, storecontract.ErrAlreadyDispatched):
|
||||
return status.Error(codes.AlreadyExists, msgAlreadyDispatched)
|
||||
default:
|
||||
return status.Error(codes.Internal, msgInternal)
|
||||
for _, w := range wireErrors {
|
||||
if errors.Is(err, w.sentinel) {
|
||||
return status.Error(w.code, w.message)
|
||||
}
|
||||
}
|
||||
return status.Error(codes.Internal, msgInternal)
|
||||
}
|
||||
|
||||
// unmapError rehydrates a gRPC status error back to the store sentinel it
|
||||
@@ -382,21 +389,38 @@ type wireStatus struct {
|
||||
message string
|
||||
}
|
||||
|
||||
// wireSentinels is the (code, canonical message) to sentinel table
|
||||
// sentinelForStatus reads.
|
||||
var wireSentinels = map[wireStatus]error{
|
||||
{codes.FailedPrecondition, msgStaleTransition}: storecontract.ErrStaleTransition,
|
||||
{codes.FailedPrecondition, msgBindingOverlap}: storecontract.ErrBindingOverlap,
|
||||
{codes.FailedPrecondition, msgBindingTransition}: storecontract.ErrBindingTransition,
|
||||
{codes.FailedPrecondition, msgEventTypeOverlap}: eventtype.ErrOverlap,
|
||||
{codes.InvalidArgument, msgEventTypeInvalid}: eventtype.ErrInvalid,
|
||||
{codes.NotFound, msgBindingNotFound}: storecontract.ErrBindingNotFound,
|
||||
{codes.NotFound, msgMappingNotFound}: storecontract.ErrMappingNotFound,
|
||||
{codes.NotFound, msgEventTypeNotFound}: storecontract.ErrEventTypeNotFound,
|
||||
{codes.AlreadyExists, msgAlreadyDispatched}: storecontract.ErrAlreadyDispatched,
|
||||
{codes.Unavailable, msgTaskLogsUnavailable}: logging.ErrTaskLogsUnavailable,
|
||||
// wireErrors pairs each sentinel with its canonical (code, message). mapError
|
||||
// reads it forward and sentinelForStatus backward, so the two directions
|
||||
// cannot drift.
|
||||
var wireErrors = []struct {
|
||||
sentinel error
|
||||
code codes.Code
|
||||
message string
|
||||
}{
|
||||
{storecontract.ErrStaleTransition, codes.FailedPrecondition, msgStaleTransition},
|
||||
{storecontract.ErrBindingOverlap, codes.FailedPrecondition, msgBindingOverlap},
|
||||
{storecontract.ErrBindingTransition, codes.FailedPrecondition, msgBindingTransition},
|
||||
{storecontract.ErrSourceSigningStale, codes.FailedPrecondition, msgSourceSigning},
|
||||
{eventtype.ErrOverlap, codes.FailedPrecondition, msgEventTypeOverlap},
|
||||
{eventtype.ErrInvalid, codes.InvalidArgument, msgEventTypeInvalid},
|
||||
{storecontract.ErrBindingNotFound, codes.NotFound, msgBindingNotFound},
|
||||
{storecontract.ErrMappingNotFound, codes.NotFound, msgMappingNotFound},
|
||||
{storecontract.ErrEventTypeNotFound, codes.NotFound, msgEventTypeNotFound},
|
||||
{storecontract.ErrSourceNotFound, codes.NotFound, msgSourceNotFound},
|
||||
{storecontract.ErrAlreadyDispatched, codes.AlreadyExists, msgAlreadyDispatched},
|
||||
{storecontract.ErrSourcePathTaken, codes.AlreadyExists, msgSourcePathTaken},
|
||||
{logging.ErrTaskLogsUnavailable, codes.Unavailable, msgTaskLogsUnavailable},
|
||||
}
|
||||
|
||||
// wireSentinels indexes wireErrors by (code, canonical message).
|
||||
var wireSentinels = func() map[wireStatus]error {
|
||||
m := make(map[wireStatus]error, len(wireErrors))
|
||||
for _, w := range wireErrors {
|
||||
m[wireStatus{w.code, w.message}] = w.sentinel
|
||||
}
|
||||
return m
|
||||
}()
|
||||
|
||||
// configSnapshotProto and configSnapshotValue carry the dashboard's
|
||||
// configuration projection. document crosses as bytes, unread by either side
|
||||
// of this hop: the store holds it and the page renders it.
|
||||
|
||||
@@ -21,9 +21,15 @@ type bindingRequest struct {
|
||||
// for multi-repo deployments. Both empty is valid (falls back to the
|
||||
// daemon's single-configured-repo behaviour); binding.Validate
|
||||
// rejects setting only one.
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
Secret string `json:"secret"`
|
||||
Owner string `json:"owner"`
|
||||
Repo string `json:"repo"`
|
||||
}
|
||||
|
||||
// bindingView is a listed binding with its source's signing state, so the
|
||||
// list can flag a binding that dispatches unsigned events.
|
||||
type bindingView struct {
|
||||
binding.Binding
|
||||
Unsigned bool `json:"unsigned"`
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -37,8 +43,17 @@ func (s *Server) handleBindingsList(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
stripBindingSecrets(bindings)
|
||||
writeJSON(w, map[string]any{"bindings": bindings})
|
||||
unsigned, err := s.unsignedSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list sources", "err", err)
|
||||
http.Error(w, "list bindings failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
views := make([]bindingView, 0, len(bindings))
|
||||
for _, b := range bindings {
|
||||
views = append(views, bindingView{Binding: b, Unsigned: unsigned[b.Matcher.Source]})
|
||||
}
|
||||
writeJSON(w, map[string]any{"bindings": views})
|
||||
}
|
||||
|
||||
func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -70,7 +85,6 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
Secret: req.Secret,
|
||||
Status: binding.StatusPendingApproval,
|
||||
}
|
||||
if err := b.Validate(); err != nil {
|
||||
@@ -93,7 +107,6 @@ func (s *Server) handleBindingCreate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "create binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
created.Secret = ""
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, created)
|
||||
}
|
||||
@@ -118,7 +131,6 @@ func (s *Server) handleBindingGet(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "binding not found", http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
b.Secret = ""
|
||||
writeJSON(w, b)
|
||||
}
|
||||
|
||||
@@ -157,9 +169,8 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
Workflow: req.Workflow,
|
||||
Owner: req.Owner,
|
||||
Repo: req.Repo,
|
||||
Secret: req.Secret,
|
||||
}
|
||||
if err := b.ValidateForUpdate(); err != nil {
|
||||
if err := b.Validate(); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
@@ -181,7 +192,6 @@ func (s *Server) handleBindingUpdate(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "update binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated.Secret = ""
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
@@ -243,15 +253,5 @@ func (s *Server) handleBindingApprove(w http.ResponseWriter, r *http.Request) {
|
||||
http.Error(w, "approve binding failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
updated.Secret = ""
|
||||
writeJSON(w, updated)
|
||||
}
|
||||
|
||||
// stripBindingSecrets zeroes the Secret field on every binding in the slice
|
||||
// so the list handler never leaks a shared HMAC secret through /api/bindings.
|
||||
// Single-binding reads do the same inline; this covers the list path.
|
||||
func stripBindingSecrets(bs []binding.Binding) {
|
||||
for i := range bs {
|
||||
bs[i].Secret = ""
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/binding"
|
||||
@@ -52,16 +51,13 @@ func seedMapping(t *testing.T, srv *Server, name string) string {
|
||||
}
|
||||
|
||||
// validBindingRequest returns a populated bindingRequest that passes
|
||||
// binding.Validate and server-side workflow validation. The Secret is 32
|
||||
// bytes (above the 16-byte floor) so length never accidentally trips
|
||||
// validation in a test that isn't about secret length.
|
||||
// binding.Validate and server-side workflow validation.
|
||||
func validBindingRequest(suffix, source, mappingID string) map[string]any {
|
||||
return map[string]any{
|
||||
"name": "binding " + suffix,
|
||||
"matcher": map[string]any{"source": source},
|
||||
"mapping_id": mappingID,
|
||||
"workflow": "implement",
|
||||
"secret": "0123456789abcdef0123456789abcdef",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -83,9 +79,6 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
if created.Status != binding.StatusPendingApproval {
|
||||
t.Fatalf("created.Status = %q, want %q", created.Status, binding.StatusPendingApproval)
|
||||
}
|
||||
if created.Secret != "" {
|
||||
t.Fatalf("created.Secret = %q, want \"\" (response must strip secret)", created.Secret)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/bindings/"+created.ID, nil)
|
||||
if w.Code != http.StatusOK {
|
||||
@@ -98,15 +91,12 @@ func TestHandleBindingCreateAndGet(t *testing.T) {
|
||||
if got.ID != created.ID {
|
||||
t.Fatalf("got.ID = %q, want %q", got.ID, created.ID)
|
||||
}
|
||||
if got.Secret != "" {
|
||||
t.Fatalf("get.Secret = %q, want \"\"", got.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo covers the
|
||||
// multi-repo fix at the API layer: a create/update request carrying
|
||||
// owner/repo persists them, and they're visible in the response
|
||||
// (they're not secret, unlike Secret).
|
||||
// (they're not secret).
|
||||
func TestHandleBindingCreateAndUpdateRoundTripsOwnerRepo(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
@@ -159,34 +149,6 @@ func TestHandleBindingCreateRejectsPartialOwnerRepo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingsListStripsSecrets(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("list status = %d, want %d; body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Bindings []binding.Binding `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("unmarshal: %v", err)
|
||||
}
|
||||
if len(body.Bindings) != 1 {
|
||||
t.Fatalf("bindings = %d, want 1", len(body.Bindings))
|
||||
}
|
||||
if body.Bindings[0].Secret != "" {
|
||||
t.Fatalf("listed Secret = %q, want \"\"", body.Bindings[0].Secret)
|
||||
}
|
||||
// Defence against accidental echo in the raw JSON: the "secret" key
|
||||
// must not appear at all (the binding.Binding tag is omitempty).
|
||||
if strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("list response leaked secret key: %s", w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingCreateRejectsOverlap(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
@@ -220,10 +182,8 @@ func TestHandleBindingCreateRejectsValidationFailure(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
// Short secret trips binding.Validate's length floor regardless of
|
||||
// any store-side check.
|
||||
req := validBindingRequest("a", "sentry", mappingID)
|
||||
req["secret"] = "short"
|
||||
req["name"] = " "
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", req)
|
||||
if w.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d; body = %s", w.Code, http.StatusBadRequest, w.Body.String())
|
||||
@@ -277,35 +237,6 @@ func TestHandleBindingUpdatePreservesOtherFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleBindingUpdateWithEmptySecretPreservesExisting is the API-layer
|
||||
// half of UpdateBinding's own documented contract ("Secret is preserved
|
||||
// when the caller passes an empty string ... so a partial update cannot
|
||||
// erase the HMAC secret"): an edit that never touches the secret field
|
||||
// must not be rejected by Validate's create-time secret-length floor,
|
||||
// since nothing about the existing secret is changing.
|
||||
func TestHandleBindingUpdateWithEmptySecretPreservesExisting(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest("a", "sentry", mappingID))
|
||||
var created binding.Binding
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &created)
|
||||
|
||||
update := validBindingRequest("renamed", "sentry", mappingID)
|
||||
update["secret"] = ""
|
||||
w = doJSON(t, srv, http.MethodPatch, "/api/bindings/"+created.ID, update)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want %d (empty secret must mean 'keep existing', not fail validation); body = %s", w.Code, http.StatusOK, w.Body.String())
|
||||
}
|
||||
|
||||
stored, err := srv.Bindings.GetBinding(t.Context(), created.ID)
|
||||
if err != nil || stored == nil {
|
||||
t.Fatalf("GetBinding: %+v, %v", stored, err)
|
||||
}
|
||||
if stored.Secret != "0123456789abcdef0123456789abcdef" {
|
||||
t.Fatalf("stored secret = %q, want the original secret preserved", stored.Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleBindingApproveArmedRejected(t *testing.T) {
|
||||
srv := bindingTestServer(t)
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// Capture sources and their signing setting (docs/prds/event-automation.md
|
||||
// "Sources"). A secret is returned only by the two writes that generate it,
|
||||
// so the operator can copy it into the sender; every other read withholds it.
|
||||
// Turning signing off is a request plus an approval, both behind the same
|
||||
// mutation gate that arms a binding.
|
||||
|
||||
func (s *Server) handleSourcesList(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
list, err := s.Sources.ListSources(r.Context())
|
||||
if err != nil {
|
||||
s.Log.Error("list sources", "err", err)
|
||||
http.Error(w, "list sources failed", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
for i := range list {
|
||||
list[i].Secret = ""
|
||||
}
|
||||
writeJSON(w, map[string]any{"sources": list})
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceCreate(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var req struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
src, err := source.New(req.Path)
|
||||
if errors.Is(err, source.ErrInvalidPath) {
|
||||
http.Error(w, err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
err = s.Sources.InsertSource(r.Context(), src)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "create source", err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSigning turns signing on at once, or requests turning it off.
|
||||
func (s *Server) handleSourceSigning(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
Signed bool `json:"signed"`
|
||||
}
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "invalid request body: "+err.Error(), http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
transition := (*source.Source).RequestUnsigned
|
||||
if req.Signed {
|
||||
transition = (*source.Source).RequireSigning
|
||||
}
|
||||
s.transitionSource(w, r, transition)
|
||||
}
|
||||
|
||||
func (s *Server) handleSourceApproveUnsigned(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
s.transitionSource(w, r, (*source.Source).ApproveUnsigned)
|
||||
}
|
||||
|
||||
// transitionSource applies one domain signing transition and writes it with
|
||||
// the state it was decided from, so a concurrent change is refused.
|
||||
func (s *Server) transitionSource(w http.ResponseWriter, r *http.Request, transition func(*source.Source) error) {
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
from := src.Signing
|
||||
if err := transition(src); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if err := s.Sources.SetSourceSigning(r.Context(), src.Path, from, src.Signing); err != nil {
|
||||
s.sourceError(w, "set source signing", err)
|
||||
return
|
||||
}
|
||||
src.Secret = ""
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
// handleSourceSecret generates a new secret and returns it once.
|
||||
func (s *Server) handleSourceSecret(w http.ResponseWriter, r *http.Request) {
|
||||
if !s.authorizeTaskMutation(w, r) {
|
||||
return
|
||||
}
|
||||
src, ok := s.loadSource(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
secret, err := source.NewSecret()
|
||||
if err == nil {
|
||||
err = s.Sources.SetSourceSecret(r.Context(), src.Path, secret)
|
||||
}
|
||||
if err != nil {
|
||||
s.sourceError(w, "set source secret", err)
|
||||
return
|
||||
}
|
||||
src.Secret = secret
|
||||
writeJSON(w, src)
|
||||
}
|
||||
|
||||
func (s *Server) loadSource(w http.ResponseWriter, r *http.Request) (*source.Source, bool) {
|
||||
if s.Sources == nil {
|
||||
http.Error(w, "sources not configured", http.StatusServiceUnavailable)
|
||||
return nil, false
|
||||
}
|
||||
src, err := s.Sources.GetSource(r.Context(), r.PathValue("path"))
|
||||
if err != nil {
|
||||
s.sourceError(w, "get source", err)
|
||||
return nil, false
|
||||
}
|
||||
if src == nil {
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
return nil, false
|
||||
}
|
||||
return src, true
|
||||
}
|
||||
|
||||
func (s *Server) sourceError(w http.ResponseWriter, what string, err error) {
|
||||
switch {
|
||||
case errors.Is(err, storecontract.ErrSourcePathTaken):
|
||||
http.Error(w, "source path already taken", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceSigningStale):
|
||||
http.Error(w, "source signing changed; reload and retry", http.StatusConflict)
|
||||
case errors.Is(err, storecontract.ErrSourceNotFound):
|
||||
http.Error(w, "source not found", http.StatusNotFound)
|
||||
default:
|
||||
s.Log.Error(what, "err", err)
|
||||
http.Error(w, what+" failed", http.StatusInternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// unsignedSources is the set of source paths approved to take unsigned
|
||||
// events. With no source store nothing is unsigned.
|
||||
func (s *Server) unsignedSources(ctx context.Context) (map[string]bool, error) {
|
||||
out := map[string]bool{}
|
||||
if s.Sources == nil {
|
||||
return out, nil
|
||||
}
|
||||
list, err := s.Sources.ListSources(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, src := range list {
|
||||
if src.Unsigned() {
|
||||
out[src.Path] = true
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/source"
|
||||
"github.com/samcharles93/archie-core/internal/domain/storecontract"
|
||||
)
|
||||
|
||||
// memSources is an in-memory SourceStore with the store's error contract.
|
||||
type memSources map[string]source.Source
|
||||
|
||||
func (m memSources) InsertSource(_ context.Context, s source.Source) error {
|
||||
if _, ok := m[s.Path]; ok {
|
||||
return storecontract.ErrSourcePathTaken
|
||||
}
|
||||
m[s.Path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) GetSource(_ context.Context, path string) (*source.Source, error) {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return nil, nil
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
func (m memSources) ListSources(context.Context) ([]source.Source, error) {
|
||||
out := make([]source.Source, 0, len(m))
|
||||
for _, s := range m {
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSigning(_ context.Context, path string, from, to source.Signing) error {
|
||||
s, ok := m[path]
|
||||
switch {
|
||||
case !ok:
|
||||
return storecontract.ErrSourceNotFound
|
||||
case s.Signing != from:
|
||||
return storecontract.ErrSourceSigningStale
|
||||
}
|
||||
s.Signing = to
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m memSources) SetSourceSecret(_ context.Context, path, secret string) error {
|
||||
s, ok := m[path]
|
||||
if !ok {
|
||||
return storecontract.ErrSourceNotFound
|
||||
}
|
||||
s.Secret = secret
|
||||
m[path] = s
|
||||
return nil
|
||||
}
|
||||
|
||||
func sourceTestServer(t *testing.T) (*Server, memSources) {
|
||||
t.Helper()
|
||||
srv := bindingTestServer(t)
|
||||
sources := memSources{}
|
||||
srv.Sources = sources
|
||||
return srv, sources
|
||||
}
|
||||
|
||||
func decodeSource(t *testing.T, body []byte) source.Source {
|
||||
t.Helper()
|
||||
var s source.Source
|
||||
if err := json.Unmarshal(body, &s); err != nil {
|
||||
t.Fatalf("unmarshal source: %v; body = %s", err, body)
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func TestSourceCreateDefaultsToSignedUUIDv7AndShowsSecretOnce(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{})
|
||||
if w.Code != http.StatusCreated {
|
||||
t.Fatalf("create status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
created := decodeSource(t, w.Body.Bytes())
|
||||
if id, err := uuid.Parse(created.Path); err != nil || id.Version() != 7 {
|
||||
t.Fatalf("path %q is not a UUIDv7 (%v)", created.Path, err)
|
||||
}
|
||||
if created.Signing != source.SigningSigned || len(created.Secret) != source.MinSecretLen {
|
||||
t.Fatalf("created = %+v, want signed with a generated secret shown once", created)
|
||||
}
|
||||
|
||||
w = doJSON(t, srv, http.MethodGet, "/api/sources", nil)
|
||||
if w.Code != http.StatusOK || strings.Contains(w.Body.String(), created.Secret) || strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("list = %d %s; want the secret withheld", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceCreateRefusesTakenOrUnsafePath(t *testing.T) {
|
||||
srv, _ := sourceTestServer(t)
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": "sentry"}); w.Code != http.StatusCreated {
|
||||
t.Fatalf("first create = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
tests := []struct {
|
||||
path string
|
||||
want int
|
||||
}{
|
||||
{"sentry", http.StatusConflict},
|
||||
{"a/b", http.StatusBadRequest},
|
||||
{"has space", http.StatusBadRequest},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/sources", map[string]any{"path": tt.path}); w.Code != tt.want {
|
||||
t.Errorf("create %q = %d, want %d; body = %s", tt.path, w.Code, tt.want, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceUnsignedNeedsApproval(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned, Secret: "k"}
|
||||
steps := []struct {
|
||||
name, path string
|
||||
body any
|
||||
code int
|
||||
want source.Signing
|
||||
}{
|
||||
{"approve with no request", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningSigned},
|
||||
{"request unsigned", "/api/sources/fw/signing", map[string]any{"signed": false}, http.StatusOK, source.SigningUnsignedPending},
|
||||
{"approve", "/api/sources/fw/approve-unsigned", nil, http.StatusOK, source.SigningUnsigned},
|
||||
{"approve twice", "/api/sources/fw/approve-unsigned", nil, http.StatusConflict, source.SigningUnsigned},
|
||||
{"sign again", "/api/sources/fw/signing", map[string]any{"signed": true}, http.StatusOK, source.SigningSigned},
|
||||
{"unknown source", "/api/sources/nope/signing", map[string]any{"signed": false}, http.StatusNotFound, source.SigningSigned},
|
||||
}
|
||||
for _, st := range steps {
|
||||
w := doJSON(t, srv, http.MethodPost, st.path, st.body)
|
||||
if w.Code != st.code {
|
||||
t.Fatalf("%s: status = %d, want %d; body = %s", st.name, w.Code, st.code, w.Body.String())
|
||||
}
|
||||
if got := sources["fw"].Signing; got != st.want {
|
||||
t.Fatalf("%s: signing = %q, want %q", st.name, got, st.want)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), `"secret"`) {
|
||||
t.Fatalf("%s: response leaked the secret: %s", st.name, w.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceRegenerateSecret(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningSigned}
|
||||
w := doJSON(t, srv, http.MethodPost, "/api/sources/fw/secret", nil)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
got := decodeSource(t, w.Body.Bytes())
|
||||
if len(got.Secret) != source.MinSecretLen || sources["fw"].Secret != got.Secret {
|
||||
t.Fatalf("secret = %q (stored %q), want a new stored secret shown once", got.Secret, sources["fw"].Secret)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSourceMutationsRequireCSRFHeader(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsignedPending}
|
||||
for _, path := range []string{"/api/sources", "/api/sources/fw/signing", "/api/sources/fw/approve-unsigned", "/api/sources/fw/secret"} {
|
||||
if w := doJSONNoCSRF(t, srv, http.MethodPost, path, map[string]any{}); w.Code != http.StatusForbidden {
|
||||
t.Errorf("%s without CSRF = %d, want %d", path, w.Code, http.StatusForbidden)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindingListMarksUnsignedSources(t *testing.T) {
|
||||
srv, sources := sourceTestServer(t)
|
||||
sources["fw"] = source.Source{Path: "fw", Signing: source.SigningUnsigned}
|
||||
sources["sentry"] = source.Source{Path: "sentry", Signing: source.SigningSigned}
|
||||
mappingID := seedMapping(t, srv, "m")
|
||||
for _, src := range []string{"fw", "sentry"} {
|
||||
if w := doJSON(t, srv, http.MethodPost, "/api/bindings", validBindingRequest(src, src, mappingID)); w.Code != http.StatusCreated {
|
||||
t.Fatalf("create binding = %d; body = %s", w.Code, w.Body.String())
|
||||
}
|
||||
}
|
||||
w := doJSON(t, srv, http.MethodGet, "/api/bindings", nil)
|
||||
var body struct {
|
||||
Bindings []struct {
|
||||
Matcher struct{ Source string } `json:"matcher"`
|
||||
Unsigned bool `json:"unsigned"`
|
||||
} `json:"bindings"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || len(body.Bindings) != 2 {
|
||||
t.Fatalf("list = %s (%v)", w.Body.String(), err)
|
||||
}
|
||||
for _, b := range body.Bindings {
|
||||
if want := b.Matcher.Source == "fw"; b.Unsigned != want {
|
||||
t.Errorf("binding on %q unsigned = %v, want %v", b.Matcher.Source, b.Unsigned, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -156,6 +156,11 @@ type Server struct {
|
||||
// /api/bindings route answer 503 rather than the dashboard failing to start.
|
||||
Bindings storecontract.BindingStore
|
||||
|
||||
// Sources persists capture sources and their signing setting
|
||||
// (docs/prds/event-automation.md "Sources"). Optional: nil makes every
|
||||
// /api/sources route answer 503 and marks no binding unsigned.
|
||||
Sources storecontract.SourceStore
|
||||
|
||||
// TelegramUpdateReportPath and TelegramUpdateChatID let a dashboard-
|
||||
// initiated update use the same post-restart notification route as a
|
||||
// Telegram-initiated update. The web UI has no durable chat identity, so
|
||||
@@ -274,6 +279,11 @@ func (s *Server) registerMappingAndBindingRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("PATCH /api/bindings/{id}", s.handleBindingUpdate)
|
||||
mux.HandleFunc("DELETE /api/bindings/{id}", s.handleBindingDelete)
|
||||
mux.HandleFunc("POST /api/bindings/{id}/approve", s.handleBindingApprove)
|
||||
mux.HandleFunc("GET /api/sources", s.handleSourcesList)
|
||||
mux.HandleFunc("POST /api/sources", s.handleSourceCreate)
|
||||
mux.HandleFunc("POST /api/sources/{path}/signing", s.handleSourceSigning)
|
||||
mux.HandleFunc("POST /api/sources/{path}/approve-unsigned", s.handleSourceApproveUnsigned)
|
||||
mux.HandleFunc("POST /api/sources/{path}/secret", s.handleSourceSecret)
|
||||
}
|
||||
|
||||
func (s *Server) registerConfigAndLogRoutes(mux *http.ServeMux) {
|
||||
|
||||
Reference in new issue
Block a user