grpc_authz_end2end_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. /*
  2. *
  3. * Copyright 2021 gRPC authors.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. *
  17. */
  18. package authz_test
  19. import (
  20. "context"
  21. "crypto/tls"
  22. "crypto/x509"
  23. "io"
  24. "net"
  25. "os"
  26. "testing"
  27. "time"
  28. "google.golang.org/grpc"
  29. "google.golang.org/grpc/authz"
  30. "google.golang.org/grpc/codes"
  31. "google.golang.org/grpc/credentials"
  32. "google.golang.org/grpc/credentials/insecure"
  33. "google.golang.org/grpc/internal/grpctest"
  34. "google.golang.org/grpc/metadata"
  35. "google.golang.org/grpc/status"
  36. "google.golang.org/grpc/testdata"
  37. testgrpc "google.golang.org/grpc/interop/grpc_testing"
  38. testpb "google.golang.org/grpc/interop/grpc_testing"
  39. )
  40. type testServer struct {
  41. testgrpc.UnimplementedTestServiceServer
  42. }
  43. func (s *testServer) UnaryCall(ctx context.Context, req *testpb.SimpleRequest) (*testpb.SimpleResponse, error) {
  44. return &testpb.SimpleResponse{}, nil
  45. }
  46. func (s *testServer) StreamingInputCall(stream testgrpc.TestService_StreamingInputCallServer) error {
  47. for {
  48. _, err := stream.Recv()
  49. if err == io.EOF {
  50. return stream.SendAndClose(&testpb.StreamingInputCallResponse{})
  51. }
  52. if err != nil {
  53. return err
  54. }
  55. }
  56. }
  57. type s struct {
  58. grpctest.Tester
  59. }
  60. func Test(t *testing.T) {
  61. grpctest.RunSubTests(t, s{})
  62. }
  63. var authzTests = map[string]struct {
  64. authzPolicy string
  65. md metadata.MD
  66. wantStatus *status.Status
  67. }{
  68. "DeniesRPCMatchInDenyNoMatchInAllow": {
  69. authzPolicy: `{
  70. "name": "authz",
  71. "allow_rules":
  72. [
  73. {
  74. "name": "allow_StreamingOutputCall",
  75. "request": {
  76. "paths":
  77. [
  78. "/grpc.testing.TestService/StreamingOutputCall"
  79. ]
  80. }
  81. }
  82. ],
  83. "deny_rules":
  84. [
  85. {
  86. "name": "deny_TestServiceCalls",
  87. "request": {
  88. "paths":
  89. [
  90. "/grpc.testing.TestService/*"
  91. ],
  92. "headers":
  93. [
  94. {
  95. "key": "key-abc",
  96. "values":
  97. [
  98. "val-abc",
  99. "val-def"
  100. ]
  101. }
  102. ]
  103. }
  104. }
  105. ]
  106. }`,
  107. md: metadata.Pairs("key-abc", "val-abc"),
  108. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  109. },
  110. "DeniesRPCMatchInDenyAndAllow": {
  111. authzPolicy: `{
  112. "name": "authz",
  113. "allow_rules":
  114. [
  115. {
  116. "name": "allow_all",
  117. "request": {
  118. "paths":
  119. [
  120. "*"
  121. ]
  122. }
  123. }
  124. ],
  125. "deny_rules":
  126. [
  127. {
  128. "name": "deny_all",
  129. "request": {
  130. "paths":
  131. [
  132. "*"
  133. ]
  134. }
  135. }
  136. ]
  137. }`,
  138. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  139. },
  140. "AllowsRPCNoMatchInDenyMatchInAllow": {
  141. authzPolicy: `{
  142. "name": "authz",
  143. "allow_rules":
  144. [
  145. {
  146. "name": "allow_all"
  147. }
  148. ],
  149. "deny_rules":
  150. [
  151. {
  152. "name": "deny_TestServiceCalls",
  153. "request": {
  154. "paths":
  155. [
  156. "/grpc.testing.TestService/UnaryCall",
  157. "/grpc.testing.TestService/StreamingInputCall"
  158. ],
  159. "headers":
  160. [
  161. {
  162. "key": "key-abc",
  163. "values":
  164. [
  165. "val-abc",
  166. "val-def"
  167. ]
  168. }
  169. ]
  170. }
  171. }
  172. ]
  173. }`,
  174. md: metadata.Pairs("key-xyz", "val-xyz"),
  175. wantStatus: status.New(codes.OK, ""),
  176. },
  177. "DeniesRPCNoMatchInDenyAndAllow": {
  178. authzPolicy: `{
  179. "name": "authz",
  180. "allow_rules":
  181. [
  182. {
  183. "name": "allow_some_user",
  184. "source": {
  185. "principals":
  186. [
  187. "some_user"
  188. ]
  189. }
  190. }
  191. ],
  192. "deny_rules":
  193. [
  194. {
  195. "name": "deny_StreamingOutputCall",
  196. "request": {
  197. "paths":
  198. [
  199. "/grpc.testing.TestService/StreamingOutputCall"
  200. ]
  201. }
  202. }
  203. ]
  204. }`,
  205. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  206. },
  207. "AllowsRPCEmptyDenyMatchInAllow": {
  208. authzPolicy: `{
  209. "name": "authz",
  210. "allow_rules":
  211. [
  212. {
  213. "name": "allow_UnaryCall",
  214. "request":
  215. {
  216. "paths":
  217. [
  218. "/grpc.testing.TestService/UnaryCall"
  219. ]
  220. }
  221. },
  222. {
  223. "name": "allow_StreamingInputCall",
  224. "request":
  225. {
  226. "paths":
  227. [
  228. "/grpc.testing.TestService/StreamingInputCall"
  229. ]
  230. }
  231. }
  232. ]
  233. }`,
  234. wantStatus: status.New(codes.OK, ""),
  235. },
  236. "DeniesRPCEmptyDenyNoMatchInAllow": {
  237. authzPolicy: `{
  238. "name": "authz",
  239. "allow_rules":
  240. [
  241. {
  242. "name": "allow_StreamingOutputCall",
  243. "request":
  244. {
  245. "paths":
  246. [
  247. "/grpc.testing.TestService/StreamingOutputCall"
  248. ]
  249. }
  250. }
  251. ]
  252. }`,
  253. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  254. },
  255. "DeniesRPCRequestWithPrincipalsFieldOnUnauthenticatedConnection": {
  256. authzPolicy: `{
  257. "name": "authz",
  258. "allow_rules":
  259. [
  260. {
  261. "name": "allow_authenticated",
  262. "source": {
  263. "principals": ["*", ""]
  264. }
  265. }
  266. ]
  267. }`,
  268. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  269. },
  270. "DeniesRPCRequestNoMatchInAllowFailsPresenceMatch": {
  271. authzPolicy: `{
  272. "name": "authz",
  273. "allow_rules":
  274. [
  275. {
  276. "name": "allow_TestServiceCalls",
  277. "request": {
  278. "paths":
  279. [
  280. "/grpc.testing.TestService/*"
  281. ],
  282. "headers":
  283. [
  284. {
  285. "key": "key-abc",
  286. "values":
  287. [
  288. "*"
  289. ]
  290. }
  291. ]
  292. }
  293. }
  294. ]
  295. }`,
  296. md: metadata.Pairs("key-abc", ""),
  297. wantStatus: status.New(codes.PermissionDenied, "unauthorized RPC request rejected"),
  298. },
  299. }
  300. func (s) TestStaticPolicyEnd2End(t *testing.T) {
  301. for name, test := range authzTests {
  302. t.Run(name, func(t *testing.T) {
  303. // Start a gRPC server with gRPC authz unary and stream server interceptors.
  304. i, _ := authz.NewStatic(test.authzPolicy)
  305. s := grpc.NewServer(
  306. grpc.ChainUnaryInterceptor(i.UnaryInterceptor),
  307. grpc.ChainStreamInterceptor(i.StreamInterceptor))
  308. defer s.Stop()
  309. testgrpc.RegisterTestServiceServer(s, &testServer{})
  310. lis, err := net.Listen("tcp", "localhost:0")
  311. if err != nil {
  312. t.Fatalf("error listening: %v", err)
  313. }
  314. go s.Serve(lis)
  315. // Establish a connection to the server.
  316. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
  317. if err != nil {
  318. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  319. }
  320. defer clientConn.Close()
  321. client := testgrpc.NewTestServiceClient(clientConn)
  322. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  323. defer cancel()
  324. ctx = metadata.NewOutgoingContext(ctx, test.md)
  325. // Verifying authorization decision for Unary RPC.
  326. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  327. if got := status.Convert(err); got.Code() != test.wantStatus.Code() || got.Message() != test.wantStatus.Message() {
  328. t.Fatalf("[UnaryCall] error want:{%v} got:{%v}", test.wantStatus.Err(), got.Err())
  329. }
  330. // Verifying authorization decision for Streaming RPC.
  331. stream, err := client.StreamingInputCall(ctx)
  332. if err != nil {
  333. t.Fatalf("failed StreamingInputCall err: %v", err)
  334. }
  335. req := &testpb.StreamingInputCallRequest{
  336. Payload: &testpb.Payload{
  337. Body: []byte("hi"),
  338. },
  339. }
  340. if err := stream.Send(req); err != nil && err != io.EOF {
  341. t.Fatalf("failed stream.Send err: %v", err)
  342. }
  343. _, err = stream.CloseAndRecv()
  344. if got := status.Convert(err); got.Code() != test.wantStatus.Code() || got.Message() != test.wantStatus.Message() {
  345. t.Fatalf("[StreamingCall] error want:{%v} got:{%v}", test.wantStatus.Err(), got.Err())
  346. }
  347. })
  348. }
  349. }
  350. func (s) TestAllowsRPCRequestWithPrincipalsFieldOnTLSAuthenticatedConnection(t *testing.T) {
  351. authzPolicy := `{
  352. "name": "authz",
  353. "allow_rules":
  354. [
  355. {
  356. "name": "allow_authenticated",
  357. "source": {
  358. "principals": ["*", ""]
  359. }
  360. }
  361. ]
  362. }`
  363. // Start a gRPC server with gRPC authz unary server interceptor.
  364. i, _ := authz.NewStatic(authzPolicy)
  365. creds, err := credentials.NewServerTLSFromFile(testdata.Path("x509/server1_cert.pem"), testdata.Path("x509/server1_key.pem"))
  366. if err != nil {
  367. t.Fatalf("failed to generate credentials: %v", err)
  368. }
  369. s := grpc.NewServer(
  370. grpc.Creds(creds),
  371. grpc.ChainUnaryInterceptor(i.UnaryInterceptor))
  372. defer s.Stop()
  373. testgrpc.RegisterTestServiceServer(s, &testServer{})
  374. lis, err := net.Listen("tcp", "localhost:0")
  375. if err != nil {
  376. t.Fatalf("error listening: %v", err)
  377. }
  378. go s.Serve(lis)
  379. // Establish a connection to the server.
  380. creds, err = credentials.NewClientTLSFromFile(testdata.Path("x509/server_ca_cert.pem"), "x.test.example.com")
  381. if err != nil {
  382. t.Fatalf("failed to load credentials: %v", err)
  383. }
  384. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(creds))
  385. if err != nil {
  386. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  387. }
  388. defer clientConn.Close()
  389. client := testgrpc.NewTestServiceClient(clientConn)
  390. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  391. defer cancel()
  392. // Verifying authorization decision.
  393. if _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  394. t.Fatalf("client.UnaryCall(_, _) = %v; want nil", err)
  395. }
  396. }
  397. func (s) TestAllowsRPCRequestWithPrincipalsFieldOnMTLSAuthenticatedConnection(t *testing.T) {
  398. authzPolicy := `{
  399. "name": "authz",
  400. "allow_rules":
  401. [
  402. {
  403. "name": "allow_authenticated",
  404. "source": {
  405. "principals": ["*", ""]
  406. }
  407. }
  408. ]
  409. }`
  410. // Start a gRPC server with gRPC authz unary server interceptor.
  411. i, _ := authz.NewStatic(authzPolicy)
  412. cert, err := tls.LoadX509KeyPair(testdata.Path("x509/server1_cert.pem"), testdata.Path("x509/server1_key.pem"))
  413. if err != nil {
  414. t.Fatalf("tls.LoadX509KeyPair(x509/server1_cert.pem, x509/server1_key.pem) failed: %v", err)
  415. }
  416. ca, err := os.ReadFile(testdata.Path("x509/client_ca_cert.pem"))
  417. if err != nil {
  418. t.Fatalf("os.ReadFile(x509/client_ca_cert.pem) failed: %v", err)
  419. }
  420. certPool := x509.NewCertPool()
  421. if !certPool.AppendCertsFromPEM(ca) {
  422. t.Fatal("failed to append certificates")
  423. }
  424. creds := credentials.NewTLS(&tls.Config{
  425. ClientAuth: tls.RequireAndVerifyClientCert,
  426. Certificates: []tls.Certificate{cert},
  427. ClientCAs: certPool,
  428. })
  429. s := grpc.NewServer(
  430. grpc.Creds(creds),
  431. grpc.ChainUnaryInterceptor(i.UnaryInterceptor))
  432. defer s.Stop()
  433. testgrpc.RegisterTestServiceServer(s, &testServer{})
  434. lis, err := net.Listen("tcp", "localhost:0")
  435. if err != nil {
  436. t.Fatalf("error listening: %v", err)
  437. }
  438. go s.Serve(lis)
  439. // Establish a connection to the server.
  440. cert, err = tls.LoadX509KeyPair(testdata.Path("x509/client1_cert.pem"), testdata.Path("x509/client1_key.pem"))
  441. if err != nil {
  442. t.Fatalf("tls.LoadX509KeyPair(x509/client1_cert.pem, x509/client1_key.pem) failed: %v", err)
  443. }
  444. ca, err = os.ReadFile(testdata.Path("x509/server_ca_cert.pem"))
  445. if err != nil {
  446. t.Fatalf("os.ReadFile(x509/server_ca_cert.pem) failed: %v", err)
  447. }
  448. roots := x509.NewCertPool()
  449. if !roots.AppendCertsFromPEM(ca) {
  450. t.Fatal("failed to append certificates")
  451. }
  452. creds = credentials.NewTLS(&tls.Config{
  453. Certificates: []tls.Certificate{cert},
  454. RootCAs: roots,
  455. ServerName: "x.test.example.com",
  456. })
  457. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(creds))
  458. if err != nil {
  459. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  460. }
  461. defer clientConn.Close()
  462. client := testgrpc.NewTestServiceClient(clientConn)
  463. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  464. defer cancel()
  465. // Verifying authorization decision.
  466. if _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{}); err != nil {
  467. t.Fatalf("client.UnaryCall(_, _) = %v; want nil", err)
  468. }
  469. }
  470. func (s) TestFileWatcherEnd2End(t *testing.T) {
  471. for name, test := range authzTests {
  472. t.Run(name, func(t *testing.T) {
  473. file := createTmpPolicyFile(t, name, []byte(test.authzPolicy))
  474. i, _ := authz.NewFileWatcher(file, 1*time.Second)
  475. defer i.Close()
  476. // Start a gRPC server with gRPC authz unary and stream server interceptors.
  477. s := grpc.NewServer(
  478. grpc.ChainUnaryInterceptor(i.UnaryInterceptor),
  479. grpc.ChainStreamInterceptor(i.StreamInterceptor))
  480. defer s.Stop()
  481. testgrpc.RegisterTestServiceServer(s, &testServer{})
  482. lis, err := net.Listen("tcp", "localhost:0")
  483. if err != nil {
  484. t.Fatalf("error listening: %v", err)
  485. }
  486. defer lis.Close()
  487. go s.Serve(lis)
  488. // Establish a connection to the server.
  489. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
  490. if err != nil {
  491. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  492. }
  493. defer clientConn.Close()
  494. client := testgrpc.NewTestServiceClient(clientConn)
  495. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  496. defer cancel()
  497. ctx = metadata.NewOutgoingContext(ctx, test.md)
  498. // Verifying authorization decision for Unary RPC.
  499. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  500. if got := status.Convert(err); got.Code() != test.wantStatus.Code() || got.Message() != test.wantStatus.Message() {
  501. t.Fatalf("[UnaryCall] error want:{%v} got:{%v}", test.wantStatus.Err(), got.Err())
  502. }
  503. // Verifying authorization decision for Streaming RPC.
  504. stream, err := client.StreamingInputCall(ctx)
  505. if err != nil {
  506. t.Fatalf("failed StreamingInputCall err: %v", err)
  507. }
  508. req := &testpb.StreamingInputCallRequest{
  509. Payload: &testpb.Payload{
  510. Body: []byte("hi"),
  511. },
  512. }
  513. if err := stream.Send(req); err != nil && err != io.EOF {
  514. t.Fatalf("failed stream.Send err: %v", err)
  515. }
  516. _, err = stream.CloseAndRecv()
  517. if got := status.Convert(err); got.Code() != test.wantStatus.Code() || got.Message() != test.wantStatus.Message() {
  518. t.Fatalf("[StreamingCall] error want:{%v} got:{%v}", test.wantStatus.Err(), got.Err())
  519. }
  520. })
  521. }
  522. }
  523. func retryUntil(ctx context.Context, tsc testgrpc.TestServiceClient, want *status.Status) (lastErr error) {
  524. for ctx.Err() == nil {
  525. _, lastErr = tsc.UnaryCall(ctx, &testpb.SimpleRequest{})
  526. if s := status.Convert(lastErr); s.Code() == want.Code() && s.Message() == want.Message() {
  527. return nil
  528. }
  529. time.Sleep(20 * time.Millisecond)
  530. }
  531. return lastErr
  532. }
  533. func (s) TestFileWatcher_ValidPolicyRefresh(t *testing.T) {
  534. valid1 := authzTests["DeniesRPCMatchInDenyAndAllow"]
  535. file := createTmpPolicyFile(t, "valid_policy_refresh", []byte(valid1.authzPolicy))
  536. i, _ := authz.NewFileWatcher(file, 100*time.Millisecond)
  537. defer i.Close()
  538. // Start a gRPC server with gRPC authz unary server interceptor.
  539. s := grpc.NewServer(
  540. grpc.ChainUnaryInterceptor(i.UnaryInterceptor))
  541. defer s.Stop()
  542. testgrpc.RegisterTestServiceServer(s, &testServer{})
  543. lis, err := net.Listen("tcp", "localhost:0")
  544. if err != nil {
  545. t.Fatalf("error listening: %v", err)
  546. }
  547. defer lis.Close()
  548. go s.Serve(lis)
  549. // Establish a connection to the server.
  550. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
  551. if err != nil {
  552. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  553. }
  554. defer clientConn.Close()
  555. client := testgrpc.NewTestServiceClient(clientConn)
  556. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  557. defer cancel()
  558. // Verifying authorization decision.
  559. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  560. if got := status.Convert(err); got.Code() != valid1.wantStatus.Code() || got.Message() != valid1.wantStatus.Message() {
  561. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got.Err(), valid1.wantStatus.Err())
  562. }
  563. // Rewrite the file with a different valid authorization policy.
  564. valid2 := authzTests["AllowsRPCEmptyDenyMatchInAllow"]
  565. if err := os.WriteFile(file, []byte(valid2.authzPolicy), os.ModePerm); err != nil {
  566. t.Fatalf("os.WriteFile(%q) failed: %v", file, err)
  567. }
  568. // Verifying authorization decision.
  569. if got := retryUntil(ctx, client, valid2.wantStatus); got != nil {
  570. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got, valid2.wantStatus.Err())
  571. }
  572. }
  573. func (s) TestFileWatcher_InvalidPolicySkipReload(t *testing.T) {
  574. valid := authzTests["DeniesRPCMatchInDenyAndAllow"]
  575. file := createTmpPolicyFile(t, "invalid_policy_skip_reload", []byte(valid.authzPolicy))
  576. i, _ := authz.NewFileWatcher(file, 20*time.Millisecond)
  577. defer i.Close()
  578. // Start a gRPC server with gRPC authz unary server interceptors.
  579. s := grpc.NewServer(
  580. grpc.ChainUnaryInterceptor(i.UnaryInterceptor))
  581. defer s.Stop()
  582. testgrpc.RegisterTestServiceServer(s, &testServer{})
  583. lis, err := net.Listen("tcp", "localhost:0")
  584. if err != nil {
  585. t.Fatalf("error listening: %v", err)
  586. }
  587. defer lis.Close()
  588. go s.Serve(lis)
  589. // Establish a connection to the server.
  590. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
  591. if err != nil {
  592. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  593. }
  594. defer clientConn.Close()
  595. client := testgrpc.NewTestServiceClient(clientConn)
  596. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  597. defer cancel()
  598. // Verifying authorization decision.
  599. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  600. if got := status.Convert(err); got.Code() != valid.wantStatus.Code() || got.Message() != valid.wantStatus.Message() {
  601. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got.Err(), valid.wantStatus.Err())
  602. }
  603. // Skips the invalid policy update, and continues to use the valid policy.
  604. if err := os.WriteFile(file, []byte("{}"), os.ModePerm); err != nil {
  605. t.Fatalf("os.WriteFile(%q) failed: %v", file, err)
  606. }
  607. // Wait 40 ms for background go routine to read updated files.
  608. time.Sleep(40 * time.Millisecond)
  609. // Verifying authorization decision.
  610. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  611. if got := status.Convert(err); got.Code() != valid.wantStatus.Code() || got.Message() != valid.wantStatus.Message() {
  612. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got.Err(), valid.wantStatus.Err())
  613. }
  614. }
  615. func (s) TestFileWatcher_RecoversFromReloadFailure(t *testing.T) {
  616. valid1 := authzTests["DeniesRPCMatchInDenyAndAllow"]
  617. file := createTmpPolicyFile(t, "recovers_from_reload_failure", []byte(valid1.authzPolicy))
  618. i, _ := authz.NewFileWatcher(file, 100*time.Millisecond)
  619. defer i.Close()
  620. // Start a gRPC server with gRPC authz unary server interceptors.
  621. s := grpc.NewServer(
  622. grpc.ChainUnaryInterceptor(i.UnaryInterceptor))
  623. defer s.Stop()
  624. testgrpc.RegisterTestServiceServer(s, &testServer{})
  625. lis, err := net.Listen("tcp", "localhost:0")
  626. if err != nil {
  627. t.Fatalf("error listening: %v", err)
  628. }
  629. defer lis.Close()
  630. go s.Serve(lis)
  631. // Establish a connection to the server.
  632. clientConn, err := grpc.Dial(lis.Addr().String(), grpc.WithTransportCredentials(insecure.NewCredentials()))
  633. if err != nil {
  634. t.Fatalf("grpc.Dial(%v) failed: %v", lis.Addr().String(), err)
  635. }
  636. defer clientConn.Close()
  637. client := testgrpc.NewTestServiceClient(clientConn)
  638. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  639. defer cancel()
  640. // Verifying authorization decision.
  641. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  642. if got := status.Convert(err); got.Code() != valid1.wantStatus.Code() || got.Message() != valid1.wantStatus.Message() {
  643. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got.Err(), valid1.wantStatus.Err())
  644. }
  645. // Skips the invalid policy update, and continues to use the valid policy.
  646. if err := os.WriteFile(file, []byte("{}"), os.ModePerm); err != nil {
  647. t.Fatalf("os.WriteFile(%q) failed: %v", file, err)
  648. }
  649. // Wait 120 ms for background go routine to read updated files.
  650. time.Sleep(120 * time.Millisecond)
  651. // Verifying authorization decision.
  652. _, err = client.UnaryCall(ctx, &testpb.SimpleRequest{})
  653. if got := status.Convert(err); got.Code() != valid1.wantStatus.Code() || got.Message() != valid1.wantStatus.Message() {
  654. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got.Err(), valid1.wantStatus.Err())
  655. }
  656. // Rewrite the file with a different valid authorization policy.
  657. valid2 := authzTests["AllowsRPCEmptyDenyMatchInAllow"]
  658. if err := os.WriteFile(file, []byte(valid2.authzPolicy), os.ModePerm); err != nil {
  659. t.Fatalf("os.WriteFile(%q) failed: %v", file, err)
  660. }
  661. // Verifying authorization decision.
  662. if got := retryUntil(ctx, client, valid2.wantStatus); got != nil {
  663. t.Fatalf("client.UnaryCall(_, _) = %v; want = %v", got, valid2.wantStatus.Err())
  664. }
  665. }