forked from mtusi2026/mtusi2026lab7
Prepare verified laboratory 7 implementation and evidence
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrClientConfiguration = errors.New("separate broker identities required")
|
||||
|
||||
// Clients parses configuration only; connecting/authenticating is deferred to
|
||||
// the native client. No credential or original parser error reaches diagnostics.
|
||||
func Clients(publishURL, consumeURL string) (*redis.Client, *redis.Client, error) {
|
||||
p, e := redis.ParseURL(publishURL)
|
||||
if e != nil {
|
||||
return nil, nil, ErrClientConfiguration
|
||||
}
|
||||
c, e := redis.ParseURL(consumeURL)
|
||||
if e != nil || p.Username == "" || c.Username == "" || p.Username == c.Username {
|
||||
return nil, nil, ErrClientConfiguration
|
||||
}
|
||||
for _, o := range []*redis.Options{p, c} {
|
||||
o.MaxRetries = -1
|
||||
o.DialTimeout = time.Second
|
||||
o.ReadTimeout = 2 * time.Second
|
||||
o.WriteTimeout = time.Second
|
||||
o.PoolSize = 2
|
||||
o.MaxActiveConns = 2
|
||||
o.MaxIdleConns = 1
|
||||
}
|
||||
return redis.NewClient(p), redis.NewClient(c), nil
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"backend/internal/config"
|
||||
"backend/internal/domain/model"
|
||||
"context"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"net/url"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRealValkeyRejectsCrossRoleCommands(t *testing.T) {
|
||||
if os.Getenv("RUN_BROKER_ACL_TESTS") != "1" {
|
||||
t.Skip("explicit isolated Valkey admin required")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
raw, e := config.ReadSecret("/run/secrets/cache_url")
|
||||
if e != nil {
|
||||
t.Fatal("admin file unavailable")
|
||||
}
|
||||
opts, e := redis.ParseURL(raw)
|
||||
if e != nil {
|
||||
t.Fatal("admin config invalid")
|
||||
}
|
||||
opts.MaxRetries = -1
|
||||
admin := redis.NewClient(opts)
|
||||
defer closeRedis(t, admin)
|
||||
names, e := admin.ACLUsers(ctx).Result()
|
||||
if e != nil {
|
||||
t.Fatal("temporary ACL inventory failed")
|
||||
}
|
||||
owned := regexp.MustCompile(`^vp7_(pub|con)_[a-f0-9]{32}$`)
|
||||
for _, name := range names {
|
||||
if owned.MatchString(name) {
|
||||
if e = admin.Do(ctx, "ACL", "DELUSER", name).Err(); e != nil {
|
||||
t.Fatal("prior temporary ACL cleanup failed")
|
||||
}
|
||||
}
|
||||
}
|
||||
u, e := url.Parse(raw)
|
||||
if e != nil {
|
||||
t.Fatal("broker URL invalid")
|
||||
}
|
||||
suffix := strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
pubName, conName := "vp7_pub_"+suffix, "vp7_con_"+suffix
|
||||
password := uuid.NewString()
|
||||
defer func() {
|
||||
c, stop := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer stop()
|
||||
if e := admin.Do(c, "ACL", "DELUSER", pubName, conName).Err(); e != nil {
|
||||
t.Error("temporary ACL cleanup failed")
|
||||
}
|
||||
}()
|
||||
for _, role := range []struct {
|
||||
name string
|
||||
commands []string
|
||||
}{{pubName, []string{"+xadd"}}, {conName, []string{"+xgroup", "+xreadgroup", "+xautoclaim", "+xack", "+xdel"}}} {
|
||||
args := []any{"ACL", "SETUSER", role.name, "reset", "on", ">" + password, "~attachment-jobs", "+hello", "+ping", "+select", "+client|setinfo"}
|
||||
for _, command := range role.commands {
|
||||
args = append(args, command)
|
||||
}
|
||||
if e = admin.Do(ctx, args...).Err(); e != nil {
|
||||
t.Fatal("temporary ACL setup failed")
|
||||
}
|
||||
}
|
||||
u.User = url.UserPassword(pubName, password)
|
||||
pubURL := u.String()
|
||||
u.User = url.UserPassword(conName, password)
|
||||
p, c, e := Clients(pubURL, u.String())
|
||||
if e != nil {
|
||||
t.Fatal("separate clients rejected")
|
||||
}
|
||||
defer closeRedis(t, p)
|
||||
defer closeRedis(t, c)
|
||||
j := model.Job{ID: uuid.New(), AttachmentID: uuid.New(), PipelineVersion: 1, CreatedAt: time.Now()}
|
||||
s := &publishStore{j: j}
|
||||
b := New(p, c, s, "synthetic")
|
||||
if e = b.Publish(ctx); e != nil || !s.published {
|
||||
t.Fatal("publisher-only native identity could not publish outbox")
|
||||
}
|
||||
rows, e := admin.XRevRangeN(ctx, stream, "+", "-", 1).Result()
|
||||
if e != nil || len(rows) != 1 || !strings.Contains(rows[0].Values["job"].(string), j.ID.String()) {
|
||||
t.Fatal("owned test publication not found")
|
||||
}
|
||||
defer admin.XDel(context.Background(), stream, rows[0].ID)
|
||||
if e = p.XAck(ctx, stream, "workers", rows[0].ID).Err(); e == nil || !strings.Contains(e.Error(), "NOPERM") {
|
||||
t.Fatal("publisher identity could acknowledge consumer work")
|
||||
}
|
||||
if e = c.XAdd(ctx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"forbidden": "synthetic"}}).Err(); e == nil || !strings.Contains(e.Error(), "NOPERM") {
|
||||
t.Fatal("consumer identity could publish work")
|
||||
}
|
||||
processed := false
|
||||
b.consume(ctx, rows[0], func(context.Context, model.Job) error { processed = true; return nil }, func(error) { t.Error("consumer failed") })
|
||||
if !processed {
|
||||
t.Fatal("native consumer did not accept envelope")
|
||||
}
|
||||
if left, e := admin.XRangeN(ctx, stream, rows[0].ID, rows[0].ID, 1).Result(); e != nil || len(left) != 0 {
|
||||
t.Fatal("native consumer did not delete its acknowledged delivery")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"net"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type commandHook struct {
|
||||
role string
|
||||
mu sync.Mutex
|
||||
commands []string
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
func (h *commandHook) DialHook(redis.DialHook) redis.DialHook {
|
||||
return func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, errors.New("test forbids network")
|
||||
}
|
||||
}
|
||||
func (h *commandHook) ProcessHook(redis.ProcessHook) redis.ProcessHook {
|
||||
return func(_ context.Context, c redis.Cmder) error {
|
||||
h.mu.Lock()
|
||||
defer h.mu.Unlock()
|
||||
name := c.Name()
|
||||
if h.role == "publisher" && name != "xadd" || h.role == "consumer" && name != "xack" && name != "xdel" {
|
||||
h.t.Errorf("%s principal used forbidden command %s", h.role, name)
|
||||
}
|
||||
h.commands = append(h.commands, name)
|
||||
switch v := c.(type) {
|
||||
case *redis.StringCmd:
|
||||
v.SetVal("1-0")
|
||||
case *redis.IntCmd:
|
||||
v.SetVal(1)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
func (h *commandHook) ProcessPipelineHook(redis.ProcessPipelineHook) redis.ProcessPipelineHook {
|
||||
return func(context.Context, []redis.Cmder) error { return errors.New("test forbids implicit pipeline") }
|
||||
}
|
||||
|
||||
type publishStore struct {
|
||||
port.PipelineStore
|
||||
j model.Job
|
||||
published bool
|
||||
}
|
||||
|
||||
func (s *publishStore) PendingJobs(context.Context) ([]model.Job, error) {
|
||||
return []model.Job{s.j}, nil
|
||||
}
|
||||
func (s *publishStore) Published(_ context.Context, id uuid.UUID) error {
|
||||
s.published = id == s.j.ID
|
||||
return nil
|
||||
}
|
||||
func TestPublisherAndConsumerCommandsUseSeparatePrincipals(t *testing.T) {
|
||||
p := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
|
||||
defer closeRedis(t, p)
|
||||
c := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
|
||||
defer closeRedis(t, c)
|
||||
ph, ch := &commandHook{role: "publisher", t: t}, &commandHook{role: "consumer", t: t}
|
||||
p.AddHook(ph)
|
||||
c.AddHook(ch)
|
||||
j := model.Job{ID: uuid.New(), AttachmentID: uuid.New(), PipelineVersion: 1, Attempt: 1, CreatedAt: time.Now()}
|
||||
s := &publishStore{j: j}
|
||||
b := New(p, c, s, "synthetic")
|
||||
if e := b.Publish(context.Background()); e != nil || !s.published {
|
||||
t.Fatal("outbox publish did not complete")
|
||||
}
|
||||
raw, _ := json.Marshal(struct {
|
||||
Schema int `json:"schema_version"`
|
||||
Type string `json:"type"`
|
||||
model.Job
|
||||
}{1, "attachment.process.v1", j})
|
||||
processed := false
|
||||
b.consume(context.Background(), redis.XMessage{ID: "1-0", Values: map[string]any{"job": string(raw)}}, func(context.Context, model.Job) error { processed = true; return nil }, func(error) { t.Fatal("consumer processing failed") })
|
||||
if !processed || len(ph.commands) != 1 || len(ch.commands) != 2 {
|
||||
t.Fatal("publication and acknowledgement were not routed independently")
|
||||
}
|
||||
}
|
||||
func TestSeparateClientConfigurationFailsClosed(t *testing.T) {
|
||||
for _, pair := range [][2]string{{"", "redis://consumer:p@127.0.0.1:1"}, {"redis://same:p@127.0.0.1:1", "redis://same:q@127.0.0.1:1"}, {"redis://:p@127.0.0.1:1", "redis://consumer:p@127.0.0.1:1"}} {
|
||||
if p, c, e := Clients(pair[0], pair[1]); e == nil {
|
||||
closeRedis(t, p)
|
||||
closeRedis(t, c)
|
||||
t.Fatal("missing or shared identity accepted")
|
||||
}
|
||||
}
|
||||
p, c, e := Clients("redis://publisher:synthetic@127.0.0.1:1", "redis://consumer:synthetic@127.0.0.1:1")
|
||||
if e != nil {
|
||||
t.Fatal("separate identity configuration rejected")
|
||||
}
|
||||
defer closeRedis(t, p)
|
||||
defer closeRedis(t, c)
|
||||
if p.Options().Username != "publisher" || c.Options().Username != "consumer" {
|
||||
t.Fatal("actual clients lost principal names")
|
||||
}
|
||||
}
|
||||
|
||||
func closeRedis(t *testing.T, c *redis.Client) {
|
||||
t.Helper()
|
||||
if e := c.Close(); e != nil {
|
||||
t.Error("client cleanup failed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"context"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type reviewPendingStore struct{ port.PipelineStore }
|
||||
|
||||
func (reviewPendingStore) PendingJobs(context.Context) ([]model.Job, error) {
|
||||
return []model.Job{{ID: uuid.New(), AttachmentID: uuid.New(), PipelineVersion: 1, CreatedAt: time.Now()}}, nil
|
||||
}
|
||||
func TestReviewPublishTransportFailureMarksProducerSpan(t *testing.T) {
|
||||
exporter := tracetest.NewInMemoryExporter()
|
||||
provider := sdktrace.NewTracerProvider(sdktrace.WithSyncer(exporter))
|
||||
previous := otel.GetTracerProvider()
|
||||
otel.SetTracerProvider(provider)
|
||||
defer func() {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
_ = provider.Shutdown(ctx)
|
||||
otel.SetTracerProvider(previous)
|
||||
}()
|
||||
client := redis.NewClient(&redis.Options{MaxRetries: -1, Dialer: func(context.Context, string, string) (net.Conn, error) {
|
||||
return nil, errors.New("synthetic transport failure")
|
||||
}})
|
||||
defer func() { _ = client.Close() }()
|
||||
consumer := redis.NewClient(&redis.Options{Addr: "127.0.0.1:1"})
|
||||
defer func() { _ = consumer.Close() }()
|
||||
broker := New(client, consumer, reviewPendingStore{}, "fake-review")
|
||||
if err := broker.Publish(context.Background()); err == nil {
|
||||
t.Fatal("negative control did not fail")
|
||||
}
|
||||
spans := exporter.GetSpans()
|
||||
if len(spans) != 1 || spans[0].Name != "attachment.publish" || spans[0].Status.Code != codes.Error {
|
||||
t.Fatalf("failed publish not marked as failed producer span; count=%d", len(spans))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
package queue
|
||||
|
||||
import (
|
||||
"backend/internal/domain/model"
|
||||
"backend/internal/domain/port"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
"time"
|
||||
)
|
||||
|
||||
const stream = "attachment-jobs"
|
||||
|
||||
type Broker struct {
|
||||
client *redis.Client
|
||||
publisher *redis.Client
|
||||
store port.PipelineStore
|
||||
consumer string
|
||||
}
|
||||
|
||||
func New(publisher, client *redis.Client, store port.PipelineStore, consumer string) *Broker {
|
||||
return &Broker{client: client, publisher: publisher, store: store, consumer: consumer}
|
||||
}
|
||||
func (b *Broker) Publish(ctx context.Context) error {
|
||||
jobs, e := b.store.PendingJobs(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
for _, j := range jobs {
|
||||
parent := otel.GetTextMapPropagator().Extract(ctx, propagation.MapCarrier{"traceparent": j.Traceparent, "tracestate": j.Tracestate})
|
||||
send, span := otel.Tracer("messenger").Start(parent, "attachment.publish", trace.WithSpanKind(trace.SpanKindProducer))
|
||||
carrier := propagation.MapCarrier{}
|
||||
otel.GetTextMapPropagator().Inject(send, carrier)
|
||||
j.Traceparent = carrier.Get("traceparent")
|
||||
j.Tracestate = carrier.Get("tracestate")
|
||||
j.Attempt++
|
||||
payload := struct {
|
||||
Schema int `json:"schema_version"`
|
||||
Type string `json:"type"`
|
||||
model.Job
|
||||
}{1, "attachment.process.v1", j}
|
||||
raw, e := json.Marshal(payload)
|
||||
if e != nil {
|
||||
span.SetStatus(codes.Error, "job_encoding_error")
|
||||
span.End()
|
||||
return e
|
||||
}
|
||||
if e = b.publisher.XAdd(send, &redis.XAddArgs{Stream: stream, MaxLen: 10000, Approx: true, Values: map[string]any{"job": string(raw)}}).Err(); e != nil {
|
||||
span.SetStatus(codes.Error, "broker_error")
|
||||
span.End()
|
||||
return e
|
||||
}
|
||||
if e = b.store.Published(send, j.ID); e != nil {
|
||||
span.SetStatus(codes.Error, "outbox_persistence_error")
|
||||
span.End()
|
||||
return e
|
||||
}
|
||||
span.End()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (b *Broker) RunPublisher(ctx context.Context, onError func(error)) {
|
||||
tick := time.NewTicker(500 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if e := b.Publish(ctx); e != nil {
|
||||
onError(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func (b *Broker) ack(ctx context.Context, id string) {
|
||||
if b.client.XAck(ctx, stream, "workers", id).Err() == nil {
|
||||
_ = b.client.XDel(ctx, stream, id).Err()
|
||||
}
|
||||
}
|
||||
func (b *Broker) consume(ctx context.Context, m redis.XMessage, process func(context.Context, model.Job) error, onError func(error)) {
|
||||
raw, ok := m.Values["job"].(string)
|
||||
if !ok || len(raw) > 2048 {
|
||||
b.ack(ctx, m.ID)
|
||||
return
|
||||
}
|
||||
var envelope struct {
|
||||
Schema int `json:"schema_version"`
|
||||
Type string `json:"type"`
|
||||
model.Job
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewBufferString(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&envelope) != nil || envelope.Schema != 1 || envelope.Type != "attachment.process.v1" || envelope.ID == uuid.Nil || envelope.AttachmentID == uuid.Nil || envelope.PipelineVersion < 1 || envelope.Attempt < 1 {
|
||||
b.ack(ctx, m.ID)
|
||||
return
|
||||
}
|
||||
work, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
e := process(work, envelope.Job)
|
||||
cancel()
|
||||
if e != nil {
|
||||
onError(e)
|
||||
} else {
|
||||
b.ack(ctx, m.ID)
|
||||
}
|
||||
}
|
||||
func (b *Broker) RunWorker(ctx context.Context, process func(context.Context, model.Job) error, onError func(error)) {
|
||||
for ctx.Err() == nil {
|
||||
e := b.client.XGroupCreateMkStream(ctx, stream, "workers", "0").Err()
|
||||
if e != nil && e.Error() != "BUSYGROUP Consumer Group name already exists" {
|
||||
onError(e)
|
||||
pause(ctx)
|
||||
continue
|
||||
}
|
||||
// Reclaim abandoned PEL entries; the DB lease and version fence are authoritative.
|
||||
claimed, _, e := b.client.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: "workers", Consumer: b.consumer, MinIdle: 30 * time.Second, Start: "0-0", Count: 1}).Result()
|
||||
if e == nil && len(claimed) > 0 {
|
||||
for _, m := range claimed {
|
||||
b.consume(ctx, m, process, onError)
|
||||
}
|
||||
continue
|
||||
}
|
||||
rows, e := b.client.XReadGroup(ctx, &redis.XReadGroupArgs{Group: "workers", Consumer: b.consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result()
|
||||
if errors.Is(e, redis.Nil) {
|
||||
continue
|
||||
}
|
||||
if e != nil {
|
||||
onError(e)
|
||||
pause(ctx)
|
||||
continue
|
||||
}
|
||||
for _, row := range rows {
|
||||
for _, m := range row.Messages {
|
||||
b.consume(ctx, m, process, onError)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func pause(ctx context.Context) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user