package dashboard import ( "context" "database/sql" "strings" "sync" "testing" "time" "amadan.net/rastrillo/rastrillo/assertion" family "amadan.net/rastrillo/rastrillo/crypto" _ "modernc.org/sqlite" ) func fixture(t *testing.T) (*family.Keypair, Claims) { t.Helper() k, e := family.Generate() if e != nil { t.Fatal(e) } id, _ := ID() nonce, _ := ID() return k, Claims{Version: 1, Issuer: "https://id.example.com", Audience: "https://docs.example.com", Directory: "https://home.example.com", Subject: "pr_" + strings.Repeat("a", 26), Team: "pilot", Purpose: "dashboard-read", KeyID: "key", ID: id, Nonce: nonce, Issued: 1000, Expires: 1120} } func TestTokensAreBoundAndPurposeSeparated(t *testing.T) { k, c := fixture(t) token, e := Sign(k, c) if e != nil { t.Fatal(e) } verify := func(token string, c Claims, now int64) error { _, e := Verify(token, c.Issuer, c.Audience, c.Directory, c.Team, map[string][]byte{"key": k.SignPub()}, time.Unix(now, 0)) return e } if e = verify(token, c, 1000); e != nil { t.Fatal(e) } for _, field := range []string{"issuer", "audience", "directory", "team"} { wrong := c switch field { case "issuer": wrong.Issuer = "https://other.example.com" case "audience": wrong.Audience = "https://other.example.com" case "directory": wrong.Directory = "https://other.example.com" case "team": wrong.Team = "other" } if verify(token, wrong, 1000) == nil { t.Fatal("accepted wrong", field) } } for _, now := range []int64{969, 1120, 1200} { if verify(token, c, now) == nil { t.Fatal("accepted time", now) } } login, e := assertion.Sign(k, assertion.Claims{Version: 1, Issuer: c.Issuer, Audience: c.Audience, Subject: c.Subject, KeyID: c.KeyID, ID: c.ID, Nonce: c.Nonce, IssuedAt: 1000, ExpiresAt: 1120, AuthTime: 1000}) if e != nil { t.Fatal(e) } if verify(login, c, 1000) == nil { t.Fatal("login accepted for dashboard") } v, _ := assertion.NewVerifier(c.Issuer, c.Audience, map[string][]byte{"key": k.SignPub()}) if _, e = v.Verify(token, time.Unix(1000, 0)); e == nil { t.Fatal("dashboard accepted for login") } } func TestReplaySurvivesReopenAndClockRollback(t *testing.T) { path := t.TempDir() + "/replay.db" db, e := sql.Open("sqlite", path) if e != nil { t.Fatal(e) } db.SetMaxOpenConns(1) b, _ := Migrations.ReadFile("migrations/0001_dashboard.sql") if _, e = db.Exec(string(b)); e != nil { t.Fatal(e) } _, c := fixture(t) var mu sync.Mutex success := 0 var wg sync.WaitGroup for range 8 { wg.Add(1) go func() { defer wg.Done() if Consume(context.Background(), db, c, time.Unix(1000, 0)) == nil { mu.Lock() success++ mu.Unlock() } }() } wg.Wait() if success != 1 { t.Fatalf("consumed %d times", success) } db.Close() db, e = sql.Open("sqlite", path) if e != nil { t.Fatal(e) } defer db.Close() if Consume(context.Background(), db, c, time.Unix(1000, 0)) == nil { t.Fatal("replayed after reopen") } c.ID, _ = ID() if Consume(context.Background(), db, c, time.Unix(969, 0)) == nil { t.Fatal("clock rollback accepted") } }