-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathadmin_test.go
3037 lines (2748 loc) · 97.5 KB
/
admin_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2014 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package server
import (
"bytes"
"context"
gosql "database/sql"
"encoding/json"
"fmt"
"io/ioutil"
"math"
"net/http"
"net/url"
"reflect"
"regexp"
"sort"
"strings"
"testing"
"time"
"github.com/cockroachdb/cockroach/pkg/base"
"github.com/cockroachdb/cockroach/pkg/clusterversion"
"github.com/cockroachdb/cockroach/pkg/config/zonepb"
"github.com/cockroachdb/cockroach/pkg/jobs"
"github.com/cockroachdb/cockroach/pkg/jobs/jobspb"
"github.com/cockroachdb/cockroach/pkg/keys"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/kvserverpb"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness"
"github.com/cockroachdb/cockroach/pkg/kv/kvserver/liveness/livenesspb"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/cockroachdb/cockroach/pkg/rpc"
"github.com/cockroachdb/cockroach/pkg/security/username"
"github.com/cockroachdb/cockroach/pkg/server/debug"
"github.com/cockroachdb/cockroach/pkg/server/serverpb"
"github.com/cockroachdb/cockroach/pkg/server/telemetry"
"github.com/cockroachdb/cockroach/pkg/settings"
"github.com/cockroachdb/cockroach/pkg/settings/cluster"
"github.com/cockroachdb/cockroach/pkg/sql"
"github.com/cockroachdb/cockroach/pkg/sql/catalog/descpb"
"github.com/cockroachdb/cockroach/pkg/sql/idxusage"
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree"
"github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb"
"github.com/cockroachdb/cockroach/pkg/testutils"
"github.com/cockroachdb/cockroach/pkg/testutils/serverutils"
"github.com/cockroachdb/cockroach/pkg/testutils/skip"
"github.com/cockroachdb/cockroach/pkg/testutils/sqlutils"
"github.com/cockroachdb/cockroach/pkg/util/hlc"
"github.com/cockroachdb/cockroach/pkg/util/leaktest"
"github.com/cockroachdb/cockroach/pkg/util/log"
"github.com/cockroachdb/cockroach/pkg/util/protoutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/cockroach/pkg/util/uuid"
"github.com/cockroachdb/errors"
"github.com/gogo/protobuf/proto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func getAdminJSONProto(
ts serverutils.TestServerInterface, path string, response protoutil.Message,
) error {
return getAdminJSONProtoWithAdminOption(ts, path, response, true)
}
func getAdminJSONProtoWithAdminOption(
ts serverutils.TestServerInterface, path string, response protoutil.Message, isAdmin bool,
) error {
return serverutils.GetJSONProtoWithAdminOption(ts, adminPrefix+path, response, isAdmin)
}
func postAdminJSONProto(
ts serverutils.TestServerInterface, path string, request, response protoutil.Message,
) error {
return postAdminJSONProtoWithAdminOption(ts, path, request, response, true)
}
func postAdminJSONProtoWithAdminOption(
ts serverutils.TestServerInterface,
path string,
request, response protoutil.Message,
isAdmin bool,
) error {
return serverutils.PostJSONProtoWithAdminOption(ts, adminPrefix+path, request, response, isAdmin)
}
// getText fetches the HTTP response body as text in the form of a
// byte slice from the specified URL.
func getText(ts serverutils.TestServerInterface, url string) ([]byte, error) {
httpClient, err := ts.GetAdminHTTPClient()
if err != nil {
return nil, err
}
resp, err := httpClient.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
// getJSON fetches the JSON from the specified URL and returns
// it as unmarshaled JSON. Returns an error on any failure to fetch
// or unmarshal response body.
func getJSON(ts serverutils.TestServerInterface, url string) (interface{}, error) {
body, err := getText(ts, url)
if err != nil {
return nil, err
}
var jI interface{}
if err := json.Unmarshal(body, &jI); err != nil {
return nil, errors.Wrapf(err, "body is:\n%s", body)
}
return jI, nil
}
// debugURL returns the root debug URL.
func debugURL(s serverutils.TestServerInterface) string {
return s.AdminURL() + debug.Endpoint
}
// TestAdminDebugExpVar verifies that cmdline and memstats variables are
// available via the /debug/vars link.
func TestAdminDebugExpVar(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
jI, err := getJSON(s, debugURL(s)+"vars")
if err != nil {
t.Fatalf("failed to fetch JSON: %v", err)
}
j := jI.(map[string]interface{})
if _, ok := j["cmdline"]; !ok {
t.Error("cmdline not found in JSON response")
}
if _, ok := j["memstats"]; !ok {
t.Error("memstats not found in JSON response")
}
}
// TestAdminDebugMetrics verifies that cmdline and memstats variables are
// available via the /debug/metrics link.
func TestAdminDebugMetrics(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
jI, err := getJSON(s, debugURL(s)+"metrics")
if err != nil {
t.Fatalf("failed to fetch JSON: %v", err)
}
j := jI.(map[string]interface{})
if _, ok := j["cmdline"]; !ok {
t.Error("cmdline not found in JSON response")
}
if _, ok := j["memstats"]; !ok {
t.Error("memstats not found in JSON response")
}
}
// TestAdminDebugPprof verifies that pprof tools are available.
// via the /debug/pprof/* links.
func TestAdminDebugPprof(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
body, err := getText(s, debugURL(s)+"pprof/block?debug=1")
if err != nil {
t.Fatal(err)
}
if exp := "contention:\ncycles/second="; !bytes.Contains(body, []byte(exp)) {
t.Errorf("expected %s to contain %s", body, exp)
}
}
// TestAdminDebugTrace verifies that the net/trace endpoints are available
// via /debug/{requests,events}.
func TestAdminDebugTrace(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
tc := []struct {
segment, search string
}{
{"requests", "<title>/debug/requests</title>"},
{"events", "<title>events</title>"},
}
for _, c := range tc {
body, err := getText(s, debugURL(s)+c.segment)
if err != nil {
t.Fatal(err)
}
if !bytes.Contains(body, []byte(c.search)) {
t.Errorf("expected %s to be contained in %s", c.search, body)
}
}
}
func TestAdminDebugAuth(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
url := debugURL(s)
// Unauthenticated.
client, err := ts.GetUnauthenticatedHTTPClient()
if err != nil {
t.Fatal(err)
}
resp, err := client.Get(url)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected status code %d; got %d", http.StatusUnauthorized, resp.StatusCode)
}
// Authenticated as non-admin.
client, err = ts.GetAuthenticatedHTTPClient(false)
if err != nil {
t.Fatal(err)
}
resp, err = client.Get(url)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected status code %d; got %d", http.StatusUnauthorized, resp.StatusCode)
}
// Authenticated as admin.
client, err = ts.GetAuthenticatedHTTPClient(true)
if err != nil {
t.Fatal(err)
}
resp, err = client.Get(url)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status code %d; got %d", http.StatusOK, resp.StatusCode)
}
}
// TestAdminDebugRedirect verifies that the /debug/ endpoint is redirected to on
// incorrect /debug/ paths.
func TestAdminDebugRedirect(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
expURL := debugURL(s)
origURL := expURL + "incorrect"
// Must be admin to access debug endpoints
client, err := ts.GetAdminHTTPClient()
if err != nil {
t.Fatal(err)
}
// Don't follow redirects automatically.
redirectAttemptedError := errors.New("redirect")
client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
return redirectAttemptedError
}
resp, err := client.Get(origURL)
if urlError := (*url.Error)(nil); errors.As(err, &urlError) &&
errors.Is(urlError.Err, redirectAttemptedError) {
// Ignore the redirectAttemptedError.
err = nil
}
if err != nil {
t.Fatal(err)
} else {
resp.Body.Close()
if resp.StatusCode != http.StatusMovedPermanently {
t.Errorf("expected status code %d; got %d", http.StatusMovedPermanently, resp.StatusCode)
}
if redirectURL, err := resp.Location(); err != nil {
t.Error(err)
} else if foundURL := redirectURL.String(); foundURL != expURL {
t.Errorf("expected location %s; got %s", expURL, foundURL)
}
}
}
func TestAdminAPIDatabases(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
ac := ts.AmbientCtx()
ctx, span := ac.AnnotateCtxWithSpan(context.Background(), "test")
defer span.Finish()
const testdb = "test"
query := "CREATE DATABASE " + testdb
if _, err := db.Exec(query); err != nil {
t.Fatal(err)
}
// Test needs to revoke CONNECT on the public database to properly exercise
// fine-grained permissions logic.
if _, err := db.Exec(fmt.Sprintf("REVOKE CONNECT ON DATABASE %s FROM public", testdb)); err != nil {
t.Fatal(err)
}
if _, err := db.Exec("REVOKE CONNECT ON DATABASE defaultdb FROM public"); err != nil {
t.Fatal(err)
}
// We have to create the non-admin user before calling
// "GRANT ... TO authenticatedUserNameNoAdmin".
// This is done in "GetAuthenticatedHTTPClient".
if _, err := ts.GetAuthenticatedHTTPClient(false); err != nil {
t.Fatal(err)
}
// Grant permissions to view the tables for the given viewing user.
privileges := []string{"CONNECT"}
query = fmt.Sprintf(
"GRANT %s ON DATABASE %s TO %s",
strings.Join(privileges, ", "),
testdb,
authenticatedUserNameNoAdmin().SQLIdentifier(),
)
if _, err := db.Exec(query); err != nil {
t.Fatal(err)
}
// Non admins now also require VIEWACTIVITY.
sysPrivileges := []string{"VIEWACTIVITY"}
query = fmt.Sprintf(
"GRANT SYSTEM %s TO %s",
strings.Join(sysPrivileges, ", "),
authenticatedUserNameNoAdmin().SQLIdentifier(),
)
if _, err := db.Exec(query); err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
expectedDBs []string
isAdmin bool
}{
{[]string{"defaultdb", "postgres", "system", testdb}, true},
{[]string{"postgres", testdb}, false},
} {
t.Run(fmt.Sprintf("isAdmin:%t", tc.isAdmin), func(t *testing.T) {
// Test databases endpoint.
var resp serverpb.DatabasesResponse
if err := getAdminJSONProtoWithAdminOption(
s,
"databases",
&resp,
tc.isAdmin,
); err != nil {
t.Fatal(err)
}
if a, e := len(resp.Databases), len(tc.expectedDBs); a != e {
t.Fatalf("length of result %d != expected %d", a, e)
}
sort.Strings(resp.Databases)
for i, e := range tc.expectedDBs {
if a := resp.Databases[i]; a != e {
t.Fatalf("database name %s != expected %s", a, e)
}
}
// Test database details endpoint.
var details serverpb.DatabaseDetailsResponse
if err := getAdminJSONProtoWithAdminOption(
s,
"databases/"+testdb,
&details,
tc.isAdmin,
); err != nil {
t.Fatal(err)
}
if a, e := len(details.Grants), 3; a != e {
t.Fatalf("# of grants %d != expected %d", a, e)
}
userGrants := make(map[string][]string)
for _, grant := range details.Grants {
switch grant.User {
case username.AdminRole, username.RootUser, authenticatedUserNoAdmin:
userGrants[grant.User] = append(userGrants[grant.User], grant.Privileges...)
default:
t.Fatalf("unknown grant to user %s", grant.User)
}
}
for u, p := range userGrants {
switch u {
case username.AdminRole:
if !reflect.DeepEqual(p, []string{"ALL"}) {
t.Fatalf("privileges %v != expected %v", p, privileges)
}
case username.RootUser:
if !reflect.DeepEqual(p, []string{"ALL"}) {
t.Fatalf("privileges %v != expected %v", p, privileges)
}
case authenticatedUserNoAdmin:
sort.Strings(p)
if !reflect.DeepEqual(p, privileges) {
t.Fatalf("privileges %v != expected %v", p, privileges)
}
default:
t.Fatalf("unknown grant to user %s", u)
}
}
// Verify Descriptor ID.
databaseID, err := ts.admin.queryDatabaseID(ctx, username.RootUserName(), testdb)
if err != nil {
t.Fatal(err)
}
if a, e := details.DescriptorID, int64(databaseID); a != e {
t.Fatalf("db had descriptorID %d, expected %d", a, e)
}
})
}
}
func TestAdminAPIDatabaseDoesNotExist(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
const errPattern = "database.+does not exist"
if err := getAdminJSONProto(s, "databases/i_do_not_exist", nil); !testutils.IsError(err, errPattern) {
t.Fatalf("unexpected error: %v\nexpected: %s", err, errPattern)
}
}
func TestAdminAPIDatabaseSQLInjection(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
const fakedb = "system;DROP DATABASE system;"
const path = "databases/" + fakedb
const errPattern = `target database or schema does not exist`
if err := getAdminJSONProto(s, path, nil); !testutils.IsError(err, errPattern) {
t.Fatalf("unexpected error: %v\nexpected: %s", err, errPattern)
}
}
func TestAdminAPINonTableStats(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartNewTestCluster(t, 3, base.TestClusterArgs{})
defer testCluster.Stopper().Stop(context.Background())
s := testCluster.Server(0)
// Skip TableStatsResponse.Stats comparison, since it includes data which
// aren't consistent (time, bytes).
expectedResponse := serverpb.NonTableStatsResponse{
TimeSeriesStats: &serverpb.TableStatsResponse{
RangeCount: 1,
ReplicaCount: 3,
NodeCount: 3,
},
InternalUseStats: &serverpb.TableStatsResponse{
RangeCount: 11,
ReplicaCount: 15,
NodeCount: 3,
},
}
var resp serverpb.NonTableStatsResponse
if err := getAdminJSONProto(s, "nontablestats", &resp); err != nil {
t.Fatal(err)
}
assertExpectedStatsResponse := func(expected, actual *serverpb.TableStatsResponse) {
assert.Equal(t, expected.RangeCount, actual.RangeCount)
assert.Equal(t, expected.ReplicaCount, actual.ReplicaCount)
assert.Equal(t, expected.NodeCount, actual.NodeCount)
}
assertExpectedStatsResponse(expectedResponse.TimeSeriesStats, resp.TimeSeriesStats)
assertExpectedStatsResponse(expectedResponse.InternalUseStats, resp.InternalUseStats)
}
// Verify that for a cluster with no user data, all the ranges on the Databases
// page consist of:
// 1) the total ranges listed for the system database
// 2) the total ranges listed for the Non-Table data
func TestRangeCount(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
testCluster := serverutils.StartNewTestCluster(t, 3, base.TestClusterArgs{})
require.NoError(t, testCluster.WaitForFullReplication())
defer testCluster.Stopper().Stop(context.Background())
s := testCluster.Server(0)
// Sum up ranges for non-table parts of the system returned
// from the "nontablestats" enpoint.
getNonTableRangeCount := func() (ts, internal int64) {
var resp serverpb.NonTableStatsResponse
if err := getAdminJSONProto(s, "nontablestats", &resp); err != nil {
t.Fatal(err)
}
return resp.TimeSeriesStats.RangeCount, resp.InternalUseStats.RangeCount
}
// Return map tablename=>count obtained from the
// "databases/system/tables/{table}" endpoints.
getSystemTableRangeCount := func() map[string]int64 {
m := map[string]int64{}
var dbResp serverpb.DatabaseDetailsResponse
if err := getAdminJSONProto(s, "databases/system", &dbResp); err != nil {
t.Fatal(err)
}
for _, tableName := range dbResp.TableNames {
var tblResp serverpb.TableStatsResponse
path := "databases/system/tables/" + tableName + "/stats"
if err := getAdminJSONProto(s, path, &tblResp); err != nil {
t.Fatal(err)
}
m[tableName] = tblResp.RangeCount
}
return m
}
getRangeCountFromFullSpan := func() int64 {
adminServer := s.(*TestServer).Server.admin
stats, err := adminServer.statsForSpan(context.Background(), roachpb.Span{
Key: keys.LocalMax,
EndKey: keys.MaxKey,
})
if err != nil {
t.Fatal(err)
}
return stats.RangeCount
}
exp := getRangeCountFromFullSpan()
var systemTableRangeCount int64
sysDBMap := getSystemTableRangeCount()
for _, n := range sysDBMap {
systemTableRangeCount += n
}
tsCount, internalCount := getNonTableRangeCount()
act := tsCount + internalCount + systemTableRangeCount
if !assert.Equal(t,
exp,
act,
) {
t.Log("did nonTableDescriptorRangeCount() change?")
t.Logf(
"claimed numbers:\ntime series = %d\ninternal = %d\nsystemdb = %d (%v)",
tsCount, internalCount, systemTableRangeCount, sysDBMap,
)
db := testCluster.ServerConn(0)
defer db.Close()
runner := sqlutils.MakeSQLRunner(db)
s := sqlutils.MatrixToStr(runner.QueryStr(t, `
select range_id, database_name, table_name, start_pretty, end_pretty from crdb_internal.ranges order by range_id asc`,
))
t.Logf("actual ranges:\n%s", s)
}
}
func TestAdminAPITableDoesNotExist(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
const fakename = "i_do_not_exist"
const badDBPath = "databases/" + fakename + "/tables/foo"
const dbErrPattern = `relation \\"` + fakename + `.foo\\" does not exist`
if err := getAdminJSONProto(s, badDBPath, nil); !testutils.IsError(err, dbErrPattern) {
t.Fatalf("unexpected error: %v\nexpected: %s", err, dbErrPattern)
}
const badTablePath = "databases/system/tables/" + fakename
const tableErrPattern = `relation \\"system.` + fakename + `\\" does not exist`
if err := getAdminJSONProto(s, badTablePath, nil); !testutils.IsError(err, tableErrPattern) {
t.Fatalf("unexpected error: %v\nexpected: %s", err, tableErrPattern)
}
}
func TestAdminAPITableSQLInjection(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails with
// it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
const fakeTable = "users;DROP DATABASE system;"
const path = "databases/system/tables/" + fakeTable
const errPattern = `relation \"system.` + fakeTable + `\" does not exist`
if err := getAdminJSONProto(s, path, nil); !testutils.IsError(err, regexp.QuoteMeta(errPattern)) {
t.Fatalf("unexpected error: %v\nexpected: %s", err, errPattern)
}
}
func TestAdminAPITableDetails(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
for _, tc := range []struct {
name, dbName, tblName, pkName string
}{
{name: "lower", dbName: "test", tblName: "tbl", pkName: "tbl_pkey"},
{name: "lower", dbName: "test", tblName: `testschema.tbl`, pkName: "tbl_pkey"},
{name: "lower with space", dbName: "test test", tblName: `"tbl tbl"`, pkName: "tbl tbl_pkey"},
{name: "upper", dbName: "TEST", tblName: `"TBL"`, pkName: "TBL_pkey"}, // Regression test for issue #14056
} {
t.Run(tc.name, func(t *testing.T) {
s, _, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails
// with it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
escDBName := tree.NameStringP(&tc.dbName)
tblName := tc.tblName
schemaName := "testschema"
ac := ts.AmbientCtx()
ctx, span := ac.AnnotateCtxWithSpan(context.Background(), "test")
defer span.Finish()
tableSchema := `nulls_allowed INT8,
nulls_not_allowed INT8 NOT NULL DEFAULT 1000,
default2 INT8 DEFAULT 2,
string_default STRING DEFAULT 'default_string',
INDEX descidx (default2 DESC)`
setupQueries := []string{
fmt.Sprintf("CREATE DATABASE %s", escDBName),
fmt.Sprintf("CREATE SCHEMA %s", schemaName),
fmt.Sprintf(`CREATE TABLE %s.%s (%s)`, escDBName, tblName, tableSchema),
"CREATE USER readonly",
"CREATE USER app",
fmt.Sprintf("GRANT SELECT ON %s.%s TO readonly", escDBName, tblName),
fmt.Sprintf("GRANT SELECT,UPDATE,DELETE ON %s.%s TO app", escDBName, tblName),
fmt.Sprintf("CREATE STATISTICS test_stats FROM %s.%s", escDBName, tblName),
}
pgURL, cleanupGoDB := sqlutils.PGUrl(
t, s.ServingSQLAddr(), "StartServer" /* prefix */, url.User(username.RootUser))
defer cleanupGoDB()
pgURL.Path = tc.dbName
db, err := gosql.Open("postgres", pgURL.String())
if err != nil {
t.Fatal(err)
}
defer db.Close()
for _, q := range setupQueries {
if _, err := db.Exec(q); err != nil {
t.Fatal(err)
}
}
// Perform API call.
var resp serverpb.TableDetailsResponse
url := fmt.Sprintf("databases/%s/tables/%s", tc.dbName, tblName)
if err := getAdminJSONProto(s, url, &resp); err != nil {
t.Fatal(err)
}
// Verify columns.
expColumns := []serverpb.TableDetailsResponse_Column{
{Name: "nulls_allowed", Type: "INT8", Nullable: true, DefaultValue: ""},
{Name: "nulls_not_allowed", Type: "INT8", Nullable: false, DefaultValue: "1000:::INT8"},
{Name: "default2", Type: "INT8", Nullable: true, DefaultValue: "2:::INT8"},
{Name: "string_default", Type: "STRING", Nullable: true, DefaultValue: "'default_string':::STRING"},
{Name: "rowid", Type: "INT8", Nullable: false, DefaultValue: "unique_rowid()", Hidden: true},
}
testutils.SortStructs(expColumns, "Name")
testutils.SortStructs(resp.Columns, "Name")
if a, e := len(resp.Columns), len(expColumns); a != e {
t.Fatalf("# of result columns %d != expected %d (got: %#v)", a, e, resp.Columns)
}
for i, a := range resp.Columns {
e := expColumns[i]
if a.String() != e.String() {
t.Fatalf("mismatch at column %d: actual %#v != %#v", i, a, e)
}
}
// Verify grants.
expGrants := []serverpb.TableDetailsResponse_Grant{
{User: username.AdminRole, Privileges: []string{"ALL"}},
{User: username.RootUser, Privileges: []string{"ALL"}},
{User: "app", Privileges: []string{"DELETE"}},
{User: "app", Privileges: []string{"SELECT"}},
{User: "app", Privileges: []string{"UPDATE"}},
{User: "readonly", Privileges: []string{"SELECT"}},
}
testutils.SortStructs(expGrants, "User")
testutils.SortStructs(resp.Grants, "User")
if a, e := len(resp.Grants), len(expGrants); a != e {
t.Fatalf("# of grant columns %d != expected %d (got: %#v)", a, e, resp.Grants)
}
for i, a := range resp.Grants {
e := expGrants[i]
sort.Strings(a.Privileges)
sort.Strings(e.Privileges)
if a.String() != e.String() {
t.Fatalf("mismatch at index %d: actual %#v != %#v", i, a, e)
}
}
// Verify indexes.
expIndexes := []serverpb.TableDetailsResponse_Index{
{Name: tc.pkName, Column: "string_default", Direction: "N/A", Unique: true, Seq: 5, Storing: true},
{Name: tc.pkName, Column: "default2", Direction: "N/A", Unique: true, Seq: 4, Storing: true},
{Name: tc.pkName, Column: "nulls_not_allowed", Direction: "N/A", Unique: true, Seq: 3, Storing: true},
{Name: tc.pkName, Column: "nulls_allowed", Direction: "N/A", Unique: true, Seq: 2, Storing: true},
{Name: tc.pkName, Column: "rowid", Direction: "ASC", Unique: true, Seq: 1},
{Name: "descidx", Column: "rowid", Direction: "ASC", Unique: false, Seq: 2, Implicit: true},
{Name: "descidx", Column: "default2", Direction: "DESC", Unique: false, Seq: 1},
}
testutils.SortStructs(expIndexes, "Name", "Seq")
testutils.SortStructs(resp.Indexes, "Name", "Seq")
for i, a := range resp.Indexes {
e := expIndexes[i]
if a.String() != e.String() {
t.Fatalf("mismatch at index %d: actual %#v != %#v", i, a, e)
}
}
// Verify range count.
if a, e := resp.RangeCount, int64(1); a != e {
t.Fatalf("# of ranges %d != expected %d", a, e)
}
// Verify Create Table Statement.
{
showCreateTableQuery := fmt.Sprintf("SHOW CREATE TABLE %s.%s", escDBName, tblName)
row := db.QueryRow(showCreateTableQuery)
var createStmt, tableName string
if err := row.Scan(&tableName, &createStmt); err != nil {
t.Fatal(err)
}
if a, e := resp.CreateTableStatement, createStmt; a != e {
t.Fatalf("mismatched create table statement; expected %s, got %s", e, a)
}
}
// Verify statistics last updated.
{
showStatisticsForTableQuery := fmt.Sprintf("SELECT max(created) AS created FROM [SHOW STATISTICS FOR TABLE %s.%s]", escDBName, tblName)
row := db.QueryRow(showStatisticsForTableQuery)
var createdTs time.Time
if err := row.Scan(&createdTs); err != nil {
t.Fatal(err)
}
if a, e := resp.StatsLastCreatedAt, createdTs; reflect.DeepEqual(a, e) {
t.Fatalf("mismatched statistics creation timestamp; expected %s, got %s", e, a)
}
}
// Verify Descriptor ID.
tableID, err := ts.admin.queryTableID(ctx, username.RootUserName(), tc.dbName, tc.tblName)
if err != nil {
t.Fatal(err)
}
if a, e := resp.DescriptorID, int64(tableID); a != e {
t.Fatalf("table had descriptorID %d, expected %d", a, e)
}
})
}
}
// TestAdminAPIZoneDetails verifies the zone configuration information returned
// for both DatabaseDetailsResponse AND TableDetailsResponse.
func TestAdminAPIZoneDetails(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails
// with it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
ts := s.(*TestServer)
// Create database and table.
ac := ts.AmbientCtx()
ctx, span := ac.AnnotateCtxWithSpan(context.Background(), "test")
defer span.Finish()
setupQueries := []string{
"CREATE DATABASE test",
"CREATE TABLE test.tbl (val STRING)",
}
for _, q := range setupQueries {
if _, err := db.Exec(q); err != nil {
t.Fatalf("error executing '%s': %s", q, err)
}
}
// Function to verify the zone for table "test.tbl" as returned by the Admin
// API.
verifyTblZone := func(
expectedZone zonepb.ZoneConfig, expectedLevel serverpb.ZoneConfigurationLevel,
) {
var resp serverpb.TableDetailsResponse
if err := getAdminJSONProto(s, "databases/test/tables/tbl", &resp); err != nil {
t.Fatal(err)
}
if a, e := &resp.ZoneConfig, &expectedZone; !a.Equal(e) {
t.Errorf("actual table zone config %v did not match expected value %v", a, e)
}
if a, e := resp.ZoneConfigLevel, expectedLevel; a != e {
t.Errorf("actual table ZoneConfigurationLevel %s did not match expected value %s", a, e)
}
if t.Failed() {
t.FailNow()
}
}
// Function to verify the zone for database "test" as returned by the Admin
// API.
verifyDbZone := func(
expectedZone zonepb.ZoneConfig, expectedLevel serverpb.ZoneConfigurationLevel,
) {
var resp serverpb.DatabaseDetailsResponse
if err := getAdminJSONProto(s, "databases/test", &resp); err != nil {
t.Fatal(err)
}
if a, e := &resp.ZoneConfig, &expectedZone; !a.Equal(e) {
t.Errorf("actual db zone config %v did not match expected value %v", a, e)
}
if a, e := resp.ZoneConfigLevel, expectedLevel; a != e {
t.Errorf("actual db ZoneConfigurationLevel %s did not match expected value %s", a, e)
}
if t.Failed() {
t.FailNow()
}
}
// Function to store a zone config for a given object ID.
setZone := func(zoneCfg zonepb.ZoneConfig, id descpb.ID) {
zoneBytes, err := protoutil.Marshal(&zoneCfg)
if err != nil {
t.Fatal(err)
}
const query = `INSERT INTO system.zones VALUES($1, $2)`
if _, err := db.Exec(query, id, zoneBytes); err != nil {
t.Fatalf("error executing '%s': %s", query, err)
}
}
// Verify zone matches cluster default.
verifyDbZone(s.(*TestServer).Cfg.DefaultZoneConfig, serverpb.ZoneConfigurationLevel_CLUSTER)
verifyTblZone(s.(*TestServer).Cfg.DefaultZoneConfig, serverpb.ZoneConfigurationLevel_CLUSTER)
databaseID, err := ts.admin.queryDatabaseID(ctx, username.RootUserName(), "test")
if err != nil {
t.Fatal(err)
}
tableID, err := ts.admin.queryTableID(ctx, username.RootUserName(), "test", "tbl")
if err != nil {
t.Fatal(err)
}
// Apply zone configuration to database and check again.
dbZone := zonepb.ZoneConfig{
RangeMinBytes: proto.Int64(456),
}
setZone(dbZone, databaseID)
verifyDbZone(dbZone, serverpb.ZoneConfigurationLevel_DATABASE)
verifyTblZone(dbZone, serverpb.ZoneConfigurationLevel_DATABASE)
// Apply zone configuration to table and check again.
tblZone := zonepb.ZoneConfig{
RangeMinBytes: proto.Int64(789),
}
setZone(tblZone, tableID)
verifyDbZone(dbZone, serverpb.ZoneConfigurationLevel_DATABASE)
verifyTblZone(tblZone, serverpb.ZoneConfigurationLevel_TABLE)
}
func TestAdminAPIUsers(t *testing.T) {
defer leaktest.AfterTest(t)()
defer log.Scope(t).Close(t)
s, db, _ := serverutils.StartServer(t, base.TestServerArgs{
// Disable the default test tenant for now as this tests fails
// with it enabled. Tracked with #81590.
DisableDefaultTestTenant: true,
})
defer s.Stopper().Stop(context.Background())
// Create sample users.
query := `
INSERT INTO system.users (username, "hashedPassword")
VALUES ('adminUser', 'abc'), ('bob', 'xyz')`
if _, err := db.Exec(query); err != nil {
t.Fatal(err)
}
// Query the API for users.
var resp serverpb.UsersResponse
if err := getAdminJSONProto(s, "users", &resp); err != nil {
t.Fatal(err)
}
expResult := serverpb.UsersResponse{
Users: []serverpb.UsersResponse_User{
{Username: "adminUser"},
{Username: "authentic_user"},
{Username: "bob"},
{Username: "root"},
},