1+ <?php
2+ /*
3+ * This file is part of Part-DB (https://github.com/Part-DB/Part-DB-symfony).
4+ *
5+ * Copyright (C) 2019 - 2024 Jan Böhmer (https://github.com/jbtronics)
6+ *
7+ * This program is free software: you can redistribute it and/or modify
8+ * it under the terms of the GNU Affero General Public License as published
9+ * by the Free Software Foundation, either version 3 of the License, or
10+ * (at your option) any later version.
11+ *
12+ * This program is distributed in the hope that it will be useful,
13+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15+ * GNU Affero General Public License for more details.
16+ *
17+ * You should have received a copy of the GNU Affero General Public License
18+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
19+ */
20+
21+ declare (strict_types=1 );
22+
23+
24+ namespace App \Helpers ;
25+
26+ use Symfony \Component \HttpFoundation \IpUtils ;
27+
28+ /**
29+ * Utils to assist with IP anonymization.
30+ * The IPUtils::anonymize has a certain edgecase with local-link addresses, which is handled here.
31+ * See: https://github.com/Part-DB/Part-DB-server/issues/782
32+ */
33+ final class IPAnonymizer
34+ {
35+ public static function anonymize (string $ ip ): string
36+ {
37+ /**
38+ * If the IP contains a % symbol, then it is a local-link address with scoping according to RFC 4007
39+ * In that case, we only care about the part before the % symbol, as the following functions, can only work with
40+ * the IP address itself. As the scope can leak information (containing interface name), we do not want to
41+ * include it in our anonymized IP data.
42+ */
43+ if (str_contains ($ ip , '% ' )) {
44+ $ ip = substr ($ ip , 0 , strpos ($ ip , '% ' ));
45+ }
46+
47+ return IpUtils::anonymize ($ ip );
48+ }
49+ }
0 commit comments