|
| 1 | +// Licensed to Elasticsearch B.V. under one or more contributor |
| 2 | +// license agreements. See the NOTICE file distributed with |
| 3 | +// this work for additional information regarding copyright |
| 4 | +// ownership. Elasticsearch B.V. licenses this file to you under |
| 5 | +// the Apache License, Version 2.0 (the "License"); you may |
| 6 | +// 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, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +// This example demonstrates how to use Interceptors to override |
| 19 | +// authentication credentials on a per-request basis using context.Context. |
| 20 | +// |
| 21 | +// This pattern is useful when different requests need different credentials, |
| 22 | +// such as multi-tenant applications or impersonation scenarios. |
| 23 | +package main |
| 24 | + |
| 25 | +import ( |
| 26 | + "context" |
| 27 | + "fmt" |
| 28 | + "log/slog" |
| 29 | + "net/http" |
| 30 | + |
| 31 | + "github.com/elastic/elastic-transport-go/v8/elastictransport" |
| 32 | + "github.com/elastic/go-elasticsearch/v9" |
| 33 | + "github.com/elastic/go-elasticsearch/v9/_examples/interceptor/internal/fake" |
| 34 | + "github.com/elastic/go-elasticsearch/v9/_examples/interceptor/internal/redact" |
| 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.NewClient(elasticsearch.Config{ |
| 60 | + Addresses: []string{srv.URL()}, |
| 61 | + Username: "default_user", |
| 62 | + Password: "default_password", |
| 63 | + Interceptors: []elastictransport.InterceptorFunc{ |
| 64 | + ContextAuthInterceptor(), |
| 65 | + }, |
| 66 | + }) |
| 67 | + if err != nil { |
| 68 | + panic(err) |
| 69 | + } |
| 70 | + |
| 71 | + // Request without context override uses default credentials |
| 72 | + fmt.Println(">>> Sending request with default credentials") |
| 73 | + _, _ = es.Info() |
| 74 | + |
| 75 | + // Request with context override uses the specified credentials |
| 76 | + fmt.Println("\n>>> Sending request with context override (tenant_a)") |
| 77 | + ctx := WithBasicAuth(context.Background(), "tenant_a", "tenant_a_secret") |
| 78 | + _, _ = es.Info(es.Info.WithContext(ctx)) |
| 79 | + |
| 80 | + // Another request with different context credentials |
| 81 | + fmt.Println("\n>>> Sending request with context override (tenant_b)") |
| 82 | + ctx = WithBasicAuth(context.Background(), "tenant_b", "tenant_b_secret") |
| 83 | + _, _ = es.Info(es.Info.WithContext(ctx)) |
| 84 | + |
| 85 | + // Request without context override still uses default credentials |
| 86 | + fmt.Println("\n>>> Sending request with default credentials again") |
| 87 | + _, _ = es.Info() |
| 88 | +} |
| 89 | + |
| 90 | +// basicAuthKey is the context key for storing basic auth credentials. |
| 91 | +type basicAuthKey struct{} |
| 92 | + |
| 93 | +type basicAuthValue struct { |
| 94 | + username string |
| 95 | + password string |
| 96 | +} |
| 97 | + |
| 98 | +// WithBasicAuth returns a context with basic auth credentials attached. |
| 99 | +// Use this to override the default client credentials for a specific request. |
| 100 | +func WithBasicAuth(ctx context.Context, username, password string) context.Context { |
| 101 | + return context.WithValue(ctx, basicAuthKey{}, basicAuthValue{username, password}) |
| 102 | +} |
| 103 | + |
| 104 | +// ContextAuthInterceptor creates an interceptor that overrides BasicAuth |
| 105 | +// credentials if they are present in the request's context. |
| 106 | +// If no credentials are in the context, the request proceeds unchanged. |
| 107 | +func ContextAuthInterceptor() elastictransport.InterceptorFunc { |
| 108 | + return func(next elastictransport.RoundTripFunc) elastictransport.RoundTripFunc { |
| 109 | + return func(req *http.Request) (*http.Response, error) { |
| 110 | + if auth, ok := req.Context().Value(basicAuthKey{}).(basicAuthValue); ok { |
| 111 | + req.SetBasicAuth(auth.username, auth.password) |
| 112 | + } |
| 113 | + return next(req) |
| 114 | + } |
| 115 | + } |
| 116 | +} |
0 commit comments