oficina / fichas Public

Add owner-approved selected-field release for Docs self-signing pilot

Paul Campbell pushed by paul@keymail.dev 14b9dcef82e1e1ad64420a1b2958beebf20d7acf parent 7144092
8 files changed, +514 −2
  • docs/superpowers/specs/2026-10-26-contract-release-demo.md +30 −0
  • internal/fichas/app.go +20 −1
  • internal/fichas/config.go +6 −0
  • internal/fichas/contract_release.go +280 −0
  • internal/fichas/contract_release_test.go +14 −0
  • internal/fichas/render.go +1 −1
  • internal/fichas/templates/contract_prepare.html +11 −0
  • internal/fichastest/contract_test.go +152 −0

CI passed — run details

diff --git a/docs/superpowers/specs/2026-10-26-contract-release-demo.md b/docs/superpowers/specs/2026-10-26-contract-release-demo.md
new file mode 100644
index 0000000..2875f0b
--- /dev/null
+++ b/docs/superpowers/specs/2026-10-26-contract-release-demo.md
@@ -0,0 +1,30 @@
+# Selected customer release for the contract demo
+
+Approved design: Docs `2026-10-26-live-contract-demo.md`, independent GPT-6
+review, 2026-10-26. Consumes suite doctrine revision 9 and its issuer-only
+release annex at `1d8e22eefca2a1df863b554dd60506de3689e7c4`.
+
+This branch is based explicitly on deployed `7144092`, the tip of
+`design/rulings-2026-09-19`; main is still the earlier design-only commit.
+It does not silently merge that existing implementation into main.
+
+An optional, explicitly configured same-team pair enables a real admitted
+owner to select text/date fields from one customer card, inspect their exact
+values and destination, and authorise one bounded release. The receiving Docs
+instance independently authenticates its configured importer. This is a
+narrow self-signing pilot, not external sharing or the suite producer API.
+The suite annex defines authority, expiry, retention and threat boundaries;
+this document cites it rather than restating it.
+
+The source uses an Ed25519-signed confirmation snapshot and transactional
+reread to bind displayed definitions, selection and values as well as card
+revision. It emits a signed release only after own-origin approval. Only the
+outbound form page permits the exact configured Docs form destination.
+Existing real authentication and CSRF guards cover every approval route;
+normal sign-in resumes the opaque preparation UUID without accepting a return
+URL. Call entries and notes are never automatically included.
+
+Deployment explicitly binds `https://fichas.oficina.works` and the dedicated
+Docs demo origin to the existing standalone Oficina team. Same account alone
+is not the team assertion. Neither app merges identities by matching email.
+Live activation requires implementation review, CI and canary validation.
diff --git a/internal/fichas/app.go b/internal/fichas/app.go
index 3496417..a8068d2 100644
--- a/internal/fichas/app.go
+++ b/internal/fichas/app.go
@@ -80,12 +80,31 @@ func App(d *db.DB, cfg Config, logger *slog.Logger) (*http.ServeMux, *app, error
// so an expired session cannot turn the click into a sign-in loop.
r.Post("/appearance", chrome.HandleAppearance)
+ if cfg.ContractRelease != nil {
+ r.Get("/contracts/prepare", a.contractPrepareReturning)
+ }
// Everything else requires a session AND admission. Grouped rather
// than wrapped per route: a route added below is born guarded, which
// is the property memoria lost when a seam let one through.
r.Group(func(r chi.Router) {
r.Use(a.requireSession)
- r.Get("/", a.index)
+ if cfg.ContractRelease != nil {
+
+ r.Post("/contracts/review", a.contractReview)
+ r.Post("/contracts/approve", a.contractApprove)
+ }
+ r.Get("/", func(w http.ResponseWriter, r *http.Request) {
+ if cfg.ContractRelease != nil {
+ if c, e := r.Cookie("fichas_contract_return"); e == nil {
+ http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
+ if validContractFlow(c.Value) {
+ http.Redirect(w, r, "/contracts/prepare?flow="+c.Value, http.StatusSeeOther)
+ return
+ }
+ }
+ }
+ a.index(w, r)
+ })
r.Get("/t/{type}", a.index)
r.Get("/t/{type}/fields", a.fieldsPage)
r.Get("/t/{type}/fields/new", a.newField)
diff --git a/internal/fichas/config.go b/internal/fichas/config.go
index f5f198d..a2c1717 100644
--- a/internal/fichas/config.go
+++ b/internal/fichas/config.go
@@ -22,6 +22,8 @@ import (
// even when the refusal was deleted, because a neighbouring error path
// supplied the os.Exit the grep was looking for.
type Config struct {
+ ContractRelease *ContractReleaseConfig
+
Origin string
Sealer *seal.Sealer
// InstanceKey seals auth's pending blob. auth.New refuses an empty
@@ -146,6 +148,10 @@ func LoadConfig(getenv func(string) string) (Config, error) {
default:
return Config{}, fmt.Errorf("fichas: FICHAS_SHAPE is %q; it is %q or %q", c.Shape, ShapeLone, ShapeSuite)
}
+ c.ContractRelease, err = loadContractRelease(getenv, c.Origin)
+ if err != nil {
+ return Config{}, err
+ }
return c, nil
}
diff --git a/internal/fichas/contract_release.go b/internal/fichas/contract_release.go
new file mode 100644
index 0000000..6469b11
--- /dev/null
+++ b/internal/fichas/contract_release.go
@@ -0,0 +1,280 @@
+package fichas
+
+import (
+ "amadan.net/oficina/estilo.git/chrome"
+ "crypto/ed25519"
+ "crypto/sha256"
+ "encoding/base64"
+ "errors"
+ "net/http"
+ "net/url"
+ "strconv"
+ "strings"
+ "time"
+
+ json "github.com/go-json-experiment/json"
+ "github.com/google/uuid"
+ "gorm.io/gorm"
+)
+
+// ContractReleaseConfig pairs one importer and one destination in an explicit
+// trusted team binding. It does not grant suite identity or general S3 access.
+type ContractReleaseConfig struct {
+ Destination, Importer, Team string
+ Key ed25519.PrivateKey
+}
+type releaseField struct {
+ Key string `json:"key"`
+ Label string `json:"label"`
+ Kind string `json:"kind"`
+ Value string `json:"value"`
+}
+type releaseEnvelope struct {
+ Version int `json:"version"`
+ Source string `json:"source"`
+ Destination string `json:"destination"`
+ Team string `json:"team"`
+ Purpose string `json:"purpose"`
+ Importer string `json:"importer"`
+ Actor string `json:"actor"`
+ Flow string `json:"flow"`
+ ID string `json:"id"`
+ Card int64 `json:"card"`
+ Revision int64 `json:"revision"`
+ Issued int64 `json:"issued"`
+ Expires int64 `json:"expires"`
+ Fields []releaseField `json:"fields"`
+}
+
+const releasePurpose = "oficina.contract.self-sign.v1"
+
+var errRelease = errors.New("fichas: contract release refused")
+
+func releaseOrigin(s string) bool {
+ u, e := url.Parse(s)
+ return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && u.Fragment == "" && !u.ForceQuery
+}
+func loadContractRelease(getenv func(string) string, source string) (*ContractReleaseConfig, error) {
+ dest, key, importer, team := getenv("FICHAS_CONTRACT_DESTINATION"), getenv("FICHAS_CONTRACT_SEED"), getenv("FICHAS_CONTRACT_IMPORTER"), getenv("FICHAS_CONTRACT_TEAM")
+ if dest == "" && key == "" && importer == "" && team == "" {
+ return nil, nil
+ }
+ seed, e := base64.StdEncoding.DecodeString(key)
+ if e != nil || len(seed) != ed25519.SeedSize || !releaseOrigin(source) || !releaseOrigin(dest) || source == dest || !releaseTeam(source, team) || !releaseTeam(dest, team) || importer == "" || importer != normaliseAddress(importer) || !strings.Contains(importer, "@") || team == "" || len(team) > 64 {
+ return nil, errRelease
+ }
+ return &ContractReleaseConfig{Destination: dest, Importer: importer, Team: team, Key: ed25519.NewKeyFromSeed(seed)}, nil
+}
+
+type contractReleasePage struct {
+ Nav []NavItem
+ Account *chrome.Account
+
+ Theme, Flow, Phase, Payload, Signature, Destination, Importer, Error string
+ Cards []CardView
+ Card *CardView
+ Release *releaseEnvelope
+}
+
+func (a *app) contractPage(w http.ResponseWriter, r *http.Request, p contractReleasePage) {
+ w.Header().Set("Cache-Control", "no-store")
+ w.Header().Set("Referrer-Policy", "no-referrer")
+ p.Theme = themeAttr(r)
+ p.Nav, _ = a.nav(r, "")
+ address, _ := a.identity(r)
+ p.Account = a.account(r, address)
+ p.Destination = a.cfg.ContractRelease.Destination
+ p.Importer = a.cfg.ContractRelease.Importer
+ if p.Phase == "send" {
+ // Scope the exact destination to this single outbound form page.
+ policy := w.Header().Get("Content-Security-Policy")
+ if strings.Contains(policy, "form-action 'self'") {
+ policy = strings.Replace(policy, "form-action 'self'", "form-action 'self' "+p.Destination, 1)
+ } else {
+ policy = "default-src 'self'; style-src 'self'; img-src 'self' data:; frame-ancestors 'none'; base-uri 'none'; form-action 'self' " + p.Destination
+ }
+ w.Header().Set("Content-Security-Policy", policy)
+ }
+ render(w, "contract_prepare", p)
+}
+func (a *app) contractPrepare(w http.ResponseWriter, r *http.Request) {
+ flow := r.URL.Query().Get("flow")
+ if _, e := uuid.Parse(flow); e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ p := contractReleasePage{Flow: flow, Phase: "choose"}
+ if id, e := strconv.ParseInt(r.URL.Query().Get("card"), 10, 64); e == nil && id > 0 {
+ c, e := LoadCard(r.Context(), a.db.G, a.sealer, id)
+ if e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ p.Card = &c
+ p.Phase = "fields"
+ } else {
+ cards, e := ListCards(r.Context(), a.db.G, a.sealer, TypeCustomer)
+ if e != nil {
+ http.Error(w, "Customers are unavailable.", 503)
+ return
+ }
+ p.Cards = cards
+ }
+ a.contractPage(w, r, p)
+}
+func releaseFields(c CardView, keys []string) ([]releaseField, error) {
+ if len(keys) == 0 || len(keys) > 32 {
+ return nil, errRelease
+ }
+ out := []releaseField{}
+ seen := map[string]bool{}
+ for _, key := range keys {
+ if seen[key] {
+ return nil, errRelease
+ }
+ seen[key] = true
+ f := c.Field(key)
+ if f.Def.Key == "" || (f.Def.Kind != KindText && f.Def.Kind != KindDate) || len(f.Value) > 8192 || len(f.Label) > 256 {
+ return nil, errRelease
+ }
+ out = append(out, releaseField{key, f.Label, f.Def.Kind, f.Value})
+ }
+ return out, nil
+}
+func (a *app) contractReview(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 64<<10)
+ if r.ParseForm() != nil {
+ http.Error(w, "Invalid selection.", 400)
+ return
+ }
+ flow := r.PostForm.Get("flow")
+ if _, e := uuid.Parse(flow); e != nil {
+ http.NotFound(w, r)
+ return
+ }
+ id, _ := strconv.ParseInt(r.PostForm.Get("card"), 10, 64)
+ rev, _ := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64)
+ actor, ok := a.identity(r)
+ if !ok || !a.Admit(actor) {
+ http.NotFound(w, r)
+ return
+ }
+ var rel releaseEnvelope
+ e := a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
+ c, e := LoadCard(r.Context(), tx, a.sealer, id)
+ if e != nil {
+ return e
+ }
+ if c.Card.Revision != rev {
+ return errRelease
+ }
+ fields, e := releaseFields(c, r.PostForm["field"])
+ if e != nil {
+ return e
+ }
+ now := time.Now().Unix()
+ cfg := a.cfg.ContractRelease
+ rel = releaseEnvelope{Version: 1, Source: a.cfg.Origin, Destination: cfg.Destination, Team: cfg.Team, Purpose: "confirm:" + releasePurpose, Importer: cfg.Importer, Actor: actor, Flow: flow, ID: uuid.NewString(), Card: id, Revision: rev, Issued: now, Expires: now + 600, Fields: fields}
+ return nil
+ })
+ if e != nil {
+ http.Error(w, "The card changed or the selected fields cannot be used. Return to the customer and try again.", 409)
+ return
+ }
+ raw, e := json.Marshal(rel)
+ if e != nil || len(raw) > 64<<10 {
+ http.Error(w, "The selection is too large.", 400)
+ return
+ }
+ a.contractPage(w, r, contractReleasePage{Flow: flow, Phase: "review", Release: &rel, Payload: base64.RawURLEncoding.EncodeToString(raw), Signature: base64.RawURLEncoding.EncodeToString(ed25519.Sign(a.cfg.ContractRelease.Key, raw))})
+}
+func (a *app) contractApprove(w http.ResponseWriter, r *http.Request) {
+ r.Body = http.MaxBytesReader(w, r.Body, 128<<10)
+ if r.ParseForm() != nil {
+ http.Error(w, "Invalid approval.", 400)
+ return
+ }
+ raw, e := base64.RawURLEncoding.DecodeString(r.PostForm.Get("payload"))
+ sig, se := base64.RawURLEncoding.DecodeString(r.PostForm.Get("signature"))
+ cfg := a.cfg.ContractRelease
+ if e != nil || se != nil || len(raw) > 64<<10 || !ed25519.Verify(cfg.Key.Public().(ed25519.PublicKey), raw, sig) {
+ http.Error(w, "Invalid approval.", 400)
+ return
+ }
+ var rel releaseEnvelope
+ if json.Unmarshal(raw, &rel, json.RejectUnknownMembers(true)) != nil {
+ http.Error(w, "Invalid approval.", 400)
+ return
+ }
+ actor, ok := a.identity(r)
+ now := time.Now().Unix()
+ if !ok || !a.Admit(actor) || rel.Actor != actor || rel.Purpose != "confirm:"+releasePurpose || rel.Expires <= now || rel.Issued > now+60 || rel.Expires-rel.Issued > 600 || rel.Source != a.cfg.Origin || rel.Destination != cfg.Destination || rel.Importer != cfg.Importer || rel.Team != cfg.Team {
+ http.Error(w, "This approval has expired or changed. Start again from Docs.", 409)
+ return
+ }
+ e = a.db.G.WithContext(r.Context()).Transaction(func(tx *gorm.DB) error {
+ c, e := LoadCard(r.Context(), tx, a.sealer, rel.Card)
+ if e != nil {
+ return e
+ }
+ if c.Card.Revision != rel.Revision {
+ return errRelease
+ }
+ keys := []string{}
+ for _, f := range rel.Fields {
+ keys = append(keys, f.Key)
+ }
+ current, e := releaseFields(c, keys)
+ if e != nil {
+ return e
+ }
+ before, _ := json.Marshal(rel.Fields)
+ after, _ := json.Marshal(current)
+ if sha256.Sum256(before) != sha256.Sum256(after) {
+ return errRelease
+ }
+ return nil
+ })
+ if e != nil {
+ http.Error(w, "The displayed customer details changed. Start again from Docs.", 409)
+ return
+ }
+ rel.Purpose = releasePurpose
+ rel.Issued = time.Now().Unix()
+ rel.Expires = rel.Issued + 1800
+ raw, e = json.Marshal(rel)
+ if e != nil {
+ http.Error(w, "Approval unavailable.", 503)
+ return
+ }
+ a.contractPage(w, r, contractReleasePage{Flow: rel.Flow, Phase: "send", Release: &rel, Payload: base64.RawURLEncoding.EncodeToString(raw), Signature: base64.RawURLEncoding.EncodeToString(ed25519.Sign(cfg.Key, raw))})
+}
+
+func validContractFlow(s string) bool { _, e := uuid.Parse(s); return e == nil }
+
+// Save only an opaque flow identifier through sign-in, never a return URL.
+func (a *app) contractPrepareReturning(w http.ResponseWriter, r *http.Request) {
+ flow := r.URL.Query().Get("flow")
+ if !validContractFlow(flow) {
+ http.NotFound(w, r)
+ return
+ }
+ http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: flow, Path: "/", MaxAge: 1800, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
+ a.requireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.SetCookie(w, &http.Cookie{Name: "fichas_contract_return", Value: "", Path: "/", MaxAge: -1, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode})
+ a.contractPrepare(w, r)
+ })).ServeHTTP(w, r)
+}
+
+func releaseTeam(origin, team string) bool {
+ u, e := url.Parse(origin)
+ if e != nil {
+ return false
+ }
+ host := strings.TrimSuffix(strings.ToLower(u.Hostname()), ".")
+ parts := strings.Split(host, ".")
+ if strings.HasSuffix(host, ".oficina.works") && len(parts) >= 4 {
+ return len(parts) == 4 && parts[0] == team
+ }
+ return true
+}
diff --git a/internal/fichas/contract_release_test.go b/internal/fichas/contract_release_test.go
new file mode 100644
index 0000000..9177f8b
--- /dev/null
+++ b/internal/fichas/contract_release_test.go
@@ -0,0 +1,14 @@
+package fichas
+
+import "testing"
+
+func TestReleaseTeamBinding(t *testing.T) {
+ for _, origin := range []string{"https://other.docs.oficina.works", "https://other.docs.OFICINA.WORKS", "https://other.docs.oficina.works."} {
+ if releaseTeam(origin, "ours") {
+ t.Errorf("accepted different team: %s", origin)
+ }
+ }
+ if !releaseTeam("https://ours.docs.oficina.works", "ours") || !releaseTeam("https://docs.oficina.works", "standalone") {
+ t.Fatal("valid explicit binding refused")
+ }
+}
diff --git a/internal/fichas/render.go b/internal/fichas/render.go
index 06436fc..0d3ee97 100644
--- a/internal/fichas/render.go
+++ b/internal/fichas/render.go
@@ -35,7 +35,7 @@ func init() {
// (templates/layout.html), because Calma keeps app chrome out of the
// place the suite meets you. Both define "layout".
shells := map[string]string{
- "index": "shell", "card_new": "shell", "card_show": "shell",
+ "contract_prepare": "shell", "index": "shell", "card_new": "shell", "card_show": "shell",
"card_edit": "shell", "card_delete": "shell",
"fields": "shell", "field_new": "shell", "field_edit": "shell",
"type_new": "shell", "card_layout": "shell",
diff --git a/internal/fichas/templates/contract_prepare.html b/internal/fichas/templates/contract_prepare.html
new file mode 100644
index 0000000..68fae31
--- /dev/null
+++ b/internal/fichas/templates/contract_prepare.html
@@ -0,0 +1,11 @@
+{{define "title"}}Prepare contract · Fichas{{end}}
+{{define "content"}}
+<header fichas-appbar><h1 fichas-appbar-title>Prepare a contract <span>Selected customer details → Oficina Docs</span></h1></header>
+<div rst-box>
+{{if eq .Phase "choose"}}<h2>Choose a live customer</h2><p>Select the customer whose details belong in this agreement.</p>{{range .Cards}}<p><a rst-btn href="/contracts/prepare?flow={{$.Flow}}&amp;card={{.Card.ID}}">{{.Title}} →</a></p>{{else}}<p>No customer cards are available.</p>{{end}}{{end}}
+{{if eq .Phase "fields"}}<h2>{{.Card.Title}}</h2><p>Choose the fields to use. Notes and call entries are not included automatically.</p><form method="post" action="/contracts/review"><input type="hidden" name="flow" value="{{.Flow}}"><input type="hidden" name="card" value="{{.Card.Card.ID}}"><input type="hidden" name="revision" value="{{.Card.Card.Revision}}">
+{{range .Card.Fields}}{{if or (eq .Def.Kind "text") (eq .Def.Kind "date")}}<p><label><input type="checkbox" name="field" value="{{.Def.Key}}" {{if eq .Def.Key "f_name"}}checked{{end}}> <strong>{{.Label}}</strong> — {{.Value}}</label></p>{{end}}{{end}}
+<button rst-btn="primary">Review selected details →</button></form>{{end}}
+{{if eq .Phase "review"}}<h2>Approve these details for your contract</h2><dl rst-detail>{{range .Release.Fields}}<dt>{{.Label}}</dt><dd>{{.Value}}</dd>{{end}}</dl><p>Destination: <strong>{{.Destination}}</strong><br>Importer and signer: <strong>{{.Importer}}</strong><br>Source revision: {{.Release.Revision}}</p><p>This authorises these selected values for one contract you sign yourself. Docs must issue it within 30 minutes. Later edits or deletion in Fichas will not retract this approved copy. There is no external-recipient access in this pilot.</p><p>Issued demo records are available for seven days. Existing encrypted backups follow the app’s backup policy; deletion from this screen cannot recall downloaded copies or guarantee backup erasure.</p><form method="post" action="/contracts/approve"><input type="hidden" name="payload" value="{{.Payload}}"><input type="hidden" name="signature" value="{{.Signature}}"><button rst-btn="primary">Approve these details</button></form>{{end}}
+{{if eq .Phase "send"}}<h2>Your details are approved.</h2><p>Continue to Docs to review the imported fields and write the agreement.</p><form method="post" action="{{.Destination}}/contracts/receive"><input type="hidden" name="payload" value="{{.Payload}}"><input type="hidden" name="signature" value="{{.Signature}}"><button rst-btn="primary">Continue to Docs →</button></form>{{end}}
+</div>{{end}}
diff --git a/internal/fichastest/contract_test.go b/internal/fichastest/contract_test.go
new file mode 100644
index 0000000..9ce153e
--- /dev/null
+++ b/internal/fichastest/contract_test.go
@@ -0,0 +1,152 @@
+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.Admit)
+ 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")
+ }
+ w := req("GET", "/auth/verify?token="+token[1], nil, 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}}
+ 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"`
+ Value string `json:"value"`
+ } `json:"fields"`
+ }
+ if json.Unmarshal(raw, &payload) != nil || payload.Purpose != "oficina.contract.self-sign.v1" || len(payload.Fields) != 1 || payload.Fields[0].Key != fichas.FieldName {
+ t.Fatal("released unselected field")
+ }
+ if !strings.Contains(w.Header().Get("Content-Security-Policy"), "form-action 'self' "+cfg.ContractRelease.Destination) {
+ t.Fatal("browser would block outbound form")
+ }
+ // 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")
+ }
+}