package dashboard import ( "context" "database/sql" "net/http/httptest" "strings" "testing" "time" ) func TestProviderRequiresBoundTokenAndExistingIdentity(t *testing.T) { db, e := sql.Open("sqlite", t.TempDir()+"/provider.db") if e != nil { t.Fatal(e) } defer db.Close() db.SetMaxOpenConns(1) b, _ := Migrations.ReadFile("migrations/0001_dashboard.sql") if _, e = db.Exec(string(b)); e != nil { t.Fatal(e) } k, c := fixture(t) c.Issued = time.Now().Unix() c.Expires = c.Issued + 120 resolveCalls, readCalls := 0, 0 cfg := ProviderConfig{DB: db, Issuer: c.Issuer, Origin: c.Audience, Directory: c.Directory, Team: c.Team, Kind: "documents", Keys: map[string][]byte{c.KeyID: k.SignPub()}, Resolve: func(_ context.Context, sub string) (int64, error) { resolveCalls++ if sub != c.Subject { return 0, ErrRefused } return 1, nil }, Read: func(_ context.Context, id int64, sub string, _ time.Time) (Response, error) { readCalls++ return Response{Items: []Item{{ID: "one", Title: "Private canary", URL: c.Audience + "/d/one", Updated: time.Now()}}}, nil }} h, e := NewProvider(cfg) if e != nil { t.Fatal(e) } request := func(token string) *httptest.ResponseRecorder { r := httptest.NewRequest("GET", c.Audience+Path, nil) if token != "" { r.Header.Set("Authorization", "Bearer "+token) } w := httptest.NewRecorder() h.ServeHTTP(w, r) return w } if w := request(""); w.Code != 401 { t.Fatal(w.Code) } bad := c bad.Team = "other" token, _ := Sign(k, bad) if w := request(token); w.Code != 401 { t.Fatal(w.Code) } if resolveCalls != 0 || readCalls != 0 { t.Fatal("unverified request reached identity/data") } token, _ = Sign(k, c) w := request(token) if w.Code != 200 || !strings.Contains(w.Body.String(), "Private canary") || w.Header().Get("Cache-Control") != "private, no-store" { t.Fatalf("response %d", w.Code) } if w = request(token); w.Code != 401 { t.Fatal("replay", w.Code) } other := c other.ID, _ = ID() other.Subject = "pr_" + strings.Repeat("b", 26) token, _ = Sign(k, other) if w = request(token); w.Code != 403 || strings.Contains(w.Body.String(), "canary") { t.Fatal("unknown identity", w.Code) } if readCalls != 1 { t.Fatal("read reached more than authorized request", readCalls) } } func TestMalformedWireIsNotEmptySuccess(t *testing.T) { r := Response{Version: 1, Team: "pilot", Kind: "documents"} if r.Valid("https://docs.example.com", "pilot", "documents") { t.Fatal("nil items accepted") } r.Items = []Item{} if !r.Valid("https://docs.example.com", "pilot", "documents") { t.Fatal("explicit empty refused") } r.Kind = "events" if r.Valid("https://docs.example.com", "pilot", "events") { t.Fatal("missing timezone accepted") } r.Timezone = "Europe/Dublin" if !r.Valid("https://docs.example.com", "pilot", "events") { t.Fatal("valid empty agenda refused") } for _, link := range []string{"https://evil.example.com/d/1", "https://docs.example.com@evil.example.com/d/1", "https://docs.example.com/\\evil"} { if SafeLink(link, "https://docs.example.com") { t.Fatal("unsafe link") } } }