oficina / slides Public

Clone
git clone https://amadan.net/oficina/slides

Plain git — no account needed to clone.

Download

Download this file

1package slides
2
3import (
4 "context"
5 "strings"
6 "sync/atomic"
7 "testing"
8 "time"
9
10 access "amadan.net/oficina/agent-access.git"
11 "amadan.net/rastrillo/rastrillo/db"
12 "gorm.io/gorm"
13)
14
15func TestAgentDeckRevocationWhileWaitingForWriter(t *testing.T) {
16 f := newSlideAgentFixture(t)
17 var revoked atomic.Bool
18 if e := f.a.app.mountAgent(f.a, access.VerifyFunc(func(context.Context, string) (access.Principal, error) {
19 if revoked.Load() {
20 return access.Principal{}, access.Fail("unauthenticated", "Revoked.")
21 }
22 return f.p, nil
23 })); e != nil {
24 t.Fatal(e)
25 }
26 // If authorization is moved after body work, this fault wins and produces503.
27 if _, e := f.a.app.db.Writer().Exec("CREATE TRIGGER body_must_not_run BEFORE INSERT ON decks BEGIN SELECT RAISE(ABORT,'body attempted'); END"); e != nil {
28 t.Fatal(e)
29 }
30 var path string
31 if e := f.a.app.db.Writer().QueryRow("SELECT file FROM pragma_database_list WHERE name='main'").Scan(&path); e != nil {
32 t.Fatal(e)
33 }
34 other, e := db.Open(path, f.a.app.logger)
35 if e != nil {
36 t.Fatal(e)
37 }
38 defer other.Close()
39 held, e := other.Writer().BeginTx(t.Context(), nil)
40 if e != nil {
41 t.Fatal(e)
42 }
43 defer held.Rollback()
44 if _, e = held.Exec("UPDATE slides_agent_state SET keycheck=keycheck"); e != nil {
45 t.Fatal(e)
46 }
47 // The separate SQLite connection holds the writer; WAL identity reads finish.
48 // Observe entry into the real reservation statement after BOTH Home lookups.
49 attempted := make(chan struct{})
50 var once atomic.Bool
51 if e = f.a.app.db.G.Callback().Raw().Before("gorm:raw").Register("test:agent_writer", func(tx *gorm.DB) {
52 if strings.HasPrefix(tx.Statement.SQL.String(), "INSERT INTO slides_agent_state") && once.CompareAndSwap(false, true) {
53 close(attempted)
54 }
55 }); e != nil {
56 t.Fatal(e)
57 }
58 defer f.a.app.db.G.Callback().Raw().Remove("test:agent_writer")
59 result := make(chan int, 1)
60 go func() { result <- f.call(t, "slides_create_deck", initialSlideAgentInput()).Code }()
61 select {
62 case <-attempted:
63 case <-time.After(3 * time.Second):
64 t.Fatal("request never reached reserved-writer statement")
65 }
66 select {
67 case code := <-result:
68 t.Fatal("writer did not block", code)
69 case <-time.After(20 * time.Millisecond):
70 }
71 revoked.Store(true)
72 if e = held.Commit(); e != nil {
73 t.Fatal(e)
74 }
75 select {
76 case code := <-result:
77 if code != 401 {
78 t.Fatal("body attempted before fresh delegation check", code)
79 }
80 case <-time.After(3 * time.Second):
81 t.Fatal("writer did not resume")
82 }
83 var n int
84 f.a.app.db.G.Raw("SELECT COUNT(*) FROM decks").Scan(&n)
85 if n != 0 {
86 t.Fatal(n)
87 }
88}
89