• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //     http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/core/lib/security/authorization/stdout_logger.h"
16 
17 #include <grpc/grpc_audit_logging.h>
18 #include <grpc/support/json.h>
19 #include <grpc/support/port_platform.h>
20 
21 #include <cstdio>
22 #include <memory>
23 #include <string>
24 
25 #include "absl/log/check.h"
26 #include "absl/status/statusor.h"
27 #include "absl/strings/str_format.h"
28 #include "absl/strings/string_view.h"
29 #include "absl/time/clock.h"
30 #include "absl/time/time.h"
31 
32 namespace grpc_core {
33 namespace experimental {
34 
35 namespace {
36 
37 constexpr absl::string_view kName = "stdout_logger";
38 constexpr char kLogFormat[] =
39     "{\"grpc_audit_log\":{\"timestamp\":\"%s\",\"rpc_method\":\"%s\","
40     "\"principal\":\"%s\",\"policy_name\":\"%s\",\"matched_rule\":\"%s\","
41     "\"authorized\":%s}}\n";
42 
43 }  // namespace
44 
Log(const AuditContext & context)45 void StdoutAuditLogger::Log(const AuditContext& context) {
46   absl::FPrintF(stdout, kLogFormat, absl::FormatTime(absl::Now()),
47                 context.rpc_method(), context.principal(),
48                 context.policy_name(), context.matched_rule(),
49                 context.authorized() ? "true" : "false");
50 }
51 
name() const52 absl::string_view StdoutAuditLoggerFactory::Config::name() const {
53   return kName;
54 }
55 
ToString() const56 std::string StdoutAuditLoggerFactory::Config::ToString() const { return "{}"; }
57 
name() const58 absl::string_view StdoutAuditLoggerFactory::name() const { return kName; }
59 
60 absl::StatusOr<std::unique_ptr<AuditLoggerFactory::Config>>
ParseAuditLoggerConfig(const Json &)61 StdoutAuditLoggerFactory::ParseAuditLoggerConfig(const Json&) {
62   return std::make_unique<StdoutAuditLoggerFactory::Config>();
63 }
64 
CreateAuditLogger(std::unique_ptr<AuditLoggerFactory::Config> config)65 std::unique_ptr<AuditLogger> StdoutAuditLoggerFactory::CreateAuditLogger(
66     std::unique_ptr<AuditLoggerFactory::Config> config) {
67   // Sanity check.
68   CHECK(config != nullptr);
69   CHECK(config->name() == name());
70   return std::make_unique<StdoutAuditLogger>();
71 }
72 
73 }  // namespace experimental
74 }  // namespace grpc_core
75