|
| 1 | +package hwtesting |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "fmt" |
| 6 | + "os" |
| 7 | + |
| 8 | + zlog "github.com/rs/zerolog/log" |
| 9 | + "github.com/stillya/testcontainers-keycloak" |
| 10 | +) |
| 11 | + |
| 12 | +const ImageKeycloak = "quay.io/keycloak/keycloak:26.1.4" |
| 13 | + |
| 14 | +const ( |
| 15 | + KeycloakAdminUser = "admin" |
| 16 | + KeycloakAdminPassword = "admin" |
| 17 | +) |
| 18 | + |
| 19 | +// realm.json |
| 20 | + |
| 21 | +const ( |
| 22 | + KeycloakClientID = "user-svc" |
| 23 | + KeycloakRealm = "main" |
| 24 | + KeycloakClientSecret = "test-secret" |
| 25 | +) |
| 26 | + |
| 27 | +type realmImportFilePathKey struct{} |
| 28 | + |
| 29 | +func WithKeycloakRealmImportFile(ctx context.Context, path string) context.Context { |
| 30 | + return context.WithValue(ctx, realmImportFilePathKey{}, path) |
| 31 | +} |
| 32 | + |
| 33 | +func getKeycloakRealmImportFile(ctx context.Context) string { |
| 34 | + path, ok := ctx.Value(realmImportFilePathKey{}).(string) |
| 35 | + if !ok { |
| 36 | + zlog.Fatal().Msg("Keycloak container started, but WithKeycloakRealmImportFile() not used") |
| 37 | + } |
| 38 | + return path |
| 39 | +} |
| 40 | + |
| 41 | +func startKeycloak(ctx context.Context) (endpoint string, teardown func()) { |
| 42 | + container, err := keycloak.Run(ctx, |
| 43 | + ImageKeycloak, |
| 44 | + keycloak.WithAdminUsername(KeycloakAdminUser), |
| 45 | + keycloak.WithAdminPassword(KeycloakAdminPassword), |
| 46 | + keycloak.WithRealmImportFile(getKeycloakRealmImportFile(ctx)), |
| 47 | + ) |
| 48 | + if err != nil { |
| 49 | + zlog.Fatal().Err(err).Msg("Could not start keycloak") |
| 50 | + } |
| 51 | + endpoint, err = container.Endpoint(ctx, "") |
| 52 | + if err != nil { |
| 53 | + zlog.Fatal().Err(err).Msg("Could not get access to keycloak endpoint") |
| 54 | + } |
| 55 | + return endpoint, func() { |
| 56 | + if err := container.Terminate(ctx); err != nil { |
| 57 | + zlog.Fatal().Err(err).Msg("Could not terminate keycloak container") |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +func SetKeycloakEnv(endpoint string) { |
| 63 | + m := map[string]string{ |
| 64 | + "OAUTH_ISSUER_URL": issURL(endpoint), |
| 65 | + "OAUTH_CLIENT_ID": KeycloakClientID, |
| 66 | + "OAUTH_KC_CLIENT_SECRET": KeycloakClientSecret, |
| 67 | + "OAUTH_KC_REALM": KeycloakRealm, |
| 68 | + } |
| 69 | + for k, v := range m { |
| 70 | + if err := os.Setenv(k, v); err != nil { |
| 71 | + zlog.Fatal().Err(err).Msgf("Could not set %s=%s", k, v) |
| 72 | + } |
| 73 | + } |
| 74 | +} |
| 75 | + |
| 76 | +func issURL(endpoint string) string { |
| 77 | + return fmt.Sprintf("http://%s/realms/%s", endpoint, KeycloakRealm) |
| 78 | +} |
0 commit comments