forked from longtao.wu/droboticflow
- handleAuthLogin now authenticates via store.FindUserByPhone instead of FindUserByEmail; the login/bootstrap-super-admin request payload field is now `phone`. Old email addresses are no longer valid login credentials. - bootstrap-super-admin now validates phone format (isValidChinaMobilePhone) instead of net/mail.ParseAddress; net/mail is fully removed from internal/api. - Same-class gap fix: handleAdminOrganizationUsersCreate (the legacy per-organization admin endpoint, not touched by ticket 02) still created users by email only, which would have left them unable to log in under the new phone-only login. Switched it to phone validation/uniqueness too, and removed the now-dead normalizeUserInput/validateUserEmailAvailable helpers. - Frontend: authApi.login, UserContext's login signature, and UserBootstrapPanel's submit handler now send `phone` instead of `email` (the form/labels were already phone-based from ticket 04). - Updated ~20 Go test files whose fixtures/helpers logged in via user.Email; adminCreateUser/loginSession/bootstrapSuperAdminSession now work in terms of phone (deterministically derived from existing email-shaped test identities via testPhoneFromSeed, to avoid rewriting every call site). Added internal/api/auth_phone_login_test.go covering phone login success/failure and old-email rejection. go test ./internal/api/... and npm run test:frontend match their pre-ticket baselines exactly (75 Go failures / 599 frontend tests with 586 pass, 13 fail) by failing test name, not just count.
228 lines
9.0 KiB
Go
228 lines
9.0 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"testing"
|
|
"time"
|
|
|
|
"droboticflow/internal/domain"
|
|
"droboticflow/internal/store"
|
|
)
|
|
|
|
func TestSupplierCascadeAPIConfirmationAndScopes(t *testing.T) {
|
|
t.Setenv("DROBOTICFLOW_REQUIRE_SESSION_AUTH", "true")
|
|
ds := store.NewMemoryStore()
|
|
h := NewHandler(ds, nil)
|
|
root := bootstrapSuperAdminSession(t, h)
|
|
org := adminCreateOrganization(t, h, root, "Cascade API", "cascade-api")
|
|
admin := adminCreateUser(t, h, root, org.ID, "Admin", "cascade-admin@example.invalid", domain.UserRoleAdmin, "test-password")
|
|
cookie := loginSession(t, h, admin.Phone, "test-password")
|
|
a := domain.SupplierRecord{ID: "cascade-a", OrganizationID: org.ID, Name: "供应商 A", Status: "active"}
|
|
_ = ds.UpsertSupplier(t.Context(), a)
|
|
b := domain.SupplierRecord{ID: "cascade-b", OrganizationID: org.ID, Name: "供应商 B", Status: "active"}
|
|
_ = ds.UpsertSupplier(t.Context(), b)
|
|
employee := adminCreateUser(t, h, root, org.ID, "A", "cascade-a@example.invalid", domain.UserRoleAnnotator, "test-password", a.ID)
|
|
other := adminCreateUser(t, h, root, org.ID, "B", "cascade-b@example.invalid", domain.UserRoleAnnotator, "test-password", b.ID)
|
|
ec := loginSession(t, h, employee.Phone, "test-password")
|
|
r := serveJSONWithCookie(h, "GET", "/api/suppliers/"+a.ID+"/deletion-preview", nil, ec)
|
|
if r.Code != 403 {
|
|
t.Fatal("employee read deletion scope")
|
|
}
|
|
r = serveJSONWithCookie(h, "GET", "/api/suppliers/"+a.ID+"/deletion-preview", nil, cookie)
|
|
if r.Code != 200 {
|
|
t.Fatalf("preview %d %s", r.Code, r.Body.String())
|
|
}
|
|
var plan domain.SupplierDeletionPlan
|
|
_ = json.Unmarshal(r.Body.Bytes(), &plan)
|
|
wrong, _ := json.Marshal(map[string]any{"confirmationName": "wrong", "digest": plan.Digest})
|
|
r = serveJSONWithCookie(h, "POST", "/api/suppliers/"+a.ID+"/deletions", wrong, cookie)
|
|
if r.Code != 409 {
|
|
t.Fatal("unconfirmed deletion admitted")
|
|
}
|
|
if user, _ := ds.GetUser(t.Context(), employee.ID); user.Status != domain.UserStatusActive {
|
|
t.Fatal("preview mutated account")
|
|
}
|
|
body, _ := json.Marshal(map[string]any{"confirmationName": a.Name, "digest": plan.Digest, "reason": "test"})
|
|
r = serveJSONWithCookie(h, "POST", "/api/suppliers/"+a.ID+"/deletions", body, cookie)
|
|
if r.Code != 202 {
|
|
t.Fatalf("admission %d %s", r.Code, r.Body.String())
|
|
}
|
|
id := supplierDeletionID(a.ID)
|
|
for i := 0; i < 100; i++ {
|
|
job, _ := ds.GetSupplierDeletion(t.Context(), id)
|
|
if job != nil && job.Status == "completed" {
|
|
break
|
|
}
|
|
if job != nil && job.Status == "failed" {
|
|
t.Fatal(job.Error)
|
|
}
|
|
time.Sleep(10 * time.Millisecond)
|
|
}
|
|
job, _ := ds.GetSupplierDeletion(t.Context(), id)
|
|
if job.Status != "completed" {
|
|
t.Fatalf("not completed %+v", job)
|
|
}
|
|
if user, _ := ds.GetUser(t.Context(), employee.ID); user != nil {
|
|
t.Fatal("owned employee survived")
|
|
}
|
|
if user, _ := ds.GetUser(t.Context(), other.ID); user == nil {
|
|
t.Fatal("other supplier employee deleted")
|
|
}
|
|
if r = serveJSONWithCookie(h, "GET", "/api/auth/me", nil, ec); r.Code != 401 {
|
|
t.Fatal("deleted account session remains")
|
|
}
|
|
r = serveJSONWithCookie(h, "POST", "/api/suppliers/"+a.ID+"/deletions", body, cookie)
|
|
if r.Code != 200 {
|
|
t.Fatal("duplicate deletion not idempotent")
|
|
}
|
|
def, _ := ds.EnsureDefaultSupplier(t.Context(), org.ID)
|
|
r = serveJSONWithCookie(h, "GET", "/api/suppliers/"+def.ID+"/deletion-preview", nil, cookie)
|
|
if r.Code != 409 {
|
|
t.Fatal("default supplier deletable")
|
|
}
|
|
_ = http.StatusOK
|
|
}
|
|
func TestSupplierCascadeFailureRetryPreservesOtherSupplierFiles(t *testing.T) {
|
|
ds := store.NewMemoryStore()
|
|
ctx := t.Context()
|
|
org := "org-files"
|
|
project := "shared"
|
|
_ = ds.UpsertProject(ctx, domain.ProjectRecord{ID: project, OrganizationID: org, Name: "shared"})
|
|
for _, id := range []string{"A", "B"} {
|
|
_ = ds.UpsertSupplier(ctx, domain.SupplierRecord{ID: id, OrganizationID: org, Name: id, Status: "active"})
|
|
_ = ds.UpsertHumanItem(ctx, domain.HumanItemRecord{ID: "i" + id, OrganizationID: org, ProjectID: project, RunID: "run-" + id, SupplierID: id, Status: domain.HumanItemAccepted})
|
|
_ = ds.UpsertRun(ctx, domain.RunRecord{ID: "run-" + id, OrganizationID: org, ProjectID: project, Status: domain.RunStatusCompleted})
|
|
}
|
|
workspace := t.TempDir()
|
|
for _, dir := range []string{"system/runs/run-A", "system/runs/run-B", "raw"} {
|
|
_ = os.MkdirAll(filepath.Join(workspace, dir), 0755)
|
|
_ = os.WriteFile(filepath.Join(workspace, dir, "keep.txt"), []byte(dir), 0600)
|
|
}
|
|
failOnce := true
|
|
old := projectDeletionRuntimeFactory
|
|
defer func() { projectDeletionRuntimeFactory = old }()
|
|
projectDeletionRuntimeFactory = func(string, string, string, string) (projectDeletionRuntime, error) {
|
|
return deletionRuntimeFunc(func(_ context.Context, _, id string) error {
|
|
if id != "run-A" {
|
|
t.Fatalf("stopped other supplier: %s", id)
|
|
}
|
|
if failOnce {
|
|
return errors.New("injected runtime stop failure")
|
|
}
|
|
return nil
|
|
}), nil
|
|
}
|
|
s := &server{store: ds, workspaceMountPath: workspace, k8sNamespace: "qa", workspacePVCName: "qa"}
|
|
plan, e := s.buildSupplierDeletionPreview(ctx, org, "A")
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
job, e := ds.BeginSupplierDeletion(ctx, domain.SupplierDeletionTask{ID: supplierDeletionID("A"), OrganizationID: org, Plan: plan, Status: "prepared", Phase: "freezing", StopRunning: true})
|
|
if e != nil {
|
|
t.Fatal(e)
|
|
}
|
|
execute := func(owner string) *domain.SupplierDeletionTask {
|
|
t.Helper()
|
|
claimed, ok, e := ds.ClaimSupplierDeletion(ctx, job.ID, owner, deletionLeaseTime(time.Now()), deletionLeaseTime(time.Now().Add(time.Minute)))
|
|
if e != nil || !ok {
|
|
t.Fatal(e)
|
|
}
|
|
s.executeSupplierDeletion(*claimed, owner)
|
|
saved, _ := ds.GetSupplierDeletion(ctx, job.ID)
|
|
return saved
|
|
}
|
|
if task := execute("first"); task.Status != "failed" {
|
|
t.Fatal("injected failure not persisted")
|
|
}
|
|
if _, e = os.Stat(filepath.Join(workspace, "system/runs/run-A/keep.txt")); e != nil {
|
|
t.Fatal("files deleted before runtime stop")
|
|
}
|
|
failOnce = false
|
|
if task := execute("second"); task.Status != "completed" {
|
|
t.Fatal(task.Error)
|
|
}
|
|
if _, e = os.Stat(filepath.Join(workspace, "system/runs/run-A")); !os.IsNotExist(e) {
|
|
t.Fatal("owned files retained")
|
|
}
|
|
for _, path := range []string{"system/runs/run-B/keep.txt", "raw/keep.txt"} {
|
|
if _, e = os.Stat(filepath.Join(workspace, path)); e != nil {
|
|
t.Fatal("protected data removed", path)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestSupplierCascadePlatformWorkspaceScope(t *testing.T) {
|
|
t.Setenv("PROJECT_DELETION_WORKSPACE_CONNECTION_ID", "platform-storage")
|
|
t.Setenv("PROJECT_DELETION_WORKSPACE_BUCKET", "platform-workspace")
|
|
plan := domain.SupplierDeletionPlan{RunIDs: []string{"run-owned"}}
|
|
base := domain.ProjectDeletionTarget{Kind: "bos", RunID: "run-owned", ConnectionID: "platform-storage", Bucket: "platform-workspace", Prefix: "system/runs/run-owned"}
|
|
if !supplierDeletionPlatformWorkspace(plan, base) {
|
|
t.Fatal("configured exact owned workspace should be permitted")
|
|
}
|
|
for _, name := range []string{"connection", "bucket", "shared-run", "parent", "sibling", "traversal"} {
|
|
t.Run(name, func(t *testing.T) {
|
|
target := base
|
|
switch name {
|
|
case "connection":
|
|
target.ConnectionID = "other-storage"
|
|
case "bucket":
|
|
target.Bucket = "other-bucket"
|
|
case "shared-run":
|
|
target.RunID = "run-shared"
|
|
target.Prefix = "system/runs/run-shared"
|
|
case "parent":
|
|
target.Prefix = "system/runs"
|
|
case "sibling":
|
|
target.Prefix = "system/runs/run-other"
|
|
case "traversal":
|
|
target.RunID = "../run-owned"
|
|
target.Prefix = "system/runs/../run-owned"
|
|
}
|
|
if supplierDeletionPlatformWorkspace(plan, target) {
|
|
t.Fatal("foreign or imprecise scope admitted")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSupplierCascadePreviewPreservesCrossOrganizationArtifactChain(t *testing.T) {
|
|
ds := store.NewMemoryStore()
|
|
ctx := t.Context()
|
|
if err := ds.UpsertSupplier(ctx, domain.SupplierRecord{ID: "A", OrganizationID: "org-a", Name: "A", Status: "active"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, id := range []string{"run-first", "run-second", "run-adjacent"} {
|
|
r := domain.RunRecord{ID: id, OrganizationID: "org-a", ProjectID: "project-a", Status: domain.RunStatusCompleted}
|
|
if id == "run-second" {
|
|
r.Artifacts = []domain.ExecutionArtifact{{Path: "/workspace/run-first/file"}}
|
|
}
|
|
if err := ds.UpsertRun(ctx, r); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := ds.UpsertHumanItem(ctx, domain.HumanItemRecord{ID: "item-" + id, OrganizationID: "org-a", ProjectID: "project-a", SupplierID: "A", RunID: id}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
if err := ds.UpsertRun(ctx, domain.RunRecord{ID: "run-foreign", OrganizationID: "org-b", Artifacts: []domain.ExecutionArtifact{{Path: "/workspace/run-second/run-adjacent/file"}}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
s := &server{store: ds}
|
|
plan, err := s.buildSupplierDeletionPreview(ctx, "org-a", "A")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(plan.RunIDs) != 0 || len(plan.SharedRunIDs) != 3 || len(plan.Targets) != 0 {
|
|
t.Fatalf("foreign/transitive artifact references lost: %+v", plan)
|
|
}
|
|
cancelled, cancel := context.WithCancel(ctx)
|
|
cancel()
|
|
if _, err = s.buildSupplierDeletionPreview(cancelled, "org-a", "A"); !errors.Is(err, context.Canceled) {
|
|
t.Fatalf("cancellation not propagated: %v", err)
|
|
}
|
|
}
|