### RPC Backend Framework Example
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/toc.html
An example of a framework designed for RPC backends, demonstrating how to enforce security and reliability in service development.
```Go
package main
import (
"context"
"fmt"
"log"
"net/http"
"time"
)
// Define a simple RPC request and response
type Request struct {
Method string
Params []interface{}
}
type Response struct {
Result interface{}/
Error string
}
// Define a handler function signature
type HandlerFunc func(ctx context.Context, params []interface{}) (interface{}, error)
// Simple RPC server structure
type Server struct {
handlers map[string]HandlerFunc
}
func NewServer() *Server {
return &Server{
handlers: make(map[string]HandlerFunc),
}
}
func (s *Server) RegisterHandler(method string, handler HandlerFunc) {
s.handlers[method] = handler
}
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
var req Request
if err := json.NewDecoder(r.Body).Decode(&req);
err != nil {
http.Error(w, "Invalid request body", http.StatusBadRequest)
return
}
handler, ok := s.handlers[req.Method]
if !ok {
resp := Response{Error: "Method not found"}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) // 5-second timeout
defer cancel()
result, err := handler(ctx, req.Params)
if err != nil {
resp := Response{Error: err.Error()}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
resp := Response{Result: result}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// Example handler functions
func add(ctx context.Context, params []interface{}) (interface{}, error) {
if len(params) != 2 {
return nil, fmt.Errorf("invalid number of arguments")
}
a, ok := params[0].(float64)
b, ok := params[1].(float64)
if !ok {
return nil, fmt.Errorf("invalid argument types")
}
return a + b, nil
}
func greet(ctx context.Context, params []interface{}) (interface{}, error) {
if len(params) != 1 {
return nil, fmt.Errorf("invalid number of arguments")
}
name, ok := params[0].(string)
if !ok {
return nil, fmt.Errorf("invalid argument types")
}
return "Hello, " + name + "!", nil
}
func main() {
server := NewServer()
server.RegisterHandler("add", add)
server.RegisterHandler("greet", greet)
http.Handle("/rpc", server)
fmt.Println("Server listening on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
```
--------------------------------
### Running AddressSanitizer (ASan) Example
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch13.html
This example demonstrates how to compile and run a C++ program with a use-after-free bug using AddressSanitizer. The `-fsanitize=address` flag enables ASan instrumentation.
```bash
echo "int main() { int *x = (int*)malloc(10*sizeof(int)); free(x); int y = x[5]; return 0; }" > use_after_free.c
clang -fsanitize=address use_after_free.c -o use_after_free
./use_after_free
```
--------------------------------
### Bazel Configuration for ASan and libFuzzer
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch13.html
Example Bazel configuration to enable AddressSanitizer (ASan) and build libFuzzer-based fuzzers. This is useful for creating fuzzer-friendly builds.
```bash
build:asan --copt -fsanitize=address --copt -O1 --copt -g -c dbg
build:asan --linkopt -fsanitize=address --copt -O1 --copt -g -c dbg
build:asan --copt -fno-omit-frame-pointer --copt -O1 --copt -g -c dbg
```
--------------------------------
### Rendering a script tag with Closure Templates
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch12.html
This example shows how to render a script tag using Closure Templates. It demonstrates the requirement to use a `TrustedResourceUrl` for the URL attribute.
```java
{template .foo kind="html"}{/template}
```
--------------------------------
### Unit Test Example using GoogleTest
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch13.html
A simple unit test written using the GoogleTest framework for C++. It demonstrates how to test individual software components in isolation.
```C++
#include
// A simple test case
TEST(MyTestSuite, MyTestName) {
EXPECT_TRUE(true);
}
```
--------------------------------
### Bazel Build Rule for Java Compilation with Error Prone
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch13.html
This example shows a Bazel build command that triggers a Java compilation. The output indicates an error detected by Error Prone due to type incompatibility.
```bash
bazel build :hello
```
--------------------------------
### Verify Update Signature
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch09.html
A Python function signature demonstrating the verification of a release signature against a key database. This is a conceptual example.
```python
def IsUpdateAllowed(self, Release, KeyDatabase) -> bool:
return VerifySignature(Release, KeyDatabase)
```
--------------------------------
### Building and Running the Fuzzer
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch13.html
Commands to build the fuzz driver using Bazel and run it with specific configurations, including AddressSanitizer and a time limit.
```bash
CC=clang-6.0 CXX=clang++-6.0 bazel build --config=asan :fuzzer
```
```bash
mkdir synthetic_corpus
ASAN_SYMBOLIZER_PATH=/usr/lib/llvm-6.0/bin/llvm-symbolizer bazel-bin/fuzzer \
-max_total_time 300 -print_final_stats synthetic_corpus/
```
--------------------------------
### Authorization Interceptor Implementation
Source: https://github.com/google/building-secure-and-reliable-systems/blob/main/raw/ch12.html
An example of an authorization interceptor that checks if the requesting user is in an allowlisted set of roles before proceeding. It modifies the context by adding verified caller information.
```Go
type authzInterceptor struct {
allowedRoles map[string]bool
}
func (ai *authzInterceptor) Before(ctx context.Context, req *Request) (context.Context, error) {
// callInfo was populated by the framework.
callInfo, err := FromContext(ctx)
if err != nil { return ctx, err }
if ai.allowedRoles[callInfo.User] { return ctx, nil }
return ctx, fmt.Errorf("Unauthorized request from %q", callInfo.User)
}
func (*authzInterceptor) After(ctx context.Context, resp *Response) error {
return nil // Nothing left to do here after the RPC is handled.
}
```