| 1 |
package util |
| 2 |
|
| 3 |
import ( |
| 4 |
"encoding/json" |
| 5 |
"net/http" |
| 6 |
"net/http/httptest" |
| 7 |
"os" |
| 8 |
) |
| 9 |
|
| 10 |
// Application Default Credentials (ADC) is a strategy used by the Google authentication libraries to automatically find credentials based on the application environment. |
| 11 |
// ADC searches for credentials in GOOGLE_APPLICATION_CREDENTIALS environment variable first (https://cloud.google.com/docs/authentication/application-default-credentials) |
| 12 |
// We use fakeAsHostEnv to let ADC find fake credential. |
| 13 |
const oauth2CredentialHostEnv = "GOOGLE_APPLICATION_CREDENTIALS" |
| 14 |
|
| 15 |
// MockOauth2Server is a struct for mocking Oauth2Server |
| 16 |
type MockOauth2Server struct { |
| 17 |
Server *httptest.Server |
| 18 |
OriginalCred string |
| 19 |
} |
| 20 |
|
| 21 |
// NewMockOauth2Server creates a mock Oauth2 server for testing purpose |
| 22 |
func NewMockOauth2Server() (*MockOauth2Server, error) { |
| 23 |
mux := http.NewServeMux() |
| 24 |
mux.HandleFunc("/o/oauth2/auth", func(_ http.ResponseWriter, _ *http.Request) { |
| 25 |
// Unimplemented: Should return authorization code back to the user |
| 26 |
}) |
| 27 |
|
| 28 |
mux.HandleFunc("/token", func(w http.ResponseWriter, _ *http.Request) { |
| 29 |
// Should return acccess token back to the user |
| 30 |
w.Header().Set("Content-Type", "application/x-www-form-urlencoded") |
| 31 |
w.Write([]byte("access_token=mocktoken&scope=user&token_type=bearer")) |
| 32 |
}) |
| 33 |
|
| 34 |
server := httptest.NewServer(mux) |
| 35 |
|
| 36 |
// create test oauth2 credentials |
| 37 |
testCredentials := map[string]string{ |
| 38 |
"client_id": "id", |
| 39 |
"client_secret": "testdata", |
| 40 |
"refresh_token": "testdata", |
| 41 |
"type": "authorized_user", |
| 42 |
} |
| 43 |
|
| 44 |
fakeOauthCredentialData, err := json.MarshalIndent(testCredentials, "", " ") // Indent for readability |
| 45 |
if err != nil { |
| 46 |
return nil, err |
| 47 |
} |
| 48 |
|
| 49 |
file, err := os.CreateTemp("", "fake_oauth2_test_credentials") |
| 50 |
if err != nil { |
| 51 |
return nil, err |
| 52 |
} |
| 53 |
defer file.Close() |
| 54 |
|
| 55 |
_, err = file.Write(fakeOauthCredentialData) |
| 56 |
if err != nil { |
| 57 |
return nil, err |
| 58 |
} |
| 59 |
|
| 60 |
old := os.Getenv(oauth2CredentialHostEnv) |
| 61 |
os.Setenv(oauth2CredentialHostEnv, file.Name()) |
| 62 |
|
| 63 |
return &MockOauth2Server{Server: server, OriginalCred: old}, nil |
| 64 |
} |
| 65 |
|
| 66 |
// Stop cleans up the fake credential, reset the original one, and shuts down the server. |
| 67 |
func (s *MockOauth2Server) Stop() { |
| 68 |
os.Remove(os.Getenv(oauth2CredentialHostEnv)) |
| 69 |
os.Setenv(oauth2CredentialHostEnv, s.OriginalCred) |
| 70 |
s.Server.Close() |
| 71 |
} |