Merge pull request #2520 from Infisical/daniel/better-k8-auth-logs

fix(k8-auth): better errors
This commit is contained in:
Daniel Hougaard
2024-10-02 14:27:37 +04:00
committed by GitHub
@@ -1,5 +1,5 @@
import { ForbiddenError } from "@casl/ability"; import { ForbiddenError } from "@casl/ability";
import axios from "axios"; import axios, { AxiosError } from "axios";
import https from "https"; import https from "https";
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
@@ -107,7 +107,8 @@ export const identityKubernetesAuthServiceFactory = ({
}); });
} }
const { data }: { data: TCreateTokenReviewResponse } = await axios.post( const { data } = await axios
.post<TCreateTokenReviewResponse>(
`${identityKubernetesAuth.kubernetesHost}/apis/authentication.k8s.io/v1/tokenreviews`, `${identityKubernetesAuth.kubernetesHost}/apis/authentication.k8s.io/v1/tokenreviews`,
{ {
apiVersion: "authentication.k8s.io/v1", apiVersion: "authentication.k8s.io/v1",
@@ -121,18 +122,39 @@ export const identityKubernetesAuthServiceFactory = ({
"Content-Type": "application/json", "Content-Type": "application/json",
Authorization: `Bearer ${tokenReviewerJwt}` Authorization: `Bearer ${tokenReviewerJwt}`
}, },
// if ca cert, rejectUnauthorized: true
httpsAgent: new https.Agent({ httpsAgent: new https.Agent({
ca: caCert, ca: caCert,
rejectUnauthorized: !!caCert rejectUnauthorized: !!caCert
}) })
} }
); )
.catch((err) => {
if (err instanceof AxiosError) {
if (err.response) {
const { message } = err?.response?.data as unknown as { message?: string };
if ("error" in data.status) throw new UnauthorizedError({ message: data.status.error }); if (message) {
throw new UnauthorizedError({
message,
name: "KubernetesTokenReviewRequestError"
});
}
}
}
throw err;
});
if ("error" in data.status)
throw new UnauthorizedError({ message: data.status.error, name: "KubernetesTokenReviewError" });
// check the response to determine if the token is valid // check the response to determine if the token is valid
if (!(data.status && data.status.authenticated)) if (!(data.status && data.status.authenticated))
throw new UnauthorizedError({ message: "Kubernetes token not authenticated" }); throw new UnauthorizedError({
message: "Kubernetes token not authenticated",
name: "KubernetesTokenReviewError"
});
const { namespace: targetNamespace, name: targetName } = extractK8sUsername(data.status.user.username); const { namespace: targetNamespace, name: targetName } = extractK8sUsername(data.status.user.username);