forked from longtao.wu/droboticflow
119 lines
5.9 KiB
Go
119 lines
5.9 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"droboticflow/internal/domain"
|
|
"encoding/json"
|
|
"errors"
|
|
"go.mongodb.org/mongo-driver/bson"
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// This fixture owns a separate ephemeral auth-enabled standalone Mongo. It
|
|
// never enables authorization or creates users on the shared source/query lab.
|
|
func TestQueryReplicaSourceAccountPermissionsLocal(t *testing.T) {
|
|
if os.Getenv("QUERY_REPLICA_LOCAL_TEST") != "1" {
|
|
t.Skip("isolated auth fixture required")
|
|
}
|
|
ctx := t.Context()
|
|
if host := os.Getenv("DOCKER_HOST"); host != "" && !strings.HasPrefix(host, "unix://") {
|
|
t.Fatal("remote Docker prohibited")
|
|
}
|
|
endpoint, e := exec.Command("docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}").Output()
|
|
if e != nil || !strings.HasPrefix(strings.TrimSpace(string(endpoint)), "unix://") {
|
|
t.Fatal("local Docker socket required")
|
|
}
|
|
user, password := domain.NewID("root"), domain.NewID("secret")
|
|
name := strings.ToLower(domain.NewID("query-auth"))
|
|
cmd := exec.Command("docker", "run", "--rm", "-d", "--name", name, "--label", "codex.fixture=query-source-auth", "--cpus=1", "--memory=512m", "-p", "127.0.0.1::27017", "--env", "MONGO_INITDB_ROOT_USERNAME", "--env", "MONGO_INITDB_ROOT_PASSWORD", "mongo@sha256:5d7043a4ffe02b9ed1b6e0bab057546981af5ca0a79107e9c461e49bc44c0a7b", "--wiredTigerCacheSizeGB", "0.25", "--bind_ip_all")
|
|
cmd.Env = append(os.Environ(), "MONGO_INITDB_ROOT_USERNAME="+user, "MONGO_INITDB_ROOT_PASSWORD="+password)
|
|
out, e := cmd.Output()
|
|
if e != nil {
|
|
t.Fatal("owned authentication fixture startup failed")
|
|
}
|
|
container := strings.TrimSpace(string(out))
|
|
t.Cleanup(func() { _ = exec.Command("docker", "stop", "--time=5", container).Run() })
|
|
raw, e := exec.Command("docker", "inspect", "--format", "{{json .NetworkSettings.Ports}}", container).Output()
|
|
if e != nil {
|
|
t.Fatal("fixture binding unavailable")
|
|
}
|
|
var ports map[string][]struct{ HostIP, HostPort string }
|
|
if json.Unmarshal(raw, &ports) != nil || len(ports["27017/tcp"]) != 1 || ports["27017/tcp"][0].HostIP != "127.0.0.1" {
|
|
t.Fatal("fixture not loopback-only")
|
|
}
|
|
uri := "mongodb://127.0.0.1:" + ports["27017/tcp"][0].HostPort + "/?directConnection=true"
|
|
admin, e := mongo.Connect(ctx, options.Client().ApplyURI(uri).SetAuth(options.Credential{AuthSource: "admin", Username: user, Password: password}).SetServerSelectionTimeout(500*time.Millisecond))
|
|
if e != nil {
|
|
t.Fatal("fixture connection failed")
|
|
}
|
|
defer admin.Disconnect(context.Background())
|
|
ready := false
|
|
for n := 0; n < 80; n++ {
|
|
short, cancel := context.WithTimeout(ctx, 500*time.Millisecond)
|
|
e = admin.Ping(short, nil)
|
|
cancel()
|
|
if e == nil {
|
|
ready = true
|
|
break
|
|
}
|
|
time.Sleep(250 * time.Millisecond)
|
|
}
|
|
if !ready {
|
|
t.Fatal("authentication fixture readiness failed")
|
|
}
|
|
dbname := domain.NewID("query_sync_auth")
|
|
db := admin.Database(dbname)
|
|
privilege := bson.A{bson.M{"resource": bson.M{"cluster": true}, "actions": bson.A{"serverStatus"}}, bson.M{"resource": bson.M{"db": dbname, "collection": "humanItems"}, "actions": bson.A{"find", "update"}}, bson.M{"resource": bson.M{"db": dbname, "collection": querySyncDeleteCollection}, "actions": bson.A{"find", "insert", "update"}}}
|
|
if e = admin.Database("admin").RunCommand(ctx, bson.D{{Key: "createRole", Value: "metadata-sync"}, {Key: "privileges", Value: privilege}, {Key: "roles", Value: bson.A{}}}).Err(); e != nil {
|
|
t.Fatal("fixture role setup failed", e)
|
|
}
|
|
limitedPassword := domain.NewID("limited-secret")
|
|
if e = db.RunCommand(ctx, bson.D{{Key: "createUser", Value: "projector"}, {Key: "pwd", Value: limitedPassword}, {Key: "roles", Value: bson.A{bson.M{"role": "metadata-sync", "db": "admin"}}}}).Err(); e != nil {
|
|
t.Fatal("fixture user setup failed")
|
|
}
|
|
_, e = db.Collection("humanItems").InsertOne(ctx, bson.M{"_id": "i", "id": "i", "version": 7, "status": "claimed", "annotationDraft": "keep", "_querySync": bson.M{"revision": 1, "dirty": true}})
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
client, e := mongo.Connect(ctx, options.Client().ApplyURI(uri).SetAuth(options.Credential{AuthSource: dbname, Username: "projector", Password: limitedPassword}))
|
|
if e != nil {
|
|
t.Fatal("fixture principal unavailable")
|
|
}
|
|
defer client.Disconnect(context.Background())
|
|
limited := client.Database(dbname)
|
|
q := &QueryReplica{Source: NewMongoStore(limited)}
|
|
if e = q.sourceMetadataBulk(ctx, "humanItems", []mongo.WriteModel{mongo.NewUpdateOneModel().SetFilter(bson.M{"_id": "i", "_querySync.revision": 1}).SetUpdate(bson.M{"$set": bson.M{"_querySync.dirty": false}})}); e != nil {
|
|
t.Fatal("allowed acknowledgement failed", e)
|
|
}
|
|
if e = q.sourceMetadataBulk(ctx, "humanItems", []mongo.WriteModel{mongo.NewUpdateOneModel().SetFilter(bson.M{"_id": "i", "_querySync.revision": 1}).SetUpdate(bson.M{"$set": bson.M{"annotationDraft": "overwrite"}})}); e == nil {
|
|
t.Fatal("application metadata boundary bypassed")
|
|
}
|
|
denied := func(label string, e error) {
|
|
t.Helper()
|
|
var ce mongo.CommandError
|
|
if !errors.As(e, &ce) || ce.Code != 13 {
|
|
t.Fatalf("%s was not denied by real authentication", label)
|
|
}
|
|
}
|
|
_, e = limited.Collection("humanItems").InsertOne(ctx, bson.M{"_id": "other"})
|
|
denied("insert", e)
|
|
_, e = limited.Collection("humanItems").DeleteOne(ctx, bson.M{"_id": "i"})
|
|
denied("delete", e)
|
|
denied("DDL", limited.RunCommand(ctx, bson.M{"drop": "humanItems"}).Err())
|
|
denied("other database", client.Database("foreign").Collection("humanItems").FindOne(ctx, bson.M{}).Err())
|
|
if e = client.Database("admin").RunCommand(ctx, bson.M{"serverStatus": 1}).Err(); e != nil {
|
|
t.Fatal("monitor privilege unavailable")
|
|
}
|
|
var kept bson.M
|
|
if e = db.Collection("humanItems").FindOne(ctx, bson.M{"_id": "i"}).Decode(&kept); e != nil || kept["annotationDraft"] != "keep" || kept["version"] != int32(7) || kept["status"] != "claimed" || deletionDoc(kept[querySyncField])["dirty"] != false {
|
|
t.Fatal("authority fields altered")
|
|
}
|
|
|
|
}
|