wip: refactor watchlist triggers

This commit is contained in:
Vincent
2025-05-22 14:00:17 +02:00
parent a9ed531921
commit 130ce1bbac
9 changed files with 108 additions and 33 deletions

View File

@@ -62,6 +62,7 @@ export function UpdateWatchlistButton({watchlist, onUpdateWatchlist, connectors}
}} }}
connectors={connectors} connectors={connectors}
isCreation={false} isCreation={false}
watchList={watchlist}
/> />
</Drawer> </Drawer>
</> </>

View File

@@ -2,12 +2,12 @@ import type { FormInstance, SelectProps} from 'antd'
import {Button, Form, Input, Select, Space, Tag, Tooltip, Typography} from 'antd' import {Button, Form, Input, Select, Space, Tag, Tooltip, Typography} from 'antd'
import {t} from 'ttag' import {t} from 'ttag'
import {ApiOutlined, MinusCircleOutlined, PlusOutlined} from '@ant-design/icons' import {ApiOutlined, MinusCircleOutlined, PlusOutlined} from '@ant-design/icons'
import React from 'react' import React, {useState} from 'react'
import type {Connector} from '../../../utils/api/connectors' import type {Connector} from '../../../utils/api/connectors'
import {rdapEventDetailTranslation, rdapEventNameTranslation} from '../../../utils/functions/rdapTranslation' import {rdapEventDetailTranslation, rdapEventNameTranslation} from '../../../utils/functions/rdapTranslation'
import {actionToColor} from '../../../utils/functions/actionToColor' import {actionToColor} from '../../../utils/functions/actionToColor'
import {actionToIcon} from '../../../utils/functions/actionToIcon' import {actionToIcon} from '../../../utils/functions/actionToIcon'
import type {EventAction} from '../../../utils/api' import {EventAction, putWatchlistTrigger, Watchlist} from '../../../utils/api'
import {formItemLayoutWithOutLabel} from "../../../utils/providers" import {formItemLayoutWithOutLabel} from "../../../utils/providers"
type TagRender = SelectProps['tagRender'] type TagRender = SelectProps['tagRender']
@@ -23,11 +23,12 @@ const formItemLayout = {
} }
} }
export function WatchlistForm({form, connectors, onFinish, isCreation}: { export function WatchlistForm({form, connectors, onFinish, isCreation, watchList}: {
form: FormInstance form: FormInstance
connectors: Array<Connector & { id: string }> connectors: Array<Connector & { id: string }>
onFinish: (values: { domains: string[], triggers: string[], token: string }) => void onFinish: (values: { domains: string[], triggers: string[], token: string }) => void
isCreation: boolean isCreation: boolean,
watchList?: Watchlist,
}) { }) {
const rdapEventNameTranslated = rdapEventNameTranslation() const rdapEventNameTranslated = rdapEventNameTranslation()
const rdapEventDetailTranslated = rdapEventDetailTranslation() const rdapEventDetailTranslated = rdapEventDetailTranslation()
@@ -59,6 +60,32 @@ export function WatchlistForm({form, connectors, onFinish, isCreation}: {
) )
} }
const [triggersLoading, setTriggersLoading] = useState(false);
const createTrigger = async (event: string) => {
if (isCreation) return
setTriggersLoading(true);
await putWatchlistTrigger(watchList!.token, { // FIXME this 500s
watchList: watchList!['@id'],
event,
action: 'email',
});
await putWatchlistTrigger(watchList!.token, {
watchList: watchList!['@id'],
event,
action: 'chat',
});
setTriggersLoading(false);
};
const removeTrigger = async (event: string) => {
if (isCreation) return
setTriggersLoading(true);
// TODO
};
return ( return (
<Form <Form
{...formItemLayoutWithOutLabel} {...formItemLayoutWithOutLabel}
@@ -169,6 +196,9 @@ export function WatchlistForm({form, connectors, onFinish, isCreation}: {
mode='multiple' mode='multiple'
tagRender={triggerTagRenderer} tagRender={triggerTagRenderer}
style={{width: '100%'}} style={{width: '100%'}}
onSelect={createTrigger}
onDeselect={removeTrigger}
loading={triggersLoading}
options={Object.keys(rdapEventNameTranslated).map(e => ({ options={Object.keys(rdapEventNameTranslated).map(e => ({
value: e, value: e,
title: rdapEventDetailTranslated[e as keyof typeof rdapEventDetailTranslated] || undefined, title: rdapEventDetailTranslated[e as keyof typeof rdapEventDetailTranslated] || undefined,

View File

@@ -21,18 +21,10 @@ interface FormValuesType {
const getRequestDataFromForm = (values: FormValuesType) => { const getRequestDataFromForm = (values: FormValuesType) => {
const domainsURI = values.domains.map(d => '/api/domains/' + d.toLowerCase()) const domainsURI = values.domains.map(d => '/api/domains/' + d.toLowerCase())
let triggers = values.triggers.map(t => ({event: t, action: 'email'}))
if (values.dsn !== undefined) {
triggers = [...triggers, ...values.triggers.map(t => ({
event: t,
action: 'chat'
}))]
}
return { return {
name: values.name, name: values.name,
domains: domainsURI, domains: domainsURI,
triggers,
connector: values.connector !== undefined ? ('/api/connectors/' + values.connector) : undefined, connector: values.connector !== undefined ? ('/api/connectors/' + values.connector) : undefined,
dsn: values.dsn dsn: values.dsn
} }
@@ -91,7 +83,8 @@ export default function WatchlistPage() {
<Divider/> <Divider/>
{(connectors != null) && (watchlists != null) && watchlists.length > 0 && {(connectors != null) && (watchlists != null) && watchlists.length > 0 &&
<WatchlistsList <WatchlistsList
watchlists={watchlists} onDelete={refreshWatchlists} watchlists={watchlists}
onDelete={refreshWatchlists}
connectors={connectors} connectors={connectors}
onUpdateWatchlist={onUpdateWatchlist} onUpdateWatchlist={onUpdateWatchlist}
/>} />}

View File

@@ -16,7 +16,7 @@ export type EventAction =
| 'enum validation expiration' | 'enum validation expiration'
| string | string
export type TriggerAction = 'email' | string export type TriggerAction = 'email' | 'chat'
export interface Event { export interface Event {
action: EventAction action: EventAction
@@ -74,19 +74,26 @@ export interface User {
roles: string[] roles: string[]
} }
export interface WatchlistTrigger {
event: EventAction
action: TriggerAction
watchList?: string
}
export interface WatchlistRequest { export interface WatchlistRequest {
name?: string name?: string
domains: string[] domains: string[]
triggers: Array<{ event: EventAction, action: TriggerAction }> triggers?: Array<WatchlistTrigger>
connector?: string connector?: string
dsn?: string[] dsn?: string[]
} }
export interface Watchlist { export interface Watchlist {
'@id': string
name?: string name?: string
token: string token: string
domains: Domain[] domains: Domain[]
triggers?: Array<{ event: EventAction, action: string }> triggers?: Array<WatchlistTrigger>
dsn?: string[] dsn?: string[]
connector?: { connector?: {
id: string id: string

View File

@@ -1,4 +1,4 @@
import type { TrackedDomains, Watchlist, WatchlistRequest} from './index' import type {TrackedDomains, Watchlist, WatchlistRequest, WatchlistTrigger} from './index'
import {request} from './index' import {request} from './index'
interface WatchlistList { interface WatchlistList {
@@ -56,3 +56,12 @@ export async function getTrackedDomainList(params: { page: number, itemsPerPage:
}) })
return response.data return response.data
} }
export async function putWatchlistTrigger(watchListToken: string, watchListTrigger: WatchlistTrigger): Promise<WatchlistTrigger> {
const response = await request<WatchlistTrigger>({
method: 'PUT',
url: `watchlists/${watchListToken}/triggers`,
data: watchListTrigger,
});
return response.data;
}

View File

@@ -2,10 +2,12 @@
namespace App\Entity; namespace App\Entity;
use ApiPlatform\Metadata\ApiProperty;
use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete; use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get; use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection; use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Patch;
use ApiPlatform\Metadata\Post; use ApiPlatform\Metadata\Post;
use ApiPlatform\Metadata\Put; use ApiPlatform\Metadata\Put;
use App\Repository\WatchListRepository; use App\Repository\WatchListRepository;
@@ -90,6 +92,7 @@ use Symfony\Component\Uid\Uuid;
security: 'object.user == user', security: 'object.user == user',
name: 'update', name: 'update',
processor: WatchListUpdateProcessor::class, processor: WatchListUpdateProcessor::class,
extraProperties: ['standard_put' => false],
), ),
new Delete( new Delete(
security: 'object.user == user' security: 'object.user == user'
@@ -101,10 +104,12 @@ class WatchList
#[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'watchLists')] #[ORM\ManyToOne(targetEntity: User::class, inversedBy: 'watchLists')]
#[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')] #[ORM\JoinColumn(nullable: false, onDelete: 'CASCADE')]
public ?User $user = null; public ?User $user = null;
#[ORM\Id] #[ORM\Id]
#[ORM\Column(type: 'uuid')] #[ORM\Column(type: 'uuid')]
#[Groups(['watchlist:item', 'watchlist:list', 'watchlist:token'])] #[Groups(['watchlist:item', 'watchlist:list', 'watchlist:token'])]
private string $token; private string $token;
/** /**
* @var Collection<int, Domain> * @var Collection<int, Domain>
*/ */

View File

@@ -3,7 +3,11 @@
namespace App\Entity; namespace App\Entity;
use ApiPlatform\Metadata\ApiResource; use ApiPlatform\Metadata\ApiResource;
use ApiPlatform\Metadata\Delete;
use ApiPlatform\Metadata\Get;
use ApiPlatform\Metadata\GetCollection;
use ApiPlatform\Metadata\Link; use ApiPlatform\Metadata\Link;
use ApiPlatform\Metadata\Put;
use App\Config\TriggerAction; use App\Config\TriggerAction;
use App\Repository\EventTriggerRepository; use App\Repository\EventTriggerRepository;
use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Mapping as ORM;
@@ -12,28 +16,45 @@ use Symfony\Component\Serializer\Attribute\Groups;
#[ORM\Entity(repositoryClass: EventTriggerRepository::class)] #[ORM\Entity(repositoryClass: EventTriggerRepository::class)]
#[ApiResource( #[ApiResource(
uriTemplate: '/watchlists/{watchListId}/triggers/{action}/{event}', uriTemplate: '/watchlists/{watchListId}/triggers/{action}/{event}',
operations: [
new Get(),
new GetCollection(
uriTemplate: '/watchlists/{watchListId}/triggers',
uriVariables: [
'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class),
],
),
new Put(
uriTemplate: '/watchlists/{watchListId}/triggers',
uriVariables: [
'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class),
],
),
new Delete(),
],
uriVariables: [ uriVariables: [
'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class), 'watchListId' => new Link(fromProperty: 'token', toProperty: 'watchList', fromClass: WatchList::class),
'action' => 'action', 'action' => 'action',
'event' => 'event', 'event' => 'event',
], ],
security: 'object.getWatchList().user == user',
)] )]
class WatchListTrigger class WatchListTrigger
{ {
#[ORM\Id] #[ORM\Id]
#[ORM\Column(length: 255)] #[ORM\Column(length: 255, nullable: false)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])] #[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])]
private ?string $event = null; private ?string $event;
#[ORM\Id] #[ORM\Id]
#[ORM\ManyToOne(targetEntity: WatchList::class, cascade: ['persist'], inversedBy: 'watchListTriggers')] #[ORM\ManyToOne(targetEntity: WatchList::class, inversedBy: 'watchListTriggers')]
#[ORM\JoinColumn(referencedColumnName: 'token', nullable: false, onDelete: 'CASCADE')] #[ORM\JoinColumn(referencedColumnName: 'token', nullable: false, onDelete: 'CASCADE')]
private ?WatchList $watchList = null; private ?WatchList $watchList;
#[ORM\Id] #[ORM\Id]
#[ORM\Column(enumType: TriggerAction::class)] #[ORM\Column(nullable: false, enumType: TriggerAction::class)]
#[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])] #[Groups(['watchlist:list', 'watchlist:item', 'watchlist:create'])]
private ?TriggerAction $action = null; private ?TriggerAction $action;
public function getEvent(): ?string public function getEvent(): ?string
{ {

View File

@@ -22,7 +22,8 @@ readonly class ChatNotificationService
public function sendChatNotification(WatchList $watchList, DomainWatchdogNotification $notification): void public function sendChatNotification(WatchList $watchList, DomainWatchdogNotification $notification): void
{ {
$webhookDsn = $watchList->getWebhookDsn(); $webhookDsn = $watchList->getWebhookDsn();
if (null === $webhookDsn || 0 === count($webhookDsn)) {
if (empty($webhookDsn)) {
return; return;
} }

View File

@@ -7,11 +7,13 @@ use ApiPlatform\Metadata\Post;
use ApiPlatform\State\ProcessorInterface; use ApiPlatform\State\ProcessorInterface;
use App\Entity\Domain; use App\Entity\Domain;
use App\Entity\WatchList; use App\Entity\WatchList;
use App\Entity\WatchListTrigger;
use App\Notifier\TestChatNotification; use App\Notifier\TestChatNotification;
use App\Repository\DomainRepository; use App\Repository\DomainRepository;
use App\Service\ChatNotificationService; use App\Service\ChatNotificationService;
use App\Service\Connector\AbstractProvider; use App\Service\Connector\AbstractProvider;
use App\Service\RDAPService; use App\Service\RDAPService;
use Doctrine\ORM\EntityManagerInterface;
use Psr\Log\LoggerInterface; use Psr\Log\LoggerInterface;
use Symfony\Bundle\SecurityBundle\Security; use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\DependencyInjection\Attribute\Autowire; use Symfony\Component\DependencyInjection\Attribute\Autowire;
@@ -27,17 +29,18 @@ class WatchListUpdateProcessor implements ProcessorInterface
{ {
public function __construct( public function __construct(
private readonly DomainRepository $domainRepository, private readonly DomainRepository $domainRepository,
private readonly RDAPService $RDAPService, private readonly RDAPService $RDAPService,
private readonly KernelInterface $kernel, private readonly KernelInterface $kernel,
private readonly Security $security, private readonly Security $security,
private readonly RateLimiterFactory $rdapRequestsLimiter, private readonly RateLimiterFactory $rdapRequestsLimiter,
private readonly ParameterBagInterface $parameterBag, private readonly ParameterBagInterface $parameterBag,
#[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')] #[Autowire(service: 'api_platform.doctrine.orm.state.persist_processor')]
private readonly ProcessorInterface $persistProcessor, private readonly ProcessorInterface $persistProcessor,
private readonly LoggerInterface $logger, private readonly LoggerInterface $logger,
private readonly ChatNotificationService $chatNotificationService, private readonly ChatNotificationService $chatNotificationService,
#[Autowire(service: 'service_container')] #[Autowire(service: 'service_container')]
private readonly ContainerInterface $locator, private readonly ContainerInterface $locator,
private readonly EntityManagerInterface $entityManager,
) )
{} {}
@@ -50,14 +53,15 @@ class WatchListUpdateProcessor implements ProcessorInterface
*/ */
public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
{ {
dd($data);
$user = $this->security->getUser(); $user = $this->security->getUser();
$data->setUser($user);
if ($this->parameterBag->get('limited_features')) { if ($this->parameterBag->get('limited_features')) {
if ($data->getDomains()->count() > (int) $this->parameterBag->get('limit_max_watchlist_domains')) { if ($data->getDomains()->count() > (int) $this->parameterBag->get('limit_max_watchlist_domains')) {
$this->logger->notice('User {username} tried to update a Watchlist. The maximum number of domains has been reached for this Watchlist', [ $this->logger->notice('User {username} tried to update a Watchlist. The maximum number of domains has been reached for this Watchlist', [
'username' => $user->getUserIdentifier(), 'username' => $user->getUserIdentifier(),
]); ]);
throw new AccessDeniedHttpException('You have exceeded the maximum number of domain names allowed in this Watchlist'); throw new AccessDeniedHttpException('You have exceeded the maximum number of domain names allowed in this Watchlist');
} }
@@ -85,6 +89,7 @@ class WatchListUpdateProcessor implements ProcessorInterface
$this->logger->notice('User {username} tried to update a Watchlist. The maximum number of webhooks has been reached.', [ $this->logger->notice('User {username} tried to update a Watchlist. The maximum number of webhooks has been reached.', [
'username' => $user->getUserIdentifier(), 'username' => $user->getUserIdentifier(),
]); ]);
throw new AccessDeniedHttpException('You have exceeded the maximum number of webhooks allowed in this Watchlist'); throw new AccessDeniedHttpException('You have exceeded the maximum number of webhooks allowed in this Watchlist');
} }
} }
@@ -97,6 +102,7 @@ class WatchListUpdateProcessor implements ProcessorInterface
'username' => $user->getUserIdentifier(), 'username' => $user->getUserIdentifier(),
'connector' => $connector->getId(), 'connector' => $connector->getId(),
]); ]);
throw new AccessDeniedHttpException('You cannot create a Watchlist with a connector that does not belong to you'); throw new AccessDeniedHttpException('You cannot create a Watchlist with a connector that does not belong to you');
} }
@@ -104,6 +110,7 @@ class WatchListUpdateProcessor implements ProcessorInterface
foreach ($data->getDomains()->getIterator() as $domain) { foreach ($data->getDomains()->getIterator() as $domain) {
if ($domain->getDeleted()) { if ($domain->getDeleted()) {
$ldhName = $domain->getLdhName(); $ldhName = $domain->getLdhName();
throw new BadRequestHttpException("To add a connector, no domain in this Watchlist must have already expired ($ldhName)"); throw new BadRequestHttpException("To add a connector, no domain in this Watchlist must have already expired ($ldhName)");
} }
} }
@@ -120,6 +127,7 @@ class WatchListUpdateProcessor implements ProcessorInterface
'username' => $user->getUserIdentifier(), 'username' => $user->getUserIdentifier(),
'connector' => $connector->getId(), 'connector' => $connector->getId(),
]); ]);
throw new BadRequestHttpException('This connector does not support all TLDs in this Watchlist'); throw new BadRequestHttpException('This connector does not support all TLDs in this Watchlist');
} }
} }