cloudydeno / deno-kubernetes_client

Typescript library for accessing a Kubernetes API server
https://deno.land/x/kubernetes_client
Apache License 2.0
18 stars 4 forks source link

Convert Client Key Data to supported format on the fly #19

Open lucsoft opened 1 year ago

lucsoft commented 1 year ago

I have something like

export async function getPatchedLocalKube() {
    const config = await KubeConfig.getDefaultConfig();
    const ctx = config.fetchContext();
    const tlsAuth = await ctx.getClientTls();
    if (tlsAuth?.userKey.includes("BEGIN EC PRIVATE KEY")) {
        console.log(btoa(await convertEcKeyToPKCS8(tlsAuth?.userKey!)));
        ctx.user[ 'client-key-data' ] = btoa(await convertEcKeyToPKCS8(tlsAuth?.userKey!));
    }
    return KubeConfigRestClient.forKubeConfig(config);
}

async function convertEcKeyToPKCS8(key: string) {
    const derStream = new Deno.Command("openssl", {
        args: [ "ec", "-inform", "PEM", "-outform", "DER" ],
        stdin: "piped",
        stdout: "piped",
        stderr: "null"
    }).spawn();

    await new Response(key).body?.pipeTo(derStream.stdin!);

    const pkcs8Stream = new Deno.Command("openssl", {
        args: [ "pkcs8", "-topk8", "-nocrypt", "-outform", "PEM" ],
        stdin: "piped",
        stdout: "piped",
        stderr: "null"
    }).spawn();

    await derStream.stdout?.pipeTo(pkcs8Stream.stdin!);

    return await new Response(pkcs8Stream.stdout).text();
}

Would be could if it could be native + portable :D

After i wrote this code snippet i noticed that i can just modify my kubeconfig. it would be awesome anyway to have some logs or something to notice that it could work but just that the private key format is unsupported

danopia commented 1 month ago

Hmm, it sounds good to report on this sort of quirk. I've done similar messaging a fair bit with other kubeconfig things, saying that e.g. deno can't handle a specific field. And I recently ran into wanting to use a pkcs2 key with webcrypto, was pretty opaque and annoying to fix up.

It's unfortunate that the conversion is easiest with executing openssl. Otherwise this sounds good. I don't actually know exactly what formats Deno supports, so some more research is needed here.