fix(webhook): authorize delivery against the source's org

This commit is contained in:
sam committed 2026-10-08 21:43:28 +11:00
1 parent f94d386e29
commit 3d7aa337d5
9 files changed
+166 -14

No files matched your search

+23 -4
View File
@@ -2988,8 +2988,11 @@ type Source struct {
UpdatedAt *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"`
Name string `protobuf:"bytes,6,opt,name=name,proto3" json:"name,omitempty"`
DeliveryHeader string `protobuf:"bytes,7,opt,name=delivery_header,json=deliveryHeader,proto3" json:"delivery_header,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
// org_id and workspace_id are the source's owning org; read-only here.
OrgId string `protobuf:"bytes,8,opt,name=org_id,json=orgId,proto3" json:"org_id,omitempty"`
WorkspaceId string `protobuf:"bytes,9,opt,name=workspace_id,json=workspaceId,proto3" json:"workspace_id,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *Source) Reset() {
@@ -3071,6 +3074,20 @@ func (x *Source) GetDeliveryHeader() string {
return ""
}
func (x *Source) GetOrgId() string {
if x != nil {
return x.OrgId
}
return ""
}
func (x *Source) GetWorkspaceId() string {
if x != nil {
return x.WorkspaceId
}
return ""
}
// WorkflowStat mirrors storecontract.WorkflowStat.
type WorkflowStat struct {
state protoimpl.MessageState `protogen:"open.v1"`
@@ -15424,7 +15441,7 @@ const file_state_v1_state_proto_rawDesc = "" +
"\n" +
"repo_param\x18\x0f \x01(\tR\trepoParam\x12\x15\n" +
"\x06org_id\x18\x10 \x01(\tR\x05orgIdJ\x04\b\n" +
"\x10\vR\x06secret\"\x81\x02\n" +
"\x10\vR\x06secret\"\xbb\x02\n" +
"\x06Source\x12\x12\n" +
"\x04path\x18\x01 \x01(\tR\x04path\x12\x18\n" +
"\asigning\x18\x02 \x01(\tR\asigning\x12\x16\n" +
@@ -15434,7 +15451,9 @@ const file_state_v1_state_proto_rawDesc = "" +
"\n" +
"updated_at\x18\x05 \x01(\v2\x1a.google.protobuf.TimestampR\tupdatedAt\x12\x12\n" +
"\x04name\x18\x06 \x01(\tR\x04name\x12'\n" +
"\x0fdelivery_header\x18\a \x01(\tR\x0edeliveryHeader\"\x84\x02\n" +
"\x0fdelivery_header\x18\a \x01(\tR\x0edeliveryHeader\x12\x15\n" +
"\x06org_id\x18\b \x01(\tR\x05orgId\x12!\n" +
"\fworkspace_id\x18\t \x01(\tR\vworkspaceId\"\x84\x02\n" +
"\fWorkflowStat\x12\x1a\n" +
"\bworkflow\x18\x01 \x01(\tR\bworkflow\x12\x12\n" +
"\x04runs\x18\x02 \x01(\x03R\x04runs\x12\x16\n" +
+7 -2
View File
@@ -5,6 +5,8 @@ package source
import (
"errors"
"time"
"github.com/samcharles93/archie-core/internal/domain/org"
)
// Signing is a source's signing state. A source is signed by default; turning
@@ -35,11 +37,14 @@ var (
// 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.
// creation. Secret is the HMAC key a signed sender signs with. OrgID is the
// org that owns the source, set from the acting org on creation.
type Source struct {
Path string `json:"path"`
// Name is the operator's label; Path stays the source's identity.
Name string `json:"name,omitempty"`
Name string `json:"name,omitempty"`
OrgID org.OrgID `json:"org_id,omitempty"`
WorkspaceID org.WorkspaceID `json:"workspace_id,omitempty"`
// DeliveryHeader is the header the sender repeats unchanged on every
// retry of one delivery, so a retry dispatches no second run. Empty
// counts every arrival as its own delivery.
@@ -14,10 +14,15 @@ func TestAuthorizeDelivery(t *testing.T) {
ID: "github-only", Level: access.LevelObject, OrgID: org.DefaultOrgID, ObjectKind: access.KindSource, ObjectID: "github",
Text: `permit(principal, action == Archie::Action::"deliver", resource) when { context.addr.isInRange(ip("140.82.112.0/20")) };`,
}
acmeOnly := access.Policy{
ID: "acme-only", Level: access.LevelObject, OrgID: "acme", ObjectKind: access.KindSource, ObjectID: "hook",
Text: `permit(principal, action == Archie::Action::"deliver", resource) when { context.addr.isInRange(ip("10.0.0.0/8")) };`,
}
shipped := access.ShippedOrgPolicies(org.DefaultOrgID)
tests := []struct {
name string
org org.OrgID
policies []access.Policy
source string
addr string
@@ -29,6 +34,9 @@ func TestAuthorizeDelivery(t *testing.T) {
{name: "source policy refuses another sender", policies: append(shipped, sourceOnly), source: "github", addr: "203.0.113.9"},
{name: "source policy admits its sender", policies: append(shipped, sourceOnly), source: "github", addr: "140.82.112.5", allowed: true},
{name: "source policy leaves other sources alone", policies: append(shipped, sourceOnly), source: "ci", addr: "203.0.113.9", allowed: true},
{name: "other org's source policy refuses an out-of-range sender", org: "acme", policies: append(shipped, acmeOnly), source: "hook", addr: "203.0.113.9"},
{name: "other org's source policy admits its sender", org: "acme", policies: append(shipped, acmeOnly), source: "hook", addr: "10.1.2.3", allowed: true},
{name: "other org's source policy leaves the default org alone", policies: append(shipped, acmeOnly), source: "hook", addr: "203.0.113.9", allowed: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -36,7 +44,11 @@ func TestAuthorizeDelivery(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if got := engine.AuthorizeDelivery(org.DefaultOrgID, tt.source, tt.addr); got.Allowed != tt.allowed {
acting := tt.org
if acting == "" {
acting = org.DefaultOrgID
}
if got := engine.AuthorizeDelivery(acting, tt.source, tt.addr); got.Allowed != tt.allowed {
t.Fatalf("allowed = %v, want %v (%+v)", got.Allowed, tt.allowed, got)
}
})
@@ -0,0 +1,98 @@
package captureintake
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/source"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
type stubSources struct {
byPath map[string]*source.Source
}
func (s stubSources) GetSource(_ context.Context, path string) (*source.Source, error) {
return s.byPath[path], nil
}
type stubCaptures struct {
stored int
}
func (s *stubCaptures) InsertCapture(_ context.Context, _ storecontract.CapturedEvent, _ time.Duration, _ int) (string, error) {
s.stored++
return "capture-1", nil
}
func (s *stubCaptures) ListCaptures(_ context.Context, _ int) ([]storecontract.CapturedEvent, error) {
return nil, nil
}
type stubDelivery struct {
orgID org.OrgID
allow bool
}
func (s *stubDelivery) AuthorizeDelivery(orgID org.OrgID, _, _ string) access.Decision {
s.orgID = orgID
return access.Decision{Allowed: s.allow}
}
// Delivery runs against the source's owning org, falling back to the
// default org when the source is unknown.
func TestDeliveryUsesSourceOrg(t *testing.T) {
newReceiver := func(delivery *stubDelivery) (*Receiver, *stubCaptures) {
captures := &stubCaptures{}
return &Receiver{
Captures: captures,
Sources: stubSources{byPath: map[string]*source.Source{
"acme-hook": {Path: "acme-hook", Signing: source.SigningUnsigned, OrgID: "acme"},
}},
Retention: time.Hour, MaxEvents: 10,
Delivery: delivery,
}, captures
}
post := func(rc *Receiver, path string) *httptest.ResponseRecorder {
mux := http.NewServeMux()
rc.Register(mux)
request := httptest.NewRequestWithContext(context.Background(), http.MethodPost, "/webhooks/capture/"+path, strings.NewReader("{}"))
request.RemoteAddr = "203.0.113.9:1234"
response := httptest.NewRecorder()
mux.ServeHTTP(response, request)
return response
}
delivery := &stubDelivery{allow: true}
rc, _ := newReceiver(delivery)
if response := post(rc, "acme-hook"); response.Code != http.StatusAccepted {
t.Fatalf("capture: %d %s", response.Code, response.Body.String())
}
if delivery.orgID != "acme" {
t.Fatalf("authorized against %q, want acme", delivery.orgID)
}
delivery = &stubDelivery{allow: true}
rc, _ = newReceiver(delivery)
if response := post(rc, "unknown"); response.Code != http.StatusAccepted {
t.Fatalf("capture: %d %s", response.Code, response.Body.String())
}
if delivery.orgID != org.DefaultOrgID {
t.Fatalf("authorized against %q, want the default org", delivery.orgID)
}
delivery = &stubDelivery{}
rc, captures := newReceiver(delivery)
if response := post(rc, "acme-hook"); response.Code != http.StatusForbidden {
t.Fatalf("refused capture: %d %s", response.Code, response.Body.String())
}
if captures.stored != 0 {
t.Fatalf("refused delivery stored %d captures", captures.stored)
}
}
@@ -86,13 +86,16 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
return
}
if rc.refused(r, path) {
// Resolved before the delivery check so the check runs against the
// source's owning org, not always the default org. An unknown source
// authorizes as the default org.
src := rc.resolveSource(r, path)
if rc.refused(r, path, orgOf(src)) {
http.Error(w, "forbidden", http.StatusForbidden)
return
}
src := rc.resolveSource(r, path)
r.Body = http.MaxBytesReader(w, r.Body, maxBodyBytesOrFallback(rc.MaxBodyBytes))
body, err := io.ReadAll(r.Body)
if err != nil {
@@ -157,12 +160,12 @@ func (rc *Receiver) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// refused applies the network rules before the body is read. A refused event
// is not stored, only counted on its source with the sender's address.
func (rc *Receiver) refused(r *http.Request, path string) bool {
func (rc *Receiver) refused(r *http.Request, path string, owner org.OrgID) bool {
if rc.Delivery == nil {
return false
}
addr := remoteAddrHost(r)
if rc.Delivery.AuthorizeDelivery(org.DefaultOrgID, path, addr).Allowed {
if rc.Delivery.AuthorizeDelivery(owner, path, addr).Allowed {
return false
}
if rc.Refusals != nil {
@@ -173,6 +176,15 @@ func (rc *Receiver) refused(r *http.Request, path string) bool {
return true
}
// orgOf reports the org that owns src, or the default org when the source
// is unknown: an unknown source has no owner to authorize against.
func orgOf(src *source.Source) org.OrgID {
if src == nil || src.OrgID == "" {
return org.DefaultOrgID
}
return src.OrgID
}
// 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
@@ -34,11 +34,11 @@ func TestCaptureCountPruneStaysInOrg(t *testing.T) {
return id
}
// Quiet org first: its captures must survive the loud org's volume.
for i := 0; i < 2; i++ {
for i := range 2 {
insert("prune-b", base.Add(time.Duration(i)*time.Second))
}
var loud []string
for i := 0; i < 5; i++ {
for i := range 5 {
loud = append(loud, insert("prune-a", base.Add(time.Duration(10+i)*time.Second)))
}
count := func(owner string) int {
@@ -171,6 +171,7 @@ func (s *EDA) sourceValue(r postgresdb.Source) (source.Source, error) {
}
return source.Source{
Path: r.Path, Name: r.Name, DeliveryHeader: r.DeliveryHeader, Signing: source.Signing(r.Signing), Secret: secret,
OrgID: org.OrgID(r.OrgID), WorkspaceID: org.WorkspaceID(r.WorkspaceID),
CreatedAt: r.CreatedAt, UpdatedAt: r.UpdatedAt,
}, nil
}
@@ -212,6 +212,7 @@ func capturedEventValue(c *pb.CapturedEvent) storecontract.CapturedEvent {
func sourceProto(s source.Source) *pb.Source {
return &pb.Source{
Path: s.Path, Name: s.Name, DeliveryHeader: s.DeliveryHeader, Signing: string(s.Signing), Secret: s.Secret,
OrgId: string(s.OrgID), WorkspaceId: string(s.WorkspaceID),
CreatedAt: timestamp(s.CreatedAt), UpdatedAt: timestamp(s.UpdatedAt),
}
}
@@ -222,6 +223,7 @@ func sourceValue(s *pb.Source) source.Source {
}
return source.Source{
Path: s.Path, Name: s.Name, DeliveryHeader: s.DeliveryHeader, Signing: source.Signing(s.Signing), Secret: s.Secret,
OrgID: org.OrgID(s.OrgId), WorkspaceID: org.WorkspaceID(s.WorkspaceId),
CreatedAt: timeValue(s.CreatedAt), UpdatedAt: timeValue(s.UpdatedAt),
}
}
+3
View File
@@ -571,6 +571,9 @@ message Source {
google.protobuf.Timestamp updated_at = 5;
string name = 6;
string delivery_header = 7;
// org_id and workspace_id are the source's owning org; read-only here.
string org_id = 8;
string workspace_id = 9;
}
// WorkflowStat mirrors storecontract.WorkflowStat.