| 1 | package equipo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | "time" |
| 10 | |
| 11 | "gorm.io/gorm" |
| 12 | ) |
| 13 | |
| 14 | func TestPreviewSecretsAreHashedAndIndexed(t *testing.T) { |
| 15 | r := newPreviewPassRig(t) |
| 16 | var lookups []string |
| 17 | if err := r.s.db.G.Callback().Query().After("gorm:query").Register("preview_exact_hash", func(tx *gorm.DB) { |
| 18 | if tx.Statement.Table == "preview_passes" || tx.Statement.Table == "preview_grants" { |
| 19 | lookups = append(lookups, tx.Statement.SQL.String()) |
| 20 | } |
| 21 | }); err != nil { |
| 22 | t.Fatal(err) |
| 23 | } |
| 24 | p := r.mint(t) |
| 25 | g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| 26 | if e != nil { |
| 27 | t.Fatal(e) |
| 28 | } |
| 29 | if _, err := r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); err != nil { |
| 30 | t.Fatal(err) |
| 31 | } |
| 32 | if len(lookups) != 2 { |
| 33 | t.Fatal("unexpected secret lookups", len(lookups)) |
| 34 | } |
| 35 | for _, query := range lookups { |
| 36 | if !strings.Contains(query, "WHERE hash = ?") { |
| 37 | t.Fatal("secret lookup is not an exact hash predicate") |
| 38 | } |
| 39 | } |
| 40 | for _, item := range []struct{ table, secret string }{{"preview_passes", p.Pass}, {"preview_grants", g.Secret}} { |
| 41 | var hash string |
| 42 | if e := r.s.db.Reader().QueryRow("SELECT hash FROM " + item.table).Scan(&hash); e != nil { |
| 43 | t.Fatal(e) |
| 44 | } |
| 45 | if hash != previewHash(item.secret) || hash == item.secret || len(hash) != 64 { |
| 46 | t.Fatal("plaintext or wrong hash") |
| 47 | } |
| 48 | var a, b, c int |
| 49 | var plan string |
| 50 | if e := r.s.db.Reader().QueryRow("EXPLAIN QUERY PLAN SELECT * FROM "+item.table+" WHERE hash = ?", hash).Scan(&a, &b, &c, &plan); e != nil { |
| 51 | t.Fatal(e) |
| 52 | } |
| 53 | if !strings.Contains(plan, "SEARCH") || !strings.Contains(plan, "INDEX") || !strings.Contains(plan, "hash=?") { |
| 54 | t.Fatal("unindexed lookup", plan) |
| 55 | } |
| 56 | } |
| 57 | rows, e := r.s.db.Reader().Query("SELECT record_id FROM audit_events WHERE kind LIKE 'preview.%'") |
| 58 | if e != nil { |
| 59 | t.Fatal(e) |
| 60 | } |
| 61 | defer rows.Close() |
| 62 | count := 0 |
| 63 | for rows.Next() { |
| 64 | var id string |
| 65 | if e = rows.Scan(&id); e != nil { |
| 66 | t.Fatal(e) |
| 67 | } |
| 68 | count++ |
| 69 | if strings.Contains(id, p.Pass) || strings.Contains(id, g.Secret) || strings.Contains(id, "https://") { |
| 70 | t.Fatal("audit contains credential or URL") |
| 71 | } |
| 72 | } |
| 73 | if count != 2 { |
| 74 | t.Fatal("missing audit", count) |
| 75 | } |
| 76 | } |
| 77 | func TestPreviewPassAuditFailureRollsBackExchange(t *testing.T) { |
| 78 | r := newPreviewPassRig(t) |
| 79 | p := r.mint(t) |
| 80 | _, e := r.s.db.Writer().Exec(`CREATE TRIGGER deny_preview_audit BEFORE INSERT ON audit_events WHEN NEW.kind = 'preview.pass.exchange' BEGIN SELECT RAISE(ABORT, 'fixture'); END`) |
| 81 | if e != nil { |
| 82 | t.Fatal(e) |
| 83 | } |
| 84 | g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| 85 | if e == nil || g.Secret != "" { |
| 86 | t.Fatal("issued grant without audit") |
| 87 | } |
| 88 | var grants int |
| 89 | if e = r.s.db.Reader().QueryRow("SELECT count(*) FROM preview_grants").Scan(&grants); e != nil || grants != 0 { |
| 90 | t.Fatal("grant survived rollback", e, grants) |
| 91 | } |
| 92 | if _, e = r.s.db.Writer().Exec("DROP TRIGGER deny_preview_audit"); e != nil { |
| 93 | t.Fatal(e) |
| 94 | } |
| 95 | if _, e = r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1"); e != nil { |
| 96 | t.Fatal("failed transaction consumed pass", e) |
| 97 | } |
| 98 | } |
| 99 | func TestPreviewPassRatesCannotBeEvadedByChangingIP(t *testing.T) { |
| 100 | r := newPreviewPassRig(t) |
| 101 | for i := 0; i < 10; i++ { |
| 102 | if _, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, fmt.Sprintf("192.0.2.%d", i)); e != nil { |
| 103 | t.Fatal(e) |
| 104 | } |
| 105 | } |
| 106 | if _, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, "198.51.100.1"); !errors.Is(e, ErrPreviewAccess) { |
| 107 | t.Fatal("device mint limit", e) |
| 108 | } |
| 109 | r.clock.Advance(time.Minute) |
| 110 | p := r.mint(t) |
| 111 | if _, e := r.s.db.Writer().Exec("UPDATE members SET active=0"); e != nil { |
| 112 | t.Fatal(e) |
| 113 | } |
| 114 | for i := 0; i < 10; i++ { |
| 115 | _, _ = r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, fmt.Sprintf("192.0.2.%d", i)) |
| 116 | } |
| 117 | if _, e := r.s.db.Writer().Exec("UPDATE members SET active=1"); e != nil { |
| 118 | t.Fatal(e) |
| 119 | } |
| 120 | if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.1"); !errors.Is(e, ErrPreviewAccess) { |
| 121 | t.Fatal("device exchange limit", e) |
| 122 | } |
| 123 | } |
| 124 | func TestPreviewPassUnknownTokensCountAgainstIPLimit(t *testing.T) { |
| 125 | r := newPreviewPassRig(t) |
| 126 | p := r.mint(t) |
| 127 | for range 30 { |
| 128 | _, _ = r.s.exchangePreviewPass(context.Background(), "invalid", "tk_preview", passCandidate, "198.51.100.2") |
| 129 | } |
| 130 | if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.2"); !errors.Is(e, ErrPreviewAccess) { |
| 131 | t.Fatal("unknown tokens evaded IP limit", e) |
| 132 | } |
| 133 | if _, e := r.s.exchangePreviewPass(context.Background(), p.Pass, "tk_preview", passCandidate, "198.51.100.3"); e != nil { |
| 134 | t.Fatal("IP limit blocked different IP", e) |
| 135 | } |
| 136 | } |
| 137 | func TestPreviewGrantBindingAndNoSlidingExpiry(t *testing.T) { |
| 138 | for _, field := range []string{"instance", "person", "credential", "epoch", "task_id", "candidate", "step_id", "attempt", "fingerprint"} { |
| 139 | t.Run(field, func(t *testing.T) { |
| 140 | r := newPreviewPassRig(t) |
| 141 | p := r.mint(t) |
| 142 | g, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| 143 | if e != nil { |
| 144 | t.Fatal(e) |
| 145 | } |
| 146 | r.clock.Advance(14 * time.Minute) |
| 147 | if _, e = r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); e != nil { |
| 148 | t.Fatal(e) |
| 149 | } |
| 150 | var expires time.Time |
| 151 | if e = r.s.db.Reader().QueryRow("SELECT expires_at FROM preview_grants").Scan(&expires); e != nil { |
| 152 | t.Fatal(e) |
| 153 | } |
| 154 | if !expires.Equal(g.ExpiresAt) { |
| 155 | t.Fatal("sliding expiry") |
| 156 | } |
| 157 | value := any("different") |
| 158 | if field == "epoch" || field == "attempt" { |
| 159 | value = int64(99) |
| 160 | } |
| 161 | if e = r.s.write(context.Background(), func(tx *gorm.DB) error { |
| 162 | return tx.Model(&previewGrantRecord{}).Where("hash = ?", previewHash(g.Secret)).Select(field).Updates(map[string]any{field: value}).Error |
| 163 | }); e != nil { |
| 164 | t.Fatal(e) |
| 165 | } |
| 166 | if _, e = r.s.readPreviewGrant(r.ctx, g.Secret, "tk_preview", "192.0.2.1"); e == nil { |
| 167 | t.Fatal("ignored binding", field) |
| 168 | } |
| 169 | }) |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | func TestPreviewPassCapsAndDeploymentEligibility(t *testing.T) { |
| 174 | for _, kind := range []string{"preview-cap", "device-cap", "same-host", "same-host-dot", "unsafe-pending", "preview-candidate", "preview-expired", "final", "unknown-grant", "revoked-grant", "audit-read"} { |
| 175 | t.Run(kind, func(t *testing.T) { |
| 176 | r := newPreviewPassRig(t) |
| 177 | exec := func(q string, args ...any) { |
| 178 | t.Helper() |
| 179 | if _, e := r.s.db.Writer().Exec(q, args...); e != nil { |
| 180 | t.Fatal(e) |
| 181 | } |
| 182 | } |
| 183 | switch kind { |
| 184 | case "preview-cap": |
| 185 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.expires_at',?) WHERE id='preview_step'", r.clock.Now().Add(30*time.Second).Format(time.RFC3339)) |
| 186 | case "device-cap": |
| 187 | exec("UPDATE person_devices SET token_expires_at=?", r.clock.Now().Add(30*time.Second)) |
| 188 | case "same-host": |
| 189 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://equipo.example:8443/') WHERE id='preview_step'") |
| 190 | case "same-host-dot": |
| 191 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.url','https://equipo.example.:8443/') WHERE id='preview_step'") |
| 192 | case "unsafe-pending": |
| 193 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.outcome','failed'),reason='preview_headers' WHERE id='preview_step'") |
| 194 | case "preview-candidate": |
| 195 | exec("UPDATE chat_steps SET candidate_sha=? WHERE id='preview_step'", strings.Repeat("2", 40)) |
| 196 | case "preview-expired": |
| 197 | exec("UPDATE chat_steps SET preview=json_set(preview,'$.expires_at',?) WHERE id='preview_step'", r.clock.Now().Format(time.RFC3339)) |
| 198 | case "final": |
| 199 | exec("UPDATE chat_tasks SET stage='done'") |
| 200 | } |
| 201 | p, e := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", passCandidate, "192.0.2.1") |
| 202 | switch kind { |
| 203 | case "same-host", "same-host-dot", "unsafe-pending", "preview-candidate", "preview-expired", "final": |
| 204 | if e == nil || p.Pass != "" { |
| 205 | t.Fatal("ineligible preview minted", kind) |
| 206 | } |
| 207 | return |
| 208 | } |
| 209 | if e != nil { |
| 210 | t.Fatal(e) |
| 211 | } |
| 212 | if strings.HasSuffix(kind, "-cap") && (!p.ExpiresAt.Equal(r.clock.Now().Add(30*time.Second)) || !p.GrantExpiresAt.Equal(p.ExpiresAt)) { |
| 213 | t.Fatal("expiry cap lost") |
| 214 | } |
| 215 | grant, e := r.s.exchangePreviewPass(r.ctx, p.Pass, "tk_preview", passCandidate, "192.0.2.1") |
| 216 | if e != nil { |
| 217 | t.Fatal(e) |
| 218 | } |
| 219 | switch kind { |
| 220 | case "unknown-grant": |
| 221 | grant.Secret = strings.Repeat("A", 43) |
| 222 | case "revoked-grant": |
| 223 | exec("UPDATE members SET active=0") |
| 224 | case "audit-read": |
| 225 | r.clock.Advance(15 * time.Minute) |
| 226 | default: |
| 227 | return |
| 228 | } |
| 229 | if task, e := r.s.readPreviewGrant(r.ctx, grant.Secret, "tk_preview", "192.0.2.1"); e == nil || task.ID != "" { |
| 230 | t.Fatal("invalid grant read succeeded") |
| 231 | } |
| 232 | if kind == "audit-read" { |
| 233 | var count int |
| 234 | if e := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); e != nil || count != 1 { |
| 235 | t.Fatal("missing refusal audit", count, e) |
| 236 | } |
| 237 | } |
| 238 | }) |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | func TestPreviewDeviceGuardBeforeTaskRead(t *testing.T) { |
| 243 | r := newPreviewPassRig(t) |
| 244 | if _, err := r.s.db.Writer().Exec("UPDATE person_devices SET revoked_at=?", r.clock.Now()); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | var refused error |
| 248 | err := r.s.write(context.Background(), func(tx *gorm.DB) error { _, refused = r.s.previewDevice(tx, r.principal); return nil }) |
| 249 | if err != nil { |
| 250 | t.Fatal(err) |
| 251 | } |
| 252 | if !errors.Is(refused, ErrPreviewAccess) { |
| 253 | t.Fatal("device helper accepted revoked credential") |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | func TestPreviewKnownRefusalsAreAuditedAndDeviceLimited(t *testing.T) { |
| 258 | r := newPreviewPassRig(t) |
| 259 | pass := r.mint(t) |
| 260 | for i := 0; i < 10; i++ { |
| 261 | _, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_other", passCandidate, fmt.Sprintf("198.51.100.%d", i)) |
| 262 | if !errors.Is(err, ErrPreviewAccess) { |
| 263 | t.Fatal("wrong binding accepted", err) |
| 264 | } |
| 265 | } |
| 266 | if _, err := r.s.exchangePreviewPass(r.ctx, pass.Pass, "tk_preview", passCandidate, "203.0.113.1"); !errors.Is(err, ErrPreviewAccess) { |
| 267 | t.Fatal("known refusals bypassed device rate", err) |
| 268 | } |
| 269 | var count int |
| 270 | if err := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); err != nil || count != 1 { |
| 271 | t.Fatal("known refusal must be audited once", count, err) |
| 272 | } |
| 273 | } |
| 274 | func TestPreviewStaleMintHasRefusalAudit(t *testing.T) { |
| 275 | r := newPreviewPassRig(t) |
| 276 | if _, err := r.s.mintPreviewPass(r.ctx, r.principal, "tk_preview", strings.Repeat("2", 40), "192.0.2.1"); !errors.Is(err, ErrPreviewChanged) { |
| 277 | t.Fatal(err) |
| 278 | } |
| 279 | var count int |
| 280 | if err := r.s.db.Reader().QueryRow("SELECT count(*) FROM audit_events WHERE kind='preview.pass.refused'").Scan(&count); err != nil || count != 1 { |
| 281 | t.Fatal("stale mint missing audit", count, err) |
| 282 | } |
| 283 | } |
| 284 | |