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 <grpc/support/port_platform.h>
16 
17 #include "src/core/lib/security/authorization/stdout_logger.h"
18 
19 #include <cstdio>
20 #include <initializer_list>
21 #include <memory>
22 #include <string>
23 
24 #include "absl/status/statusor.h"
25 #include "absl/strings/str_format.h"
26 #include "absl/strings/string_view.h"
27 #include "absl/time/clock.h"
28 #include "absl/time/time.h"
29 
30 #include <grpc/grpc_audit_logging.h>
31 #include <grpc/support/json.h>
32 #include <grpc/support/log.h>
33 
34 namespace grpc_core {
35 namespace experimental {
36 
37 namespace {
38 
39 constexpr absl::string_view kName = "stdout_logger";
40 constexpr char kLogFormat[] =
41     "{\"grpc_audit_log\":{\"timestamp\":\"%s\",\"rpc_method\":\"%s\","
42     "\"principal\":\"%s\",\"policy_name\":\"%s\",\"matched_rule\":\"%s\","
43     "\"authorized\":%s}}\n";
44 
45 }  // namespace
46 
Log(const AuditContext & context)47 void StdoutAuditLogger::Log(const AuditContext& context) {
48   absl::FPrintF(stdout, kLogFormat, absl::FormatTime(absl::Now()),
49                 context.rpc_method(), context.principal(),
50                 context.policy_name(), context.matched_rule(),
51                 context.authorized() ? "true" : "false");
52 }
53 
name() const54 absl::string_view StdoutAuditLoggerFactory::Config::name() const {
55   return kName;
56 }
57 
ToString() const58 std::string StdoutAuditLoggerFactory::Config::ToString() const { return "{}"; }
59 
name() const60 absl::string_view StdoutAuditLoggerFactory::name() const { return kName; }
61 
62 absl::StatusOr<std::unique_ptr<AuditLoggerFactory::Config>>
ParseAuditLoggerConfig(const Json &)63 StdoutAuditLoggerFactory::ParseAuditLoggerConfig(const Json&) {
64   return std::make_unique<StdoutAuditLoggerFactory::Config>();
65 }
66 
CreateAuditLogger(std::unique_ptr<AuditLoggerFactory::Config> config)67 std::unique_ptr<AuditLogger> StdoutAuditLoggerFactory::CreateAuditLogger(
68     std::unique_ptr<AuditLoggerFactory::Config> config) {
69   // Sanity check.
70   GPR_ASSERT(config != nullptr && config->name() == name());
71   return std::make_unique<StdoutAuditLogger>();
72 }
73 
74 }  // namespace experimental
75 }  // namespace grpc_core
76