review fixes

This commit is contained in:
x
2025-05-02 19:50:55 -04:00
parent 6eea4c8364
commit f49fb534ab
9 changed files with 50 additions and 117 deletions
@@ -1,21 +0,0 @@
import { Knex } from "knex";
import { TableName } from "../schemas";
export async function up(knex: Knex): Promise<void> {
const hasColumn = await knex.schema.hasColumn(TableName.SuperAdmin, "invalidatingCache");
if (!hasColumn) {
await knex.schema.alterTable(TableName.SuperAdmin, (t) => {
t.boolean("invalidatingCache").notNullable().defaultTo(false);
});
}
}
export async function down(knex: Knex): Promise<void> {
const hasColumn = await knex.schema.hasColumn(TableName.SuperAdmin, "invalidatingCache");
if (hasColumn) {
await knex.schema.alterTable(TableName.SuperAdmin, (t) => {
t.dropColumn("invalidatingCache");
});
}
}
+1 -2
View File
@@ -29,8 +29,7 @@ export const SuperAdminSchema = z.object({
adminIdentityIds: z.string().array().nullable().optional(), adminIdentityIds: z.string().array().nullable().optional(),
encryptedMicrosoftTeamsAppId: zodBuffer.nullable().optional(), encryptedMicrosoftTeamsAppId: zodBuffer.nullable().optional(),
encryptedMicrosoftTeamsClientSecret: zodBuffer.nullable().optional(), encryptedMicrosoftTeamsClientSecret: zodBuffer.nullable().optional(),
encryptedMicrosoftTeamsBotId: zodBuffer.nullable().optional(), encryptedMicrosoftTeamsBotId: zodBuffer.nullable().optional()
invalidatingCache: z.boolean().default(false)
}); });
export type TSuperAdmin = z.infer<typeof SuperAdminSchema>; export type TSuperAdmin = z.infer<typeof SuperAdminSchema>;
@@ -219,7 +219,7 @@ export const parseRotationErrorMessage = (err: unknown): string => {
if (err instanceof AxiosError) { if (err instanceof AxiosError) {
errorMessage += err?.response?.data errorMessage += err?.response?.data
? JSON.stringify(err?.response?.data) ? JSON.stringify(err?.response?.data)
: err?.message ?? "An unknown error occurred."; : (err?.message ?? "An unknown error occurred.");
} else { } else {
errorMessage += (err as Error)?.message || "An unknown error occurred."; errorMessage += (err as Error)?.message || "An unknown error occurred.";
} }
@@ -282,7 +282,7 @@ export const sshCertificateAuthorityServiceFactory = ({
// set [keyId] depending on if [allowCustomKeyIds] is true or false // set [keyId] depending on if [allowCustomKeyIds] is true or false
const keyId = sshCertificateTemplate.allowCustomKeyIds const keyId = sshCertificateTemplate.allowCustomKeyIds
? requestedKeyId ?? `${actor}-${actorId}` ? (requestedKeyId ?? `${actor}-${actorId}`)
: `${actor}-${actorId}`; : `${actor}-${actorId}`;
const sshCaSecret = await sshCertificateAuthoritySecretDAL.findOne({ sshCaId: sshCertificateTemplate.sshCaId }); const sshCaSecret = await sshCertificateAuthoritySecretDAL.findOne({ sshCaId: sshCertificateTemplate.sshCaId });
@@ -404,7 +404,7 @@ export const sshCertificateAuthorityServiceFactory = ({
// set [keyId] depending on if [allowCustomKeyIds] is true or false // set [keyId] depending on if [allowCustomKeyIds] is true or false
const keyId = sshCertificateTemplate.allowCustomKeyIds const keyId = sshCertificateTemplate.allowCustomKeyIds
? requestedKeyId ?? `${actor}-${actorId}` ? (requestedKeyId ?? `${actor}-${actorId}`)
: `${actor}-${actorId}`; : `${actor}-${actorId}`;
const sshCaSecret = await sshCertificateAuthoritySecretDAL.findOne({ sshCaId: sshCertificateTemplate.sshCaId }); const sshCaSecret = await sshCertificateAuthoritySecretDAL.findOne({ sshCaId: sshCertificateTemplate.sshCaId });
@@ -401,8 +401,8 @@ export const authLoginServiceFactory = ({
} }
const shouldCheckMfa = selectedOrg.enforceMfa || user.isMfaEnabled; const shouldCheckMfa = selectedOrg.enforceMfa || user.isMfaEnabled;
const orgMfaMethod = selectedOrg.enforceMfa ? selectedOrg.selectedMfaMethod ?? MfaMethod.EMAIL : undefined; const orgMfaMethod = selectedOrg.enforceMfa ? (selectedOrg.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
const userMfaMethod = user.isMfaEnabled ? user.selectedMfaMethod ?? MfaMethod.EMAIL : undefined; const userMfaMethod = user.isMfaEnabled ? (user.selectedMfaMethod ?? MfaMethod.EMAIL) : undefined;
const mfaMethod = orgMfaMethod ?? userMfaMethod; const mfaMethod = orgMfaMethod ?? userMfaMethod;
if (shouldCheckMfa && (!decodedToken.isMfaVerified || decodedToken.mfaMethod !== mfaMethod)) { if (shouldCheckMfa && (!decodedToken.isMfaVerified || decodedToken.mfaMethod !== mfaMethod)) {
@@ -291,7 +291,7 @@ export const parseSyncErrorMessage = (err: unknown): string => {
} else if (err instanceof AxiosError) { } else if (err instanceof AxiosError) {
errorMessage = err?.response?.data errorMessage = err?.response?.data
? JSON.stringify(err?.response?.data) ? JSON.stringify(err?.response?.data)
: err?.message ?? "An unknown error occurred."; : (err?.message ?? "An unknown error occurred.");
} else { } else {
errorMessage = (err as Error)?.message || "An unknown error occurred."; errorMessage = (err as Error)?.message || "An unknown error occurred.";
} }
@@ -21,7 +21,7 @@ export const invalidateCacheQueueFactory = ({ queueService, keyStore }: TInvalid
await queueService.queue(QueueName.InvalidateCache, QueueJobs.InvalidateCache, dto, { await queueService.queue(QueueName.InvalidateCache, QueueJobs.InvalidateCache, dto, {
removeOnComplete: true, removeOnComplete: true,
removeOnFail: true, removeOnFail: true,
jobId: "invalidate-cache" jobId: `invalidate-cache-${dto.data.type}`
}); });
}; };
@@ -176,8 +176,8 @@ export const superAdminServiceFactory = ({
const canServerAdminAccessAfterApply = const canServerAdminAccessAfterApply =
data.enabledLoginMethods.some((loginMethod) => data.enabledLoginMethods.some((loginMethod) =>
loginMethodToAuthMethod[loginMethod as LoginMethod].some( loginMethodToAuthMethod[loginMethod as LoginMethod].some((authMethod) =>
(authMethod) => superAdminUser.authMethods?.includes(authMethod) superAdminUser.authMethods?.includes(authMethod)
) )
) || ) ||
isUserSamlAccessEnabled || isUserSamlAccessEnabled ||
@@ -1,14 +1,15 @@
/* eslint-disable no-return-assign, consistent-return */
import { useEffect, useRef, useState } from "react"; import { useEffect, useRef, useState } from "react";
import { faRotate } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { createNotification } from "@app/components/notifications"; import { createNotification } from "@app/components/notifications";
import { Badge, Button, DeleteActionModal } from "@app/components/v2"; import { Badge, Button, DeleteActionModal } from "@app/components/v2";
import { useOrgPermission } from "@app/context"; import { useOrgPermission } from "@app/context";
import { usePopUp } from "@app/hooks"; import { usePopUp } from "@app/hooks";
import { useInvalidateCache } from "@app/hooks/api"; import { useInvalidateCache } from "@app/hooks/api";
import { CacheType } from "@app/hooks/api/admin/types";
import { useGetInvalidatingCacheStatus } from "@app/hooks/api/admin/queries"; import { useGetInvalidatingCacheStatus } from "@app/hooks/api/admin/queries";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { CacheType } from "@app/hooks/api/admin/types";
import { faRotate } from "@fortawesome/free-solid-svg-icons";
export const CachingPanel = () => { export const CachingPanel = () => {
const { mutateAsync: invalidateCache } = useInvalidateCache(); const { mutateAsync: invalidateCache } = useInvalidateCache();
@@ -17,6 +18,9 @@ export const CachingPanel = () => {
const { membership } = useOrgPermission(); const { membership } = useOrgPermission();
const ignoreInitial = useRef(true); const ignoreInitial = useRef(true);
const timeoutRef = useRef<NodeJS.Timeout | null>(null);
const pollingRef = useRef<NodeJS.Timeout | null>(null);
const [type, setType] = useState<CacheType | null>(null); const [type, setType] = useState<CacheType | null>(null);
const [buttonsDisabled, setButtonsDisabled] = useState(false); const [buttonsDisabled, setButtonsDisabled] = useState(false);
@@ -24,21 +28,14 @@ export const CachingPanel = () => {
"invalidateCache" "invalidateCache"
] as const); ] as const);
const success = () => { const disableButtonsTemporarily = () => {
createNotification({ setButtonsDisabled(true);
text: `Successfully invalidated cache`, timeoutRef.current = setTimeout(() => setButtonsDisabled(false), 10000);
type: "success"
});
setButtonsDisabled(false);
}; };
const timeoutRef = useRef<NodeJS.Timeout | null>(null); const success = () => {
const disableButtons = () => { createNotification({ text: "Successfully invalidated cache", type: "success" });
// Enable buttons after 10 seconds, even if still invalidating setButtonsDisabled(false);
setButtonsDisabled(true);
timeoutRef.current = setTimeout(() => {
setButtonsDisabled(false);
}, 10000);
}; };
const handleInvalidateCacheSubmit = async () => { const handleInvalidateCacheSubmit = async () => {
@@ -46,13 +43,8 @@ export const CachingPanel = () => {
try { try {
await invalidateCache({ type }); await invalidateCache({ type });
createNotification({ text: `Began invalidating ${type} cache`, type: "success" });
createNotification({ disableButtonsTemporarily();
text: `Began invalidating ${type} cache`,
type: "success"
});
disableButtons();
handlePopUpClose("invalidateCache"); handlePopUpClose("invalidateCache");
if (!(await refetchInvalidatingStatus()).data) { if (!(await refetchInvalidatingStatus()).data) {
@@ -61,59 +53,45 @@ export const CachingPanel = () => {
} }
} catch (err) { } catch (err) {
console.error(err); console.error(err);
createNotification({ createNotification({ text: `Failed to invalidate ${type} cache`, type: "error" });
text: `Failed to invalidate ${type} cache`,
type: "error"
});
} }
setType(null); setType(null);
}; };
const pollingRef = useRef<NodeJS.Timeout | null>(null);
// Update the "invalidating cache" status
useEffect(() => { useEffect(() => {
if (!isInvalidating) return; const timer = setTimeout(() => (ignoreInitial.current = false), 1000);
if (pollingRef.current) clearInterval(pollingRef.current);
if (timeoutRef.current) clearTimeout(timeoutRef.current);
// Start polling every 3 seconds
pollingRef.current = setInterval(async () => {
try {
await refetchInvalidatingStatus();
} catch (err) {
console.error("Polling error:", err);
}
}, 3000);
disableButtons();
return () => {
if (pollingRef.current) clearInterval(pollingRef.current);
if (timeoutRef.current) clearTimeout(timeoutRef.current);
};
}, [isInvalidating]);
// Helper to ignore the initial useEffect calls for isInvalidating
useEffect(() => {
const timer = setTimeout(() => {
ignoreInitial.current = false;
}, 1000);
return () => clearTimeout(timer); return () => clearTimeout(timer);
}, []); }, []);
useEffect(() => {
if (!isInvalidating) return;
clearInterval(pollingRef.current!);
clearTimeout(timeoutRef.current!);
pollingRef.current = setInterval(() => {
refetchInvalidatingStatus().catch((err) => console.error("Polling error:", err));
}, 3000);
disableButtonsTemporarily();
return () => {
clearInterval(pollingRef.current!);
clearTimeout(timeoutRef.current!);
};
}, [isInvalidating]);
useEffect(() => { useEffect(() => {
if (!ignoreInitial.current && isInvalidating === false) { if (!ignoreInitial.current && isInvalidating === false) {
success(); success();
clearInterval(pollingRef.current!);
if (pollingRef.current) clearInterval(pollingRef.current); clearTimeout(timeoutRef.current!);
if (timeoutRef.current) clearTimeout(timeoutRef.current);
} }
}, [isInvalidating]); }, [isInvalidating]);
const isAdmin = membership?.role === "admin";
return ( return (
<> <>
<div className="mb-6 flex flex-wrap items-end justify-between gap-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4"> <div className="mb-6 flex flex-wrap items-end justify-between gap-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
@@ -142,35 +120,12 @@ export const CachingPanel = () => {
setType(CacheType.SECRETS); setType(CacheType.SECRETS);
handlePopUpOpen("invalidateCache"); handlePopUpOpen("invalidateCache");
}} }}
isDisabled={Boolean(membership && membership.role !== "admin") || buttonsDisabled} isDisabled={!isAdmin || buttonsDisabled}
> >
Invalidate Secrets Cache Invalidate Secrets Cache
</Button> </Button>
</div> </div>
{/* Uncomment this when we have more than one cache type */}
{/* <div className="mb-6 flex flex-wrap items-end justify-between gap-4 rounded-lg border border-mineshaft-600 bg-mineshaft-900 p-4">
<div className="flex flex-col">
<span className="mb-2 text-xl font-semibold text-mineshaft-100">All Cache</span>
<span className="max-w-xl text-sm text-mineshaft-400">
All cache refers to the entirety of cached data throughout the system, including secrets
and miscellaneous information.
</span>
</div>
<Button
colorSchema="danger"
isLoading={isLoading}
onClick={() => {
setType(CacheType.ALL);
handlePopUpOpen("invalidateCache");
}}
isDisabled={Boolean(membership && membership.role !== "admin") || isLoading}
>
Invalidate All Cache
</Button>
</div> */}
<DeleteActionModal <DeleteActionModal
isOpen={popUp.invalidateCache.isOpen} isOpen={popUp.invalidateCache.isOpen}
title={`Are you sure you want to invalidate ${type} cache?`} title={`Are you sure you want to invalidate ${type} cache?`}