()
| 35 | ) |
| 36 | |
| 37 | func main() { |
| 38 | // Start a fake Elasticsearch server that logs incoming auth credentials |
| 39 | srv := fake.NewServer( |
| 40 | fake.WithLogFn(func(r *http.Request) { |
| 41 | username, password, _ := redact.BasicAuth(r) |
| 42 | slog.Info("server received request", |
| 43 | slog.String("method", r.Method), |
| 44 | slog.String("path", r.URL.Path), |
| 45 | slog.String("username", username), |
| 46 | slog.String("password", password), |
| 47 | ) |
| 48 | }), |
| 49 | fake.WithStatusCode(http.StatusOK), |
| 50 | fake.WithResponseBody([]byte(`{"cluster_name":"example"}`)), |
| 51 | fake.WithHeaders(func(h http.Header) { |
| 52 | h.Set("X-Elastic-Product", "Elasticsearch") |
| 53 | h.Set("Content-Type", "application/json") |
| 54 | }), |
| 55 | ) |
| 56 | defer srv.Close() |
| 57 | |
| 58 | // Create an Elasticsearch client with default credentials and context auth interceptor |
| 59 | es, err := elasticsearch.New( |
| 60 | elasticsearch.WithAddresses(srv.URL()), |
| 61 | elasticsearch.WithBasicAuth("default_user", "default_password"), |
| 62 | elasticsearch.WithTransportOptions(elastictransport.WithInterceptors( |
| 63 | ContextAuthInterceptor(), |
| 64 | )), |
| 65 | ) |
| 66 | if err != nil { |
| 67 | panic(err) |
| 68 | } |
| 69 | |
| 70 | // Request without context override uses default credentials |
| 71 | fmt.Println(">>> Sending request with default credentials") |
| 72 | _, _ = es.Info() |
| 73 | |
| 74 | // Request with context override uses the specified credentials |
| 75 | fmt.Println("\n>>> Sending request with context override (tenant_a)") |
| 76 | ctx := WithBasicAuth(context.Background(), "tenant_a", "tenant_a_secret") |
| 77 | _, _ = es.Info(es.Info.WithContext(ctx)) |
| 78 | |
| 79 | // Another request with different context credentials |
| 80 | fmt.Println("\n>>> Sending request with context override (tenant_b)") |
| 81 | ctx = WithBasicAuth(context.Background(), "tenant_b", "tenant_b_secret") |
| 82 | _, _ = es.Info(es.Info.WithContext(ctx)) |
| 83 | |
| 84 | // Request without context override still uses default credentials |
| 85 | fmt.Println("\n>>> Sending request with default credentials again") |
| 86 | _, _ = es.Info() |
| 87 | } |
| 88 | |
| 89 | // basicAuthKey is the context key for storing basic auth credentials. |
| 90 | type basicAuthKey struct{} |
nothing calls this directly
no test coverage detected