Skip to content

Commit

Permalink
refactor: remove com.google.* dependent code from the `jkube-kit-bu…
Browse files Browse the repository at this point in the history
…ild-api` module

Signed-off-by: Marc Nuri <[email protected]>
  • Loading branch information
manusa committed Dec 1, 2023
1 parent 9f9263a commit 231fa10
Show file tree
Hide file tree
Showing 16 changed files with 343 additions and 160 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,17 @@
*/
package org.eclipse.jkube.kit.build.api.auth;

import com.google.gson.JsonObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jkube.kit.common.KitLogger;
import org.eclipse.jkube.kit.common.util.Serialization;

import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.UnaryOperator;
Expand Down Expand Up @@ -61,7 +63,7 @@ public AuthConfig(String username, String password, String email, String auth) {
}

public String toHeaderValue(KitLogger logger) {
JsonObject ret = new JsonObject();
final Map<String, String> ret = new LinkedHashMap<>();
if(StringUtils.isNotBlank(identityToken)) {
putNonNull(ret, "identityToken", identityToken);
if (StringUtils.isNotBlank(username)) {
Expand All @@ -73,8 +75,13 @@ public String toHeaderValue(KitLogger logger) {
putNonNull(ret, "email", email);
putNonNull(ret, "auth", auth);
}

return encodeBase64ChunkedURLSafeString(ret.toString().getBytes(StandardCharsets.UTF_8));
try {
final byte[] bytes = Serialization.jsonWriter().without(SerializationFeature.INDENT_OUTPUT)
.writeValueAsBytes(ret);
return encodeBase64ChunkedURLSafeString(bytes);
} catch(JsonProcessingException e) {
throw new IllegalArgumentException("Cannot encode auth config", e);
}
}

public static AuthConfig fromMap(Map<String, String> params) {
Expand Down Expand Up @@ -126,9 +133,9 @@ private String encodeBase64ChunkedURLSafeString(final byte[] binaryData) {
.replace('/', '_');
}

private void putNonNull(JsonObject ret, String key, String value) {
private void putNonNull(Map<String, String> ret, String key, String value) {
if (value != null) {
ret.addProperty(key,value);
ret.put(key,value);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.Map;

import com.google.gson.JsonObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import org.eclipse.jkube.kit.common.util.Serialization;

/**
* Configuration object holding auth information for
Expand Down Expand Up @@ -71,12 +75,18 @@ public static RegistryAuth fromCredentialsEncoded(String credentialsEncoded, Str
}

private String createAuthEncoded() {
JsonObject ret = new JsonObject();
final Map<String, String> ret = new LinkedHashMap<>();
putNonNull(ret, USERNAME, username);
putNonNull(ret, PASSWORD, password);
putNonNull(ret, EMAIL, email);
putNonNull(ret, AUTH, auth);
return encodeBase64ChunkedURLSafeString(ret.toString().getBytes(StandardCharsets.UTF_8));
try {
final byte[] bytes = Serialization.jsonWriter().without(SerializationFeature.INDENT_OUTPUT)
.writeValueAsBytes(ret);
return encodeBase64ChunkedURLSafeString(bytes);
} catch(JsonProcessingException e) {
throw new IllegalArgumentException("Cannot encode auth config", e);
}
}

/**
Expand All @@ -92,9 +102,9 @@ private String encodeBase64ChunkedURLSafeString(final byte[] binaryData) {
.replace('/', '_');
}

private void putNonNull(JsonObject ret, String key, String value) {
private void putNonNull(Map<String, String> ret, String key, String value) {
if (value != null) {
ret.addProperty(key,value);
ret.put(key,value);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,11 @@

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
Expand All @@ -32,18 +31,20 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.fasterxml.jackson.core.type.TypeReference;
import org.eclipse.jkube.kit.common.JKubeFileInterpolator;
import org.eclipse.jkube.kit.common.util.Serialization;
import org.eclipse.jkube.kit.config.image.ImageConfiguration;
import org.eclipse.jkube.kit.config.image.build.BuildConfiguration;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.apache.commons.lang3.StringUtils;

import static org.eclipse.jkube.kit.common.util.EnvUtil.getEnv;
import static org.eclipse.jkube.kit.common.util.EnvUtil.getUserHome;

/**
* Utility class for dealing with dockerfiles
* @author roland
* @since 21/01/16
*/
public class DockerFileUtil {
private static final String ARG_PATTERN_REGEX = "\\$([\\w|\\-\\.]+)|\\$\\{([\\w\\-|\\.]+)\\}";
Expand Down Expand Up @@ -131,19 +132,6 @@ public static String interpolate(File dockerFile, Properties properties, String
return JKubeFileInterpolator.interpolate(dockerFile, properties, filter);
}

private static Reader getFileReaderFromDir(File file) {
if (file.exists() && file.length() != 0) {
try {
return new FileReader(file);
} catch (FileNotFoundException e) {
// Shouldn't happen. Nevertheless ...
throw new IllegalStateException("Cannot find " + file,e);
}
} else {
return null;
}
}

/**
* Helper method for extractArgs(exposed for test)
*
Expand Down Expand Up @@ -186,13 +174,22 @@ static Set<String> findAllArgs(String imageTagString) {
return args;
}

public static JsonObject readDockerConfig() {
String dockerConfig = System.getenv("DOCKER_CONFIG");

Reader reader = dockerConfig == null
? getFileReaderFromDir(new File(getHomeDir(),".docker/config.json"))
: getFileReaderFromDir(new File(dockerConfig,"config.json"));
return reader != null ? new Gson().fromJson(reader, JsonObject.class) : null;
public static Map<String, Object> readDockerConfig() {
final String dockerConfigDirectory = getEnv("DOCKER_CONFIG");
final File dockerConfig;
if (StringUtils.isNotBlank(dockerConfigDirectory)) {
dockerConfig = new File(dockerConfigDirectory,"config.json");
} else {
dockerConfig = new File(getUserHome(),".docker/config.json");
}
if (!dockerConfig.exists() || !dockerConfig.isFile()) {
return Collections.emptyMap();
}
try {
return Serialization.unmarshal(dockerConfig, new TypeReference<Map<String, Object>>() {});
} catch (IOException e) {
throw new IllegalStateException("Cannot read docker config from " + dockerConfig.getAbsolutePath(), e);
}
}

public static boolean isSimpleDockerFileMode(File projectBaseDirectory) {
Expand Down Expand Up @@ -231,14 +228,6 @@ public static ImageConfiguration addSimpleDockerfileConfig(ImageConfiguration im
return image.toBuilder().build(buildConfig).build();
}

private static File getHomeDir() {
String homeDir = System.getProperty("user.home");
if (homeDir == null) {
homeDir = System.getenv("HOME");
}
return new File(homeDir);
}

private static void updateMapWithArgValue(Map<String, String> result, Map<String, String> args, String argString) {
if (argString.contains("=") || argString.contains(":")) {
String[] argStringParts = argString.split("[=:]");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.eclipse.jkube.kit.common.util.EnvUtil.getUserHome;

public class KubernetesConfigAuthUtil {

private static final String KUBECONFIG_ENV = "KUBECONFIG";
Expand Down Expand Up @@ -97,7 +99,7 @@ private static AuthConfig parseUser(String userName, Map<String, ?> user) {
private static Map<String, Object> readKubeConfig() {
String kubeConfig = System.getenv(KUBECONFIG_ENV);
final File applicableFile = kubeConfig == null ?
getHomeDir().toPath().resolve(KUBECONFIG_FILE).toFile() : new File(kubeConfig);
getUserHome().toPath().resolve(KUBECONFIG_FILE).toFile() : new File(kubeConfig);
if (applicableFile.exists()) {
try {
return Serialization.unmarshal(applicableFile, new TypeReference<Map<String, Object>>() {});
Expand All @@ -107,9 +109,4 @@ private static Map<String, Object> readKubeConfig() {
}
return Collections.emptyMap();
}

private static File getHomeDir() {
String homeDir = System.getProperty("user.home") != null ? System.getProperty("user.home") : System.getenv("HOME");
return new File(homeDir);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
/*
* Copyright (c) 2019 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at:
*
* https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.jkube.kit.build.api.auth;

import com.fasterxml.jackson.core.type.TypeReference;
import org.eclipse.jkube.kit.common.KitLogger;
import org.eclipse.jkube.kit.common.util.Serialization;
import org.junit.jupiter.api.Test;

import java.util.Base64;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

class AuthConfigTest {

@Test
void simpleConstructor() {
AuthConfig config = AuthConfig.builder()
.username("roland")
.password("#>secrets??")
.email("[email protected]")
.build();
// Since Base64.decodeBase64 handles URL-safe encoding, must explicitly check
// the correct characters are used
assertThat(config.toHeaderValue(new KitLogger.SilentLogger()))
.isEqualTo("eyJ1c2VybmFtZSI6InJvbGFuZCIsInBhc3N3b3JkIjoiIz5zZWNyZXRzPz8iLCJlbWFpbCI6InJvbGFuZEBqb2xva2lhLm9yZyJ9");

String header = new String(Base64.getDecoder().decode(config.toHeaderValue(new KitLogger.SilentLogger())));

final Map<String, Object> result = Serialization.unmarshal(header, new TypeReference<Map<String, Object>>() {
});
assertThat(result)
.containsOnly(
entry("username", "roland"),
entry("password", "#>secrets??"),
entry("email", "[email protected]")
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,17 @@
package org.eclipse.jkube.kit.build.api.auth;

import java.util.Base64;
import java.util.Map;

import com.google.gson.JsonObject;
import org.eclipse.jkube.kit.common.JsonFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import org.eclipse.jkube.kit.common.util.Serialization;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.entry;

/**
* @author roland
* @since 30.07.14
*/
class RegistryAuthTest {

Expand Down Expand Up @@ -53,11 +54,13 @@ private void check(RegistryAuth config) {

String header = new String(Base64.getDecoder().decode(config.toHeaderValue()));

JsonObject data = JsonFactory.newJsonObject(header);
assertThat(data)
.returns("roland", d -> d.get("username").getAsString())
.returns("#>secrets??", d -> d.get("password").getAsString())
.returns("[email protected]", d -> d.get("email").getAsString())
.returns(false, d -> d.has("auth"));
final Map<String, Object> result = Serialization.unmarshal(header, new TypeReference<Map<String, Object>>() {
});
assertThat(result)
.containsOnly(
entry("username", "roland"),
entry("password", "#>secrets??"),
entry("email", "[email protected]")
);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,23 +14,24 @@
package org.eclipse.jkube.kit.build.api.auth.handler;

import java.util.Base64;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import org.eclipse.jkube.kit.build.api.auth.AuthConfig;
import org.eclipse.jkube.kit.build.api.auth.RegistryAuth;
import org.eclipse.jkube.kit.build.api.auth.RegistryAuthConfig;
import org.eclipse.jkube.kit.common.KitLogger;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import org.eclipse.jkube.kit.common.util.Serialization;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException;
import static org.assertj.core.api.Assertions.entry;

/**
* @author roland
* @since 23.10.18
*/
class FromConfigRegistryAuthHandlerTest {

Expand Down Expand Up @@ -87,13 +88,15 @@ void fromPluginConfigurationFailed() {
}

private void verifyAuthConfig(AuthConfig config, String username, String password, String email) {
JsonObject params = new Gson().fromJson(new String(Base64.getDecoder().decode(config.toHeaderValue(log).getBytes())),
JsonObject.class);
assertThat(params)
.returns(username, j -> j.get("username").getAsString())
.returns(password, j -> j.get("password").getAsString());
final Map<String, String> params = Serialization.unmarshal(
new String(Base64.getDecoder().decode(config.toHeaderValue(log).getBytes())),
new TypeReference<Map<String, String>>() {});
assertThat(params).contains(
entry("username", username),
entry("password", password)
);
if (email != null) {
assertThat(params.get("email").getAsString()).isEqualTo(email);
assertThat(params).containsEntry("email", email);
}
}

Expand Down
Loading

0 comments on commit 231fa10

Please sign in to comment.