package fichastest import ( "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "html" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "path/filepath" "regexp" "strconv" "strings" "testing" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/rastrillo/rastrillo/db" "github.com/google/uuid" ) func TestContractReleaseThroughRealAdmission(t *testing.T) { logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, e := db.Open(filepath.Join(t.TempDir(), "release.db"), logger) if e != nil { t.Fatal(e) } defer d.Close() pub, key, _ := ed25519.GenerateKey(rand.Reader) cfg := testConfig(t) cfg.ContractRelease = &fichas.ContractReleaseConfig{Destination: "https://docs.example.com", Importer: TestOwner, Team: "test-team", Key: key} mux, app, e := fichas.App(d, cfg, logger) if e != nil { t.Fatal(e) } m := &capturingMailer{} au, e := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: m}, logger, app) if e != nil { t.Fatal(e) } app.UseAuth(au) member, e := fichas.EnsureMember(context.Background(), d.G, cfg.Sealer, TestOwner) if e != nil { t.Fatal(e) } card, e := fichas.CreateCard(context.Background(), d.G, cfg.Sealer, fichas.TypeCustomer, fichas.Person(member.ID), map[string]string{fichas.FieldName: "Live-style customer", fichas.FieldEmail: "customer@example.com"}) if e != nil { t.Fatal(e) } var cookies []*http.Cookie req := func(method, path string, f url.Values, origin string) *httptest.ResponseRecorder { r := httptest.NewRequest(method, path, strings.NewReader(f.Encode())) r.Header.Set("Content-Type", "application/x-www-form-urlencoded") r.Header.Set("Origin", origin) for _, c := range cookies { r.AddCookie(c) } w := httptest.NewRecorder() mux.ServeHTTP(w, r) return w } flow := uuid.NewString() path := "/contracts/prepare?flow=" + flow + "&card=" + strconv.FormatInt(card.ID, 10) if w := req("GET", path, nil, cfg.Origin); w.Code != 303 { t.Fatalf("unsigned source status %d", w.Code) } if w := req("POST", "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}, cfg.Origin); w.Code != 303 { t.Fatalf("login %d", w.Code) } token := linkToken.FindStringSubmatch(m.last(t)) if len(token) != 2 { t.Fatal("missing login token") } // The link's GET draws the confirm door; its POST spends the token. w := req("POST", "/auth/verify", url.Values{"token": {token[1]}}, cfg.Origin) cookies = w.Result().Cookies() if len(cookies) == 0 { t.Fatal("no real session") } if w = req("GET", path, nil, cfg.Origin); w.Code != 200 || !strings.Contains(w.Body.String(), "Live-style customer") { t.Fatalf("source picker %d %s", w.Code, w.Body) } form := url.Values{"flow": {flow}, "card": {strconv.FormatInt(card.ID, 10)}, "revision": {strconv.FormatInt(card.Revision, 10)}, "field": {fichas.FieldName, fichas.FieldEmail}} if w = req("POST", "/contracts/review", form, "https://evil.example.com"); w.Code != 403 { t.Fatalf("CSRF %d", w.Code) } w = req("POST", "/contracts/review", form, cfg.Origin) if w.Code != 200 { t.Fatalf("review %d %s", w.Code, w.Body) } field := func(body, name string) string { v := regexp.MustCompile(`name="` + name + `" value="([^"]+)"`).FindStringSubmatch(body) if len(v) != 2 { t.Fatalf("missing %s", name) } return html.UnescapeString(v[1]) } approval := url.Values{"payload": {field(w.Body.String(), "payload")}, "signature": {field(w.Body.String(), "signature")}} bad := url.Values{"payload": {approval.Get("payload")}, "signature": {"tampered"}} if w = req("POST", "/contracts/approve", bad, cfg.Origin); w.Code < 400 { t.Fatal("tampered approval accepted") } w = req("POST", "/contracts/approve", approval, cfg.Origin) if w.Code != 200 || !strings.Contains(w.Body.String(), cfg.ContractRelease.Destination+"/contracts/receive") { t.Fatalf("approval %d %s", w.Code, w.Body) } raw, _ := base64.RawURLEncoding.DecodeString(field(w.Body.String(), "payload")) sig, _ := base64.RawURLEncoding.DecodeString(field(w.Body.String(), "signature")) if !ed25519.Verify(pub, raw, sig) { t.Fatal("release signature invalid") } var payload struct { Purpose string `json:"purpose"` Fields []struct { Key string `json:"key"` Kind string `json:"kind"` Value string `json:"value"` } `json:"fields"` } if json.Unmarshal(raw, &payload) != nil || payload.Purpose != "oficina.contract.self-sign.v1" || len(payload.Fields) != 2 || payload.Fields[0].Key != fichas.FieldName || payload.Fields[1].Key != fichas.FieldEmail { t.Fatalf("released other than the selected fields: %+v", payload.Fields) } // Docs knows text and date only: the Email field (its own kind since // 2026-11-12) travels as text, or Docs refuses it. for _, f := range payload.Fields { if f.Kind != "text" { t.Errorf("%s travels as %q; Docs accepts text", f.Key, f.Kind) } } if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self' "+cfg.ContractRelease.Destination) { t.Fatal("browser would block outbound form") } if got := w.Header().Get("Referrer-Policy"); got != "strict-origin" { t.Fatalf("outbound form must preserve Origin without leaking paths: %q", got) } // A field definition change without a card revision change still invalidates approval. var def fichas.FieldDef if e = d.G.Where("key = ?", fichas.FieldName).First(&def).Error; e != nil { t.Fatal(e) } oldKind := def.Kind if e = d.G.Model(&def).Update("kind", "date").Error; e != nil { t.Fatal(e) } if w = req("POST", "/contracts/approve", approval, cfg.Origin); w.Code != 409 { t.Fatal("changed definition accepted") } if e = d.G.Model(&def).Update("kind", oldKind).Error; e != nil { t.Fatal(e) } if e = fichas.UpdateCard(context.Background(), d.G, cfg.Sealer, card.ID, fichas.Person(member.ID), map[string]string{fichas.FieldName: "Changed customer"}); e != nil { t.Fatal(e) } if w = req("POST", "/contracts/approve", approval, cfg.Origin); w.Code != 409 { t.Fatal("changed source revision accepted") } if w = req("POST", "/contracts/review", form, cfg.Origin); w.Code != 409 { t.Fatal("stale field selection accepted") } }