| 1 | package fichastest |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "html" |
| 10 | "io" |
| 11 | "log/slog" |
| 12 | "net/http" |
| 13 | "net/http/httptest" |
| 14 | "net/url" |
| 15 | "path/filepath" |
| 16 | "regexp" |
| 17 | "strconv" |
| 18 | "strings" |
| 19 | "testing" |
| 20 | |
| 21 | fichas "amadan.net/oficina/fichas/internal/fichas" |
| 22 | "amadan.net/rastrillo/rastrillo/db" |
| 23 | "github.com/google/uuid" |
| 24 | ) |
| 25 | |
| 26 | func TestContractReleaseThroughRealAdmission(t *testing.T) { |
| 27 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 28 | d, e := db.Open(filepath.Join(t.TempDir(), "release.db"), logger) |
| 29 | if e != nil { |
| 30 | t.Fatal(e) |
| 31 | } |
| 32 | defer d.Close() |
| 33 | pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| 34 | cfg := testConfig(t) |
| 35 | cfg.ContractRelease = &fichas.ContractReleaseConfig{Destination: "https://docs.example.com", Importer: TestOwner, Team: "test-team", Key: key} |
| 36 | mux, app, e := fichas.App(d, cfg, logger) |
| 37 | if e != nil { |
| 38 | t.Fatal(e) |
| 39 | } |
| 40 | m := &capturingMailer{} |
| 41 | au, e := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: m}, logger, app) |
| 42 | if e != nil { |
| 43 | t.Fatal(e) |
| 44 | } |
| 45 | app.UseAuth(au) |
| 46 | member, e := fichas.EnsureMember(context.Background(), d.G, cfg.Sealer, TestOwner) |
| 47 | if e != nil { |
| 48 | t.Fatal(e) |
| 49 | } |
| 50 | 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"}) |
| 51 | if e != nil { |
| 52 | t.Fatal(e) |
| 53 | } |
| 54 | var cookies []*http.Cookie |
| 55 | req := func(method, path string, f url.Values, origin string) *httptest.ResponseRecorder { |
| 56 | r := httptest.NewRequest(method, path, strings.NewReader(f.Encode())) |
| 57 | r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 58 | r.Header.Set("Origin", origin) |
| 59 | for _, c := range cookies { |
| 60 | r.AddCookie(c) |
| 61 | } |
| 62 | w := httptest.NewRecorder() |
| 63 | mux.ServeHTTP(w, r) |
| 64 | return w |
| 65 | } |
| 66 | flow := uuid.NewString() |
| 67 | path := "/contracts/prepare?flow=" + flow + "&card=" + strconv.FormatInt(card.ID, 10) |
| 68 | if w := req("GET", path, nil, cfg.Origin); w.Code != 303 { |
| 69 | t.Fatalf("unsigned source status %d", w.Code) |
| 70 | } |
| 71 | if w := req("POST", "/auth/begin", url.Values{"address": {TestOwner}, "force": {"1"}}, cfg.Origin); w.Code != 303 { |
| 72 | t.Fatalf("login %d", w.Code) |
| 73 | } |
| 74 | token := linkToken.FindStringSubmatch(m.last(t)) |
| 75 | if len(token) != 2 { |
| 76 | t.Fatal("missing login token") |
| 77 | } |
| 78 | // The link's GET draws the confirm door; its POST spends the token. |
| 79 | w := req("POST", "/auth/verify", url.Values{"token": {token[1]}}, cfg.Origin) |
| 80 | cookies = w.Result().Cookies() |
| 81 | if len(cookies) == 0 { |
| 82 | t.Fatal("no real session") |
| 83 | } |
| 84 | if w = req("GET", path, nil, cfg.Origin); w.Code != 200 || !strings.Contains(w.Body.String(), "Live-style customer") { |
| 85 | t.Fatalf("source picker %d %s", w.Code, w.Body) |
| 86 | } |
| 87 | form := url.Values{"flow": {flow}, "card": {strconv.FormatInt(card.ID, 10)}, "revision": {strconv.FormatInt(card.Revision, 10)}, "field": {fichas.FieldName, fichas.FieldEmail}} |
| 88 | if w = req("POST", "/contracts/review", form, "https://evil.example.com"); w.Code != 403 { |
| 89 | t.Fatalf("CSRF %d", w.Code) |
| 90 | } |
| 91 | w = req("POST", "/contracts/review", form, cfg.Origin) |
| 92 | if w.Code != 200 { |
| 93 | t.Fatalf("review %d %s", w.Code, w.Body) |
| 94 | } |
| 95 | field := func(body, name string) string { |
| 96 | v := regexp.MustCompile(`name="` + name + `" value="([^"]+)"`).FindStringSubmatch(body) |
| 97 | if len(v) != 2 { |
| 98 | t.Fatalf("missing %s", name) |
| 99 | } |
| 100 | return html.UnescapeString(v[1]) |
| 101 | } |
| 102 | approval := url.Values{"payload": {field(w.Body.String(), "payload")}, "signature": {field(w.Body.String(), "signature")}} |
| 103 | bad := url.Values{"payload": {approval.Get("payload")}, "signature": {"tampered"}} |
| 104 | if w = req("POST", "/contracts/approve", bad, cfg.Origin); w.Code < 400 { |
| 105 | t.Fatal("tampered approval accepted") |
| 106 | } |
| 107 | w = req("POST", "/contracts/approve", approval, cfg.Origin) |
| 108 | if w.Code != 200 || !strings.Contains(w.Body.String(), cfg.ContractRelease.Destination+"/contracts/receive") { |
| 109 | t.Fatalf("approval %d %s", w.Code, w.Body) |
| 110 | } |
| 111 | raw, _ := base64.RawURLEncoding.DecodeString(field(w.Body.String(), "payload")) |
| 112 | sig, _ := base64.RawURLEncoding.DecodeString(field(w.Body.String(), "signature")) |
| 113 | if !ed25519.Verify(pub, raw, sig) { |
| 114 | t.Fatal("release signature invalid") |
| 115 | } |
| 116 | var payload struct { |
| 117 | Purpose string `json:"purpose"` |
| 118 | Fields []struct { |
| 119 | Key string `json:"key"` |
| 120 | Kind string `json:"kind"` |
| 121 | Value string `json:"value"` |
| 122 | } `json:"fields"` |
| 123 | } |
| 124 | if json.Unmarshal(raw, &payload) != nil || payload.Purpose != "oficina.contract.self-sign.v1" || len(payload.Fields) != 2 || |
| 125 | payload.Fields[0].Key != fichas.FieldName || payload.Fields[1].Key != fichas.FieldEmail { |
| 126 | t.Fatalf("released other than the selected fields: %+v", payload.Fields) |
| 127 | } |
| 128 | // Docs knows text and date only: the Email field (its own kind since |
| 129 | // 2026-11-12) travels as text, or Docs refuses it. |
| 130 | for _, f := range payload.Fields { |
| 131 | if f.Kind != "text" { |
| 132 | t.Errorf("%s travels as %q; Docs accepts text", f.Key, f.Kind) |
| 133 | } |
| 134 | } |
| 135 | if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self' "+cfg.ContractRelease.Destination) { |
| 136 | t.Fatal("browser would block outbound form") |
| 137 | } |
| 138 | if got := w.Header().Get("Referrer-Policy"); got != "strict-origin" { |
| 139 | t.Fatalf("outbound form must preserve Origin without leaking paths: %q", got) |
| 140 | } |
| 141 | // A field definition change without a card revision change still invalidates approval. |
| 142 | var def fichas.FieldDef |
| 143 | if e = d.G.Where("key = ?", fichas.FieldName).First(&def).Error; e != nil { |
| 144 | t.Fatal(e) |
| 145 | } |
| 146 | oldKind := def.Kind |
| 147 | if e = d.G.Model(&def).Update("kind", "date").Error; e != nil { |
| 148 | t.Fatal(e) |
| 149 | } |
| 150 | if w = req("POST", "/contracts/approve", approval, cfg.Origin); w.Code != 409 { |
| 151 | t.Fatal("changed definition accepted") |
| 152 | } |
| 153 | if e = d.G.Model(&def).Update("kind", oldKind).Error; e != nil { |
| 154 | t.Fatal(e) |
| 155 | } |
| 156 | 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 { |
| 157 | t.Fatal(e) |
| 158 | } |
| 159 | if w = req("POST", "/contracts/approve", approval, cfg.Origin); w.Code != 409 { |
| 160 | t.Fatal("changed source revision accepted") |
| 161 | } |
| 162 | if w = req("POST", "/contracts/review", form, cfg.Origin); w.Code != 409 { |
| 163 | t.Fatal("stale field selection accepted") |
| 164 | } |
| 165 | } |
| 166 | |