package calls import ( "bytes" "context" "encoding/json" "net/http/httptest" "strings" "sync/atomic" "testing" access "amadan.net/oficina/agent-access.git" "amadan.net/oficina/calls/internal/calls/seal" "amadan.net/rastrillo/rastrillo/db" "gorm.io/gorm" ) func TestDelegatedPrecommitAuthority(t *testing.T) { for _, mode := range []string{"reserved-revoke", "final-revoke", "binding", "unlink", "member"} { t.Run(mode, func(t *testing.T) { f, p := linkedDelegated(t) var checks atomic.Int64 if e := f.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { n := checks.Add(1) if mode == "reserved-revoke" && n >= 2 || mode == "final-revoke" && n >= 3 { return access.Principal{}, access.Fail("unauthenticated", "Revoked.") } return *p, nil }), f.app.agentIssuer, "acme"); e != nil { t.Fatal(e) } trigger := "" switch mode { case "reserved-revoke": trigger = "CREATE TRIGGER body_must_not_run BEFORE INSERT ON meetings BEGIN SELECT RAISE(ABORT,'body attempted'); END" case "unlink": trigger = "CREATE TRIGGER lose_authority AFTER UPDATE OF meeting_id ON calls_agent_meetings BEGIN DELETE FROM home_identity_links; END" case "binding": trigger = "CREATE TRIGGER lose_binding AFTER INSERT ON meetings BEGIN UPDATE home_identity_links SET person_binding='broken'; END" case "member": trigger = "CREATE TRIGGER lose_authority AFTER UPDATE OF meeting_id ON calls_agent_meetings BEGIN UPDATE persons SET anonymous=1; END" } if trigger != "" { if _, e := f.app.db.Writer().Exec(trigger); e != nil { t.Fatal(e) } } rec := delegatedCall(f.app, "calls_create_meeting", delegatedInputForTest()) if rec.Code != 401 && rec.Code != 403 { t.Fatal("lost authority committed", mode, rec.Code, rec.Body.String()) } for _, table := range []string{"meetings", "meeting_links", "calls_connections", "calls_agent_meetings"} { var n int if e := f.app.db.Writer().QueryRow("SELECT COUNT(*) FROM " + table).Scan(&n); e != nil || n != 0 { t.Fatal("partial meeting", table, n, e) } } }) } } func TestDelegatedAuthorityBindingRestart(t *testing.T) { f, p := linkedDelegated(t) input := delegatedInputForTest() first := delegatedCall(f.app, "calls_create_meeting", input) if first.Code != 200 { t.Fatal(first.Code) } var path string if e := f.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil { t.Fatal(e) } f.app.signinMail.close() f.app.db.Close() d, e := db.Open(path, f.app.logger) if e != nil { t.Fatal(e) } defer d.Close() restarted := newHomeRouterFixtureWith(t, d, f.app.logger, f.key, f.app.cfg.Home) if e = restarted.app.mountDelegated(access.VerifyFunc(func(context.Context, string) (access.Principal, error) { return *p, nil }), f.app.agentIssuer, "acme"); e != nil { t.Fatal(e) } rec := delegatedCall(restarted.app, "calls_create_meeting", input) if rec.Code != 200 || rec.Body.String() != first.Body.String() { t.Fatal("restart changed receipt", rec.Code, rec.Body.String()) } a := restarted.app for _, kind := range []string{"issuer", "home", "team", "key"} { t.Run(kind, func(t *testing.T) { oldIssuer, oldHome, oldTeam, oldSeal := a.agentIssuer, a.cfg.Home.Issuer, a.agentTeam, a.sealer defer func() { a.agentIssuer = oldIssuer a.cfg.Home.Issuer = oldHome a.agentTeam = oldTeam a.sealer = oldSeal }() switch kind { case "issuer": a.agentIssuer = "https://other-connect.test" case "home": a.cfg.Home.Issuer = "https://other-home.test" case "team": a.agentTeam = "green" case "key": a.sealer, _ = seal.New(bytes.Repeat([]byte{29}, 32)) } if e := a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil { t.Fatal("authority change accepted") } }) } if _, e = a.db.Writer().Exec("DELETE FROM calls_agent_state"); e != nil { t.Fatal(e) } if e = a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil { t.Fatal("existing receipts adopted without marker") } // Test each preexisting table independently, so either missing predicate fails. if e = a.db.G.Transaction(func(tx *gorm.DB) error { if e := tx.Exec("DELETE FROM calls_connections").Error; e != nil { return e } if e := a.bindDelegated(tx); e == nil { t.Fatal("receipt-only state adopted without marker") } return gorm.ErrInvalidTransaction // restore attribution for the next case }); e != gorm.ErrInvalidTransaction { t.Fatal(e) } // Attribution alone must also prevent marker adoption. if _, e = a.db.Writer().Exec("DELETE FROM calls_agent_meetings"); e != nil { t.Fatal(e) } if e = a.db.G.Transaction(func(tx *gorm.DB) error { return a.bindDelegated(tx) }); e == nil { t.Fatal("existing attribution adopted without marker") } } func TestDelegatedRejectsMalformedUnicode(t *testing.T) { f, _ := linkedDelegated(t) input := delegatedInputForTest() input["title"] = "REPLACEME" raw, _ := json.Marshal(input) for _, bad := range []string{`\ud800`, string([]byte{255})} { r := httptest.NewRequest("POST", homeTestOrigin+"/api/v1/operations/calls_create_meeting", strings.NewReader(strings.Replace(string(raw), "REPLACEME", bad, 1))) r.Header.Set("Content-Type", "application/json") r.Header.Set("Authorization", "Bearer fixture") w := httptest.NewRecorder() f.app.delegated.ServeHTTP(responseRecorder{w}, r) if w.Code != 422 { t.Fatal("malformed meeting Unicode", w.Code) } } }