Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for UTF-16 encoded kubeconfig files #1654

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 30 additions & 3 deletions kube-client/src/config/file_config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{
collections::HashMap,
fs,
fs, io,
path::{Path, PathBuf},
};

Expand Down Expand Up @@ -351,8 +351,8 @@ const KUBECONFIG: &str = "KUBECONFIG";
impl Kubeconfig {
/// Read a Config from an arbitrary location
pub fn read_from<P: AsRef<Path>>(path: P) -> Result<Kubeconfig, KubeconfigError> {
let data = fs::read_to_string(&path)
.map_err(|source| KubeconfigError::ReadConfig(source, path.as_ref().into()))?;
let data =
read_path(&path).map_err(|source| KubeconfigError::ReadConfig(source, path.as_ref().into()))?;

// Remap all files we read to absolute paths.
let mut merged_docs = None;
Expand Down Expand Up @@ -497,6 +497,33 @@ where
});
}

fn read_path<P: AsRef<Path>>(path: P) -> io::Result<String> {
let bytes = fs::read(&path)?;
match bytes.as_slice() {
[0xFF, 0xFE, ..] => {
let utf16_data: Vec<u16> = bytes[2..]
.chunks(2)
.map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]]))
.collect();
String::from_utf16(&utf16_data)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 LE"))
}
[0xFE, 0xFF, ..] => {
let utf16_data: Vec<u16> = bytes[2..]
.chunks(2)
.map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]]))
.collect();
String::from_utf16(&utf16_data)
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 BE"))
}
[0xEF, 0xBB, 0xBF, ..] => String::from_utf8(bytes[3..].to_vec())
.map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8 BOM")),
_ => {
String::from_utf8(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8"))
}
}
}

fn to_absolute(dir: &Path, file: &str) -> Option<String> {
let path = Path::new(&file);
if path.is_relative() {
Expand Down
Loading