Skip to content

Commit

Permalink
[frontend] add user confidence control in creation/edition forms (#5697)
Browse files Browse the repository at this point in the history
Co-authored-by: Laurent Bonnet <laurent.bonnet@filigran.io>
Co-authored-by: Laurent Bonnet <146674147+labo-flg@users.noreply.github.com>
  • Loading branch information
3 people authored Feb 16, 2024
1 parent f7f82ea commit 949fac8
Show file tree
Hide file tree
Showing 93 changed files with 889 additions and 227 deletions.
6 changes: 4 additions & 2 deletions opencti-platform/opencti-front/lang/front/de.json
Original file line number Diff line number Diff line change
Expand Up @@ -2560,7 +2560,6 @@
"Max Confidence Level:": "Max. Konfidenzniveau:",
"Please, verify the validity of the selected CSV mapper for the given URL.": "Bitte überprüfen Sie die Gültigkeit des ausgewählten CSV-Mappers für die angegebene URL.",
"Only successful tests allow the ingestion creation.": "Nur erfolgreiche Tests ermöglichen die Erstellung der Aufnahme.",
"Only successful tests allow the ingestion edition.": "Nur erfolgreiche Tests erlauben die Ingestion-Edition.",
"Request for takedown date": "Antrag auf Übernahmedatum",
"Enable AI powered platform": "KI-gestützte Plattform aktivieren",
"To use AI, please enable it in the configuration of your platform.": "Um AI zu nutzen, aktivieren Sie es bitte in der Konfiguration Ihrer Plattform.",
Expand Down Expand Up @@ -2662,5 +2661,8 @@
"Disable public dashboard": "Öffentliches Dashboard deaktivieren",
"Delete public dashboard": "Öffentliches Dashboard löschen",
"Are you sure you want to delete this public dashboard?": "Sind Sie sicher, dass Sie dieses öffentliche Dashboard löschen möchten?",
"A public dashboard is a snapshot...": "Ein öffentliches Dashboard ist ein Schnappschuss eines privaten Dashboards zu einem bestimmten Zeitpunkt. Wenn Sie das private Dashboard ändern, werden die bereits erstellten öffentlichen Dashboards nicht geändert."
"A public dashboard is a snapshot...": "Ein öffentliches Dashboard ist ein Schnappschuss eines privaten Dashboards zu einem bestimmten Zeitpunkt. Wenn Sie das private Dashboard ändern, werden die bereits erstellten öffentlichen Dashboards nicht geändert.",
"Only successful tests allow the ingestion edition.": "Nur erfolgreiche Tests erlauben die Ingestion-Edition.",
"Your confidence level is insufficient to edit this object.": "Dein Vertrauensniveau ist unzureichend, um dieses Objekt zu bearbeiten.",
"You need a confidence level to edit objects in the platform.": "Du benötigst ein Vertrauensniveau, um Objekte auf der Plattform zu bearbeiten."
}
4 changes: 3 additions & 1 deletion opencti-platform/opencti-front/lang/front/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -2662,5 +2662,7 @@
"AI Powered": "AI Powered",
"Missing token": "Missing token",
"Generative AI is a beta feature as we are currently fine-tuning our models. Consider checking important information.": "Generative AI is a beta feature as we are currently fine-tuning our models. Consider checking important information.",
"Accept": "Accept"
"Accept": "Accept",
"Your confidence level is insufficient to edit this object.": "Your confidence level is insufficient to edit this object.",
"You need a confidence level to edit objects in the platform.": "You need a confidence level to edit objects in the platform."
}
5 changes: 3 additions & 2 deletions opencti-platform/opencti-front/lang/front/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -2568,7 +2568,6 @@
"The Max Confidence Level is currently defined at the user level. It overrides Max Confidence Level from user’s groups.": "El nivel de confianza máximo se define actualmente a nivel de usuario. Anula el nivel de confianza máximo de los grupos de usuarios.",
"Please, verify the validity of the selected CSV mapper for the given URL.": "Por favor, verifique la validez del asignador CSV seleccionado para la URL proporcionada.",
"Only successful tests allow the ingestion creation.": "Sólo las pruebas exitosas permiten la creación de la ingesta.",
"Only successful tests allow the ingestion edition.": "Sólo las pruebas exitosas permiten la edición de ingesta.",
"Request for takedown date": "Fecha de solicitud de retirada",
"Enable AI powered platform": "Habilitar plataforma con IA",
"To use AI, please enable it in the configuration of your platform.": "Para utilizar la IA, por favor, habilítela en la configuración de su plataforma.",
Expand Down Expand Up @@ -2666,5 +2665,7 @@
"Disable public dashboard": "Desactivar panel público",
"Delete public dashboard": "Borrar panel público",
"Are you sure you want to delete this public dashboard?": "¿Está seguro de que desea eliminar este panel público?",
"A public dashboard is a snapshot...": "Un panel público es una instantánea de un panel privado en un momento determinado. Si modifica el panel privado, los paneles públicos ya creados no se modificarán."
"A public dashboard is a snapshot...": "Un panel público es una instantánea de un panel privado en un momento determinado. Si modifica el panel privado, los paneles públicos ya creados no se modificarán.",
"Your confidence level is insufficient to edit this object.": "Tu nivel de confianza es insuficiente para editar este objeto.",
"You need a confidence level to edit objects in the platform.": "Necesitas un nivel de confianza para editar objetos en la plataforma."
}
7 changes: 4 additions & 3 deletions opencti-platform/opencti-front/lang/front/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -2564,7 +2564,6 @@
"Copy link": "Copier le lien",
"Please, verify the validity of the selected CSV mapper for the given URL.": "Veuillez vérifier la validité du mappeur CSV sélectionné pour l'URL donnée.",
"Only successful tests allow the ingestion creation.": "Seuls les tests réussis permettent la création de l'ingestion.",
"Only successful tests allow the ingestion edition.": "Seuls les tests réussis permettent l'édition de l'ingestion.",
"Public dashboards": "Tableaux de bord publics",
"Existing public dashboards": "Tableaux de bord publics existants",
"No public dashboard created yet": "Aucun tableau de bord public n'a encore été créé",
Expand All @@ -2575,7 +2574,6 @@
"Delete public dashboard": "Supprimer le tableau de bord public",
"Are you sure you want to delete this public dashboard?": "Êtes-vous sûr de vouloir supprimer ce tableau de bord public ?",
"A public dashboard is a snapshot...": "Un tableau de bord public est un instantané d'un tableau de bord privé à un moment précis. Si vous modifiez le tableau de bord privé, les tableaux de bord publics déjà créés ne seront pas modifiés.",
"Home": "Accueil",
"Request for takedown date": "Date de la demande de démontage",
"Enable AI powered platform": "Activer la plateforme alimentée par l'IA",
"To use AI, please enable it in the configuration of your platform.": "Pour utiliser l'IA, veuillez l'activer dans la configuration de votre plateforme.",
Expand Down Expand Up @@ -2662,5 +2660,8 @@
"AI Powered": "AI Powered",
"Missing token": "Jeton manquant",
"Generative AI is a beta feature as we are currently fine-tuning our models. Consider checking important information.": "L'IA générative est une fonction bêta, car nous sommes en train d'affiner nos modèles. Pensez à vérifier les informations importantes.",
"Accept": "Accepter"
"Accept": "Accepter",
"Home": "Accueil",
"Your confidence level is insufficient to edit this object.": "Votre niveau de confiance est insuffisant pour éditer cet objet.",
"You need a confidence level to edit objects in the platform.": "Vous avez besoin d'un niveau de confiance pour éditer des objets sur la plateforme."
}
5 changes: 3 additions & 2 deletions opencti-platform/opencti-front/lang/front/ja.json
Original file line number Diff line number Diff line change
Expand Up @@ -2564,7 +2564,6 @@
"Copy link": "リンクをコピー",
"Please, verify the validity of the selected CSV mapper for the given URL.": "指定された URL に対して選択した CSV マッパーが有効であることを確認してください。",
"Only successful tests allow the ingestion creation.": "成功したテストのみが取り込みの作成を許可します。",
"Only successful tests allow the ingestion edition.": "テストが成功した場合のみ、インジェスト エディションが許可されます。",
"Public dashboards": "公開ダッシュボード",
"Existing public dashboards": "既存の公開ダッシュボード",
"No public dashboard created yet": "まだ作成されていない公開ダッシュボード",
Expand Down Expand Up @@ -2662,5 +2661,7 @@
"AI Powered": "AI搭載",
"Missing token": "トークンの紛失",
"Generative AI is a beta feature as we are currently fine-tuning our models. Consider checking important information.": "ジェネレーティブAIは現在モデルを微調整しているベータ機能です。重要な情報を確認してください。",
"Accept": "受け入れる"
"Accept": "受け入れる",
"Your confidence level is insufficient to edit this object.": "このオブジェクトを編集するためには、最大の自信レベルが不足しています。",
"You need a confidence level to edit objects in the platform.": "プラットフォーム上でオブジェクトを編集するには、最大の自信レベルが必要です。"
}
5 changes: 3 additions & 2 deletions opencti-platform/opencti-front/lang/front/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -2564,7 +2564,6 @@
"Copy link": "复制链接",
"Please, verify the validity of the selected CSV mapper for the given URL.": "请验证给定 URL 所选 CSV 映射器的有效性。",
"Only successful tests allow the ingestion creation.": "只有成功的测试才允许创建摄取。",
"Only successful tests allow the ingestion edition.": "只有成功的测试才允许摄取版本。",
"Public dashboards": "公共仪表板",
"Existing public dashboards": "现有公共仪表盘",
"No public dashboard created yet": "尚未创建公共仪表盘",
Expand Down Expand Up @@ -2662,5 +2661,7 @@
"AI Powered": "人工智能技术",
"Missing token": "丢失的令牌",
"Generative AI is a beta feature as we are currently fine-tuning our models. Consider checking important information.": "生成式人工智能是一项测试功能,因为我们目前正在对模型进行微调。请考虑检查重要信息。",
"Accept": "接受"
"Accept": "接受",
"Your maximum confidence level is insufficient to edit this object.": "编辑此对象需要更高的最大信心水平。",
"You need a maximum confidence level to edit objects in the platform.": "在平台上编辑对象需要最高信心水平。"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import React from 'react';
import Alert from '@mui/material/Alert';
import useConfidenceLevel from '../utils/hooks/useConfidenceLevel';
import { useFormatter } from './i18n';

type AlertConfidenceForEntityProps = {
entity: {
confidence?: number | null
}
};

const AlertConfidenceForEntity: React.FC<AlertConfidenceForEntityProps> = ({ entity }) => {
const { t_i18n } = useFormatter();
const { checkConfidenceForEntity } = useConfidenceLevel();

if (checkConfidenceForEntity(entity)) {
return null;
}

return (
<Alert
severity="warning"
variant="outlined"
style={{ marginTop: 20, marginBottom: 20 }}
>
{t_i18n('Your confidence level is insufficient to edit this object.')}
</Alert>
);
};

export default AlertConfidenceForEntity;
20 changes: 12 additions & 8 deletions opencti-platform/opencti-front/src/components/InputSliderField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,10 @@ interface InputSliderFieldProps {
entityType: string;
attributeName: string;
disabled?: boolean;
maxLimit?: number;
}

const InputSliderField: FunctionComponent<
InputSliderFieldProps & FieldProps
> = ({
const InputSliderField: FunctionComponent<InputSliderFieldProps & FieldProps> = ({
form: { setFieldValue },
field: { name, value },
label,
Expand All @@ -35,14 +34,19 @@ InputSliderFieldProps & FieldProps
entityType,
attributeName,
disabled,
maxLimit,
}) => {
const {
level: { color },
marks,
marks: defaultMarks,
scale,
} = useLevel(entityType, attributeName, value);
const min = scale?.min ? scale.min.value : 0;
const max = scale?.max ? scale.max.value : 0;
const defaultMaxValue = scale?.max ? scale.max.value : 0;
const max = maxLimit !== undefined && Number.isFinite(maxLimit) && maxLimit <= defaultMaxValue
? maxLimit
: defaultMaxValue;
const marks = defaultMarks.filter((mark) => mark.value <= max);
const sliderStyle = {
color,
'& .MuiSlider-rail': {
Expand All @@ -68,7 +72,7 @@ InputSliderFieldProps & FieldProps
label={label}
onSubmit={onSubmit}
onFocus={onFocus}
disabled={disabled}
disabled={disabled || value > max}
helpertext={
<SubscriptionFocus context={editContext} fieldName={name} />
}
Expand All @@ -80,7 +84,7 @@ InputSliderFieldProps & FieldProps
labelId={name}
value={currentLevel.level.value?.toString() ?? ''}
onChange={updateFromSelect}
disabled={disabled}
disabled={disabled || value > max}
sx={{ marginTop: 2 }} // to align field with the number input, that has a label
>
{marks.map((mark, i: number) => {
Expand All @@ -107,7 +111,7 @@ InputSliderFieldProps & FieldProps
valueLabelDisplay="off"
size="small"
valueLabelFormat={() => currentLevel.level.label}
disabled={disabled}
disabled={disabled || value > max}
/>
</>
);
Expand Down
6 changes: 6 additions & 0 deletions opencti-platform/opencti-front/src/private/Root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ const rootPrivateQuery = graphql`
theme
user_email
individual_id
effective_confidence_level {
max_confidence
}
capabilities {
name
}
Expand All @@ -91,6 +94,9 @@ const rootPrivateQuery = graphql`
}
default_time_field
default_hidden_types
effective_confidence_level {
max_confidence
}
default_marking {
entity_type
values {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import OpenVocabField from '../../common/form/OpenVocabField';
import { fieldSpacingContainerStyle } from '../../../../utils/field';
import { useSchemaEditionValidation } from '../../../../utils/hooks/useEntitySettings';
import useFormEditor from '../../../../utils/hooks/useFormEditor';
import AlertConfidenceForEntity from '../../../../components/AlertConfidenceForEntity';

export const groupingMutationFieldPatch = graphql`
mutation GroupingEditionOverviewFieldPatchMutation(
Expand Down Expand Up @@ -191,6 +192,7 @@ const GroupingEditionOverviewComponent = (props) => {
}) => (
<div>
<Form style={{ margin: '20px 0 20px 0' }}>
<AlertConfidenceForEntity entity={grouping} />
<Field
component={TextField}
name="name"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import { Field, Form, Formik } from 'formik';
import * as Yup from 'yup';
import { FormikConfig } from 'formik/dist/types';
import { GenericContext } from '@components/common/model/GenericContextModel';
import {
malwareAnalysisEditionOverviewFocus,
malwareAnalysisMutationRelationAdd,
malwareAnalysisMutationRelationDelete,
} from '@components/analyses/malware_analyses/MalwareAnalysisEditionOverview';
import TextField from '../../../../components/TextField';
import { SubscriptionFocus } from '../../../../components/Subscription';
import CommitMessage from '../../common/form/CommitMessage';
Expand All @@ -12,11 +17,12 @@ import { useFormatter } from '../../../../components/i18n';
import { Option } from '../../common/form/ReferenceField';
import { MalwareAnalysisEditionDetails_malwareAnalysis$key } from './__generated__/MalwareAnalysisEditionDetails_malwareAnalysis.graphql';
import { MalwareAnalysisEditionDetailsFocusMutation } from './__generated__/MalwareAnalysisEditionDetailsFocusMutation.graphql';
import { MalwareAnalysisEditionDetailsFieldPatchMutation as FieldPatchMutation } from './__generated__/MalwareAnalysisEditionDetailsFieldPatchMutation.graphql';
import DateTimePickerField from '../../../../components/DateTimePickerField';
import { useSchemaCreationValidation } from '../../../../utils/hooks/useEntitySettings';
import { RelayError } from '../../../../relay/relayTypes';
import { MESSAGING$ } from '../../../../relay/environment';
import useFormEditor, { GenericData } from '../../../../utils/hooks/useFormEditor';
import AlertConfidenceForEntity from '../../../../components/AlertConfidenceForEntity';

const malwareAnalysisMutationFieldPatch = graphql`
mutation MalwareAnalysisEditionDetailsFieldPatchMutation(
Expand Down Expand Up @@ -50,6 +56,14 @@ export const malwareAnalysisEditionDetailsFragment = graphql`
analysis_engine_version
analysis_definition_version
modules
confidence
objectMarking {
id
definition_type
definition
x_opencti_order
x_opencti_color
}
}
`;
interface MalwareAnalysisEditionDetailsProps {
Expand Down Expand Up @@ -80,9 +94,20 @@ const MalwareAnalysisEditionDetails: FunctionComponent<MalwareAnalysisEditionDet
const malwareAnalysisDetailsValidator = useSchemaCreationValidation('Malware-Analysis', basicShape);
const malwareAnalysis = useFragment(malwareAnalysisEditionDetailsFragment, malwareAnalysisRef);

const [commitFieldPatch] = useMutation<FieldPatchMutation>(malwareAnalysisMutationFieldPatch);
const [commitEditionDetailsFocus] = useMutation<MalwareAnalysisEditionDetailsFocusMutation>(malwareAnalysisEditionDetailsFocus);

const queries = {
fieldPatch: malwareAnalysisMutationFieldPatch,
relationAdd: malwareAnalysisMutationRelationAdd,
relationDelete: malwareAnalysisMutationRelationDelete,
editionFocus: malwareAnalysisEditionOverviewFocus,
};
const editor = useFormEditor(
malwareAnalysis as GenericData,
enableReferences,
queries,
malwareAnalysisDetailsValidator,
);
const handleChangeFocus = (name: string) => {
commitEditionDetailsFocus({
variables: {
Expand All @@ -100,7 +125,7 @@ const MalwareAnalysisEditionDetails: FunctionComponent<MalwareAnalysisEditionDet
malwareAnalysisDetailsValidator
.validateAt(name, { [name]: value })
.then(() => {
commitFieldPatch({
editor.fieldPatch({
variables: {
id: malwareAnalysis.id,
input: [{ key: name, value: [finalValue ?? ''] }],
Expand All @@ -117,7 +142,7 @@ const MalwareAnalysisEditionDetails: FunctionComponent<MalwareAnalysisEditionDet
malwareAnalysisDetailsValidator
.validateAt(name, { [name]: value })
.then(() => {
commitFieldPatch({
editor.fieldPatch({
variables: {
id: malwareAnalysis.id,
input: [{ key: name, value: finalValue }],
Expand All @@ -138,7 +163,7 @@ const MalwareAnalysisEditionDetails: FunctionComponent<MalwareAnalysisEditionDet
modules: values.modules?.split('\n') ?? [],
}).map(([key, value]) => ({ key, value: adaptFieldValue(value) }));

commitFieldPatch({
editor.fieldPatch({
variables: {
id: malwareAnalysis.id,
input: inputValues,
Expand Down Expand Up @@ -178,6 +203,7 @@ const MalwareAnalysisEditionDetails: FunctionComponent<MalwareAnalysisEditionDet
values,
}) => (
<Form style={{ margin: '20px 0 20px 0' }}>
<AlertConfidenceForEntity entity={malwareAnalysis} />
<Field
component={TextField}
name="configuration_version"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import OpenVocabField from '../../common/form/OpenVocabField';
import ConfidenceField from '../../common/form/ConfidenceField';
import { useSchemaCreationValidation } from '../../../../utils/hooks/useEntitySettings';
import useFormEditor, { GenericData } from '../../../../utils/hooks/useFormEditor';
import AlertConfidenceForEntity from '../../../../components/AlertConfidenceForEntity';

const malwareAnalysisMutationFieldPatch = graphql`
mutation MalwareAnalysisEditionOverviewFieldPatchMutation(
Expand All @@ -45,7 +46,7 @@ export const malwareAnalysisEditionOverviewFocus = graphql`
}
`;

const malwareAnalysisMutationRelationAdd = graphql`
export const malwareAnalysisMutationRelationAdd = graphql`
mutation MalwareAnalysisEditionOverviewRelationAddMutation(
$id: ID!
$input: StixRefRelationshipAddInput!
Expand All @@ -59,7 +60,7 @@ const malwareAnalysisMutationRelationAdd = graphql`
}
`;

const malwareAnalysisMutationRelationDelete = graphql`
export const malwareAnalysisMutationRelationDelete = graphql`
mutation MalwareAnalysisEditionOverviewRelationDeleteMutation(
$id: ID!
$toId: StixRef!
Expand Down Expand Up @@ -213,6 +214,7 @@ const MalwareAnalysisEditionOverview: FunctionComponent<MalwareAnalysisEditionOv
values,
}) => (
<Form style={{ margin: '20px 0 20px 0' }}>
<AlertConfidenceForEntity entity={malwareAnalysis} />
<Field
component={TextField}
name="product"
Expand Down
Loading

0 comments on commit 949fac8

Please sign in to comment.