| 1 | package setup_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/ed25519" |
| 6 | "crypto/rand" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "gorm.io/gorm" |
| 11 | "io" |
| 12 | "log/slog" |
| 13 | "path/filepath" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/equipo" |
| 18 | "amadan.net/oficina/equipo/internal/equipo/setup" |
| 19 | "amadan.net/oficina/equipo/internal/runnerproto" |
| 20 | "amadan.net/rastrillo/rastrillo/db" |
| 21 | "amadan.net/rastrillo/rastrillo/migrate" |
| 22 | ) |
| 23 | |
| 24 | func onboardingStore(t *testing.T) (*equipo.Store, *db.DB, equipo.Actor) { |
| 25 | t.Helper() |
| 26 | d, e := db.Open(filepath.Join(t.TempDir(), "onboarding.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 27 | if e != nil { |
| 28 | t.Fatal(e) |
| 29 | } |
| 30 | t.Cleanup(func() { d.Close() }) |
| 31 | if _, e = migrate.Apply(context.Background(), d, equipo.Schema); e != nil { |
| 32 | t.Fatal(e) |
| 33 | } |
| 34 | s := equipo.NewStore(d) |
| 35 | a := equipo.Actor{Address: "owner@example.com"} |
| 36 | if e = s.Bootstrap(context.Background(), []string{a.Address}); e != nil { |
| 37 | t.Fatal(e) |
| 38 | } |
| 39 | return s, d, a |
| 40 | } |
| 41 | func TestOnboardingInstallPrerequisites(t *testing.T) { |
| 42 | ctx := context.Background() |
| 43 | s, d, a := onboardingStore(t) |
| 44 | state, e := s.Onboarding(ctx, a) |
| 45 | if e != nil { |
| 46 | t.Fatal(e) |
| 47 | } |
| 48 | advance := func(step string) { |
| 49 | t.Helper() |
| 50 | var err error |
| 51 | state, err = s.AdvanceOnboarding(ctx, a, step, equipo.Mutation{RequestID: step, Revision: state.Revision}) |
| 52 | if err != nil { |
| 53 | t.Fatal(step, err) |
| 54 | } |
| 55 | } |
| 56 | advance("welcome") |
| 57 | if _, e = s.AdvanceOnboarding(ctx, a, "account", equipo.Mutation{RequestID: "no-choice", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 58 | t.Fatal("account without choice", e) |
| 59 | } |
| 60 | state, e = s.ChooseOnboardingProvider(ctx, a, "codex", equipo.Mutation{RequestID: "choose", Revision: state.Revision}) |
| 61 | if e != nil { |
| 62 | t.Fatal(e) |
| 63 | } |
| 64 | advance("account") |
| 65 | if state.CurrentStep != "runner" || !state.Completed["account"] || state.Completed["runner"] { |
| 66 | t.Fatal("choice claims login", state) |
| 67 | } |
| 68 | if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "unpaired", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 69 | t.Fatal("missing runner accepted", e) |
| 70 | } |
| 71 | exec := func(sql string, args ...any) { |
| 72 | t.Helper() |
| 73 | if e = d.G.Exec(sql, args...).Error; e != nil { |
| 74 | t.Fatal(e) |
| 75 | } |
| 76 | } |
| 77 | exec("INSERT INTO runners(id,person,machine_key_hash,label,revision) VALUES('r',?,'machine','Fixture',1)", a.Address) |
| 78 | exec("INSERT INTO runner_enrolments(id,runner_id) VALUES('e','r')") |
| 79 | reports, _ := json.Marshal([]runnerproto.ConnectionReport{{Provider: "codex", Available: true, ReadIsolation: true}}) |
| 80 | exec("INSERT INTO connections(id,runner_id,person,reports_json,last_seen) VALUES('c','r',?,?,?)", a.Address, string(reports), time.Now().UTC()) |
| 81 | if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "approved-only", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 82 | t.Fatal("approval claims exchange", e) |
| 83 | } |
| 84 | exec("UPDATE runner_enrolments SET consumed_at=?", time.Now().UTC()) |
| 85 | exec("UPDATE connections SET person='other@example.com'") |
| 86 | if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "other", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 87 | t.Fatal("other person's account", e) |
| 88 | } |
| 89 | exec("UPDATE connections SET person=?", a.Address) |
| 90 | exec("CREATE TRIGGER deny_onboarding_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture audit'); END") |
| 91 | old := state.Revision |
| 92 | if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "audit", Revision: old}); e == nil { |
| 93 | t.Fatal("advance without audit") |
| 94 | } |
| 95 | state, e = s.Onboarding(ctx, a) |
| 96 | if e != nil || state.Revision != old || state.Completed["runner"] { |
| 97 | t.Fatal("non-atomic advance", state, e) |
| 98 | } |
| 99 | exec("DROP TRIGGER deny_onboarding_audit") |
| 100 | advance("runner") |
| 101 | if state.RunnerID != "r" { |
| 102 | t.Fatal("missing persisted runner") |
| 103 | } |
| 104 | advance("specialists") |
| 105 | if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "missing-task", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 106 | t.Fatal("invented first task", e) |
| 107 | } |
| 108 | exec("INSERT INTO tasks(id,requester,request_id) VALUES('task',?,'task')", a.Address) |
| 109 | if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "unsafe-task", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| 110 | t.Fatal("write task accepted as safe first task", e) |
| 111 | } |
| 112 | exec("UPDATE tasks SET kind='recommendation'") |
| 113 | advance("first_task") |
| 114 | if state.CurrentStep != "complete" { |
| 115 | t.Fatal("incomplete", state) |
| 116 | } |
| 117 | if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "first_task", Revision: 1}); !errors.Is(e, equipo.ErrConflict) { |
| 118 | t.Fatal("changed replay input accepted", e) |
| 119 | } |
| 120 | exec("ALTER TABLE members RENAME TO missing_members") |
| 121 | if _, e = s.Onboarding(ctx, a); e == nil { |
| 122 | t.Fatal("roster error granted access") |
| 123 | } |
| 124 | } |
| 125 | func TestOnboardingPairingConfirmation(t *testing.T) { |
| 126 | now := time.Now().UTC() |
| 127 | proof := setup.PairingConfirmation("key", "person", "0123456789", now) |
| 128 | if !setup.ConfirmPairing("key", "person", "0123456789", proof, now) { |
| 129 | t.Fatal("confirmation rejected") |
| 130 | } |
| 131 | for _, tc := range []struct { |
| 132 | key, person, code string |
| 133 | at time.Time |
| 134 | }{{"key", "other", "0123456789", now}, {"key", "person", "1234567890", now}, {"other", "person", "0123456789", now}, {"key", "person", "0123456789", now.Add(5 * time.Minute)}} { |
| 135 | if setup.ConfirmPairing(tc.key, tc.person, tc.code, proof, tc.at) { |
| 136 | t.Fatal("confirmation binding or expiry bypass") |
| 137 | } |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | func TestOnboardingPairingUnique(t *testing.T) { |
| 142 | s, _, a := onboardingStore(t) |
| 143 | pub, _, e := ed25519.GenerateKey(rand.Reader) |
| 144 | if e != nil { |
| 145 | t.Fatal(e) |
| 146 | } |
| 147 | begin := func() runnerproto.DeviceCode { |
| 148 | t.Helper() |
| 149 | c, e := s.BeginEnrolment(context.Background(), base64.RawURLEncoding.EncodeToString(pub), "Fixture machine") |
| 150 | if e != nil { |
| 151 | t.Fatal(e) |
| 152 | } |
| 153 | return c |
| 154 | } |
| 155 | first, second := begin(), begin() |
| 156 | if e = s.ApproveEnrolment(context.Background(), a, first.UserCode); e != nil { |
| 157 | t.Fatal(e) |
| 158 | } |
| 159 | if e = s.ApproveEnrolment(context.Background(), a, second.UserCode); !errors.Is(e, equipo.ErrConflict) { |
| 160 | t.Fatal("duplicate runner for machine", e) |
| 161 | } |
| 162 | } |
| 163 | func TestOnboardingInstallUpgrade(t *testing.T) { |
| 164 | ctx := context.Background() |
| 165 | d, e := db.Open(filepath.Join(t.TempDir(), "old.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| 166 | if e != nil { |
| 167 | t.Fatal(e) |
| 168 | } |
| 169 | defer d.Close() |
| 170 | before := &migrate.Set{} |
| 171 | for _, m := range equipo.Schema.All() { |
| 172 | if m.ID != "equipo/0028_onboarding" { |
| 173 | before.Add(m) |
| 174 | } |
| 175 | } |
| 176 | if _, e = migrate.Apply(ctx, d, before); e != nil { |
| 177 | t.Fatal(e) |
| 178 | } |
| 179 | s := equipo.NewStore(d) |
| 180 | a := equipo.Actor{Address: "owner@example.com"} |
| 181 | if e = s.Bootstrap(ctx, []string{a.Address}); e != nil { |
| 182 | t.Fatal(e) |
| 183 | } |
| 184 | if e = d.G.Exec("INSERT INTO invitations(id,address,state,revision) VALUES('old',?,'accepted',2)", a.Address).Error; e != nil { |
| 185 | t.Fatal(e) |
| 186 | } |
| 187 | if _, e = migrate.Apply(ctx, d, equipo.Schema); e != nil { |
| 188 | t.Fatal(e) |
| 189 | } |
| 190 | var revision int64 |
| 191 | if e = d.G.Raw("SELECT revision FROM invitations WHERE id='old'").Scan(&revision).Error; e != nil || revision != 2 { |
| 192 | t.Fatal("historical invitation changed", e) |
| 193 | } |
| 194 | state, e := s.Onboarding(ctx, a) |
| 195 | if e != nil || state.Revision != 1 || state.CurrentStep != "welcome" { |
| 196 | t.Fatal("old invitee cannot resume", state, e) |
| 197 | } |
| 198 | if _, e = s.AdvanceOnboarding(ctx, a, "welcome", equipo.Mutation{RequestID: "resume", Revision: 1}); e != nil { |
| 199 | t.Fatal(e) |
| 200 | } |
| 201 | if _, e = migrate.Apply(ctx, d, equipo.Schema); e != nil { |
| 202 | t.Fatal(e) |
| 203 | } |
| 204 | state, e = s.Onboarding(ctx, a) |
| 205 | if e != nil || state.CurrentStep != "account" || !state.Completed["welcome"] { |
| 206 | t.Fatal("upgrade replay reset progress", state, e) |
| 207 | } |
| 208 | } |
| 209 | |
| 210 | func TestOnboardingPairingCountError(t *testing.T) { |
| 211 | s, d, a := onboardingStore(t) |
| 212 | pub, _, e := ed25519.GenerateKey(rand.Reader) |
| 213 | if e != nil { |
| 214 | t.Fatal(e) |
| 215 | } |
| 216 | code, e := s.BeginEnrolment(context.Background(), base64.RawURLEncoding.EncodeToString(pub), "Fixture machine") |
| 217 | if e != nil { |
| 218 | t.Fatal(e) |
| 219 | } |
| 220 | sentinel := errors.New("count fixture failure") |
| 221 | if e = d.G.Callback().Query().Before("gorm:query").Register("fixture_count_error", func(tx *gorm.DB) { |
| 222 | if tx.Statement.Table == "runners" { |
| 223 | tx.AddError(sentinel) |
| 224 | } |
| 225 | }); e != nil { |
| 226 | t.Fatal(e) |
| 227 | } |
| 228 | |
| 229 | var grant setup.EnrolmentRecord |
| 230 | if e = d.G.First(&grant).Error; e != nil { |
| 231 | t.Fatal(e) |
| 232 | } |
| 233 | mapped := errors.New("mapped error") |
| 234 | enrolments := setup.Enrolments{ |
| 235 | Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return d.G.WithContext(ctx).Transaction(fn) }, |
| 236 | Now: time.Now, |
| 237 | Instance: func(*gorm.DB) (string, error) { return code.InstanceID, nil }, |
| 238 | Rate: func(*gorm.DB, string, time.Time, time.Duration, int) (bool, error) { return true, nil }, |
| 239 | Hash: func(string, string) string { return grant.UserCodeHash }, |
| 240 | Member: func(*gorm.DB, string) (setup.Member, error) { return setup.Member{Address: a.Address}, nil }, |
| 241 | Error: func(err error) error { |
| 242 | if errors.Is(err, sentinel) { |
| 243 | return mapped |
| 244 | } |
| 245 | return err |
| 246 | }, |
| 247 | } |
| 248 | _, e = enrolments.ApproveOrInspect(context.Background(), a, code.UserCode, true) |
| 249 | if !errors.Is(e, mapped) { |
| 250 | t.Fatalf("unmapped count error: %v", e) |
| 251 | } |
| 252 | |
| 253 | } |
| 254 | |