diff --git a/doc/configuration.md b/doc/configuration.md index ad4acaf82..f43da0ac9 100644 --- a/doc/configuration.md +++ b/doc/configuration.md @@ -878,6 +878,74 @@ Whether removing an extension through the extension control file also removes wh Whether to generate a signature archive (sigzip) for published extensions. By default it does nothing. There are 3 modes: `create`, `renew` and `delete`. When `renew` is specified, then on startup a new keypair is generated and a new signature is generated for each extension version in the background. When `create` is specified then on startup, if no keypair exists, a keypair is created and a signature is generated for each extension version in the background. A signature is generated for newly published extension versions in both `renew` and `create` modes. The `delete` mode deletes the keypair and all generated signatures. +## Name Similarity + +The `NAME_SIMILARITY` publish check flags a version whose extension name or display name matches or resembles another namespace's active extension, for an admin to review on the name squatting dashboard. It never blocks publication, whether it finds a match or fails, and like every publish check it runs only while `ovsx.scanning.enabled` is `true`. The dashboard's namespaces view, which lists pairs of namespaces with similar names, uses the popularity properties below. + +| Property | `ovsx.scanning.name-similarity.enabled` +|---------------|---------------------------------------- +| Type | boolean +| Default | `true` +| Compatibility | Since 1.5.0 + +Whether the `NAME_SIMILARITY` check runs on publish. The dashboard works either way, but without the check it has no flagged versions to show beyond extensions sharing a display name. + +| Property | `ovsx.scanning.name-similarity.name-threshold` +|---------------|----------------------------------------------- +| Type | number +| Default | `0.7` +| Compatibility | Since 1.5.0 + +Lowest trigram similarity, above 0 and at most 1, at which two extension names count as a match. A value out of range stops the server from starting. + +| Property | `ovsx.scanning.name-similarity.display-name-threshold` +|---------------|------------------------------------------------------- +| Type | number +| Default | `0.7` +| Compatibility | Since 1.5.0 + +Lowest trigram similarity, above 0 and at most 1, at which two display names count as a match. A value out of range stops the server from starting. + +| Property | `ovsx.scanning.name-similarity.min-fuzzy-length` +|---------------|------------------------------------------------- +| Type | integer +| Default | `4` +| Compatibility | Since 1.5.0 + +Names shorter than this, once normalized, only match exactly, since trigram scores of very short strings say little. Must be at least 1. + +| Property | `ovsx.scanning.name-similarity.max-matches` +|---------------|-------------------------------------------- +| Type | integer +| Default | `10` +| Compatibility | Since 1.5.0 + +Most matches looked up per field and name, which bounds the work a very generic name causes. Must be at least 1. + +| Property | `ovsx.scanning.name-similarity.statement-timeout` +|---------------|-------------------------------------------------- +| Type | duration +| Default | `10s` +| Compatibility | Since 1.5.0 + +How long one lookup may run before the database cancels it, for the publish check and the dashboard alike. A cancelled check fails without blocking publication; a cancelled dashboard lookup answers 503 and suggests raising this value. Must be positive. + +| Property | `ovsx.scanning.name-similarity.popular-namespace-downloads` +|---------------|------------------------------------------------------------ +| Type | integer +| Default | `10000` +| Compatibility | Since 1.5.0 + +Downloads of its active extensions from which the more downloaded namespace of a pair counts as a popular target. The dashboard's namespaces view shows only pairs with a popular target by default, and admins can switch to all pairs. Must not be negative. + +| Property | `ovsx.scanning.name-similarity.popular-namespace-ratio` +|---------------|-------------------------------------------------------- +| Type | number +| Default | `10` +| Compatibility | Since 1.5.0 + +How many times the other namespace's downloads a popular target also needs, which keeps out pairs of two established namespaces that are rarely one squatting on the other. Must be at least 1. + ## OAuth2 The `ovsx.oauth2.attribute-names.[provider-name].*` configuration properties allow mapping a login provider's attributes to Open VSX user data. By default it provides an attribute name configuration for [GitHub](https://docs.github.com/en/free-pro-team@latest/developers/apps/building-oauth-apps). It is possible to configure attribute name mappings for multiple login providers. Make sure to also configure Spring Security using its `spring.security.oauth2.client.registration.[provider-name].*` and `spring.security.oauth2.client.provider.[provider-name].*` properties. diff --git a/server/CHANGELOG.md b/server/CHANGELOG.md index db5f943c9..55870aedd 100644 --- a/server/CHANGELOG.md +++ b/server/CHANGELOG.md @@ -4,6 +4,16 @@ This change log covers only the server of Open VSX. Releases up to and including v1.2.0 were backfilled from the GitHub release notes. Those list every pull request of the repository, so they also contain web UI and CLI changes. +## [next] (unreleased) + +### Added + +- The `NAME_SIMILARITY` publish check flags a version whose extension name or display name matches or resembles another namespace's active extension, without ever blocking publication; it runs while scanning is enabled and is configured by `ovsx.scanning.name-similarity.*` +- `GET /admin/name-squatting/collisions` looks flagged extensions, and those sharing a display name across namespaces, up again and groups each look-alike under the extension it resembles that was published first; `GET`, `POST` and `DELETE /admin/name-squatting/allowlist` manage the allowed pairs, which stop being reported; all require `manage_extensions` +- **Upgrade:** migration `V1_86` creates the `pg_trgm` extension, which the database owner can do since PostgreSQL 13, and the `name_similarity_allow` table; `V1_87` builds trigram indexes on `extension` and `extension_version` and an index on `extension_validation_failure` that block writes to those tables while building and give up after waiting 5 s for a lock, so to avoid the pause create them `CONCURRENTLY` beforehand as `V1_87` describes +- `GET /admin/name-squatting/namespaces` lists pairs of namespaces whose names are within an edit or two of each other or differ only in separators, by default only those whose more downloaded namespace counts as popular by `ovsx.scanning.name-similarity.popular-namespace-downloads` and `popular-namespace-ratio`; `POST` and `GET /admin/name-squatting/namespaces/allowlist` manage allowed namespace pairs, and `DELETE /admin/name-squatting/allowlist/{id}` removes either kind; all require `manage_extensions` +- **Upgrade:** migration `V1_88` lets `name_similarity_allow` hold pairs of namespaces and builds a trigram index on `namespace` names, which blocks writes to `namespace` while building and gives up after waiting 5 s for a lock + ## [1.4.0] - 2026-11-09 ### Added diff --git a/server/scripts/config-properties-baseline.txt b/server/scripts/config-properties-baseline.txt index 7d9071ca7..ee2e0ce9d 100644 --- a/server/scripts/config-properties-baseline.txt +++ b/server/scripts/config-properties-baseline.txt @@ -28,6 +28,12 @@ undocumented ovsx.scanning.enabled undocumented ovsx.scanning.max-archive-size-bytes undocumented ovsx.scanning.max-entry-count undocumented ovsx.scanning.max-single-file-bytes +undocumented ovsx.scanning.name-similarity.display-name-threshold +undocumented ovsx.scanning.name-similarity.enabled +undocumented ovsx.scanning.name-similarity.max-matches +undocumented ovsx.scanning.name-similarity.min-fuzzy-length +undocumented ovsx.scanning.name-similarity.name-threshold +undocumented ovsx.scanning.name-similarity.statement-timeout undocumented ovsx.scanning.namespace-ownership-check.check-active-extensions undocumented ovsx.scanning.namespace-ownership-check.enabled undocumented ovsx.scanning.namespace-ownership-check.enforced diff --git a/server/src/dev/resources/application.yml b/server/src/dev/resources/application.yml index 7fdbc21f7..0a39c0ee0 100644 --- a/server/src/dev/resources/application.yml +++ b/server/src/dev/resources/application.yml @@ -227,6 +227,15 @@ ovsx: only-protect-verified-names: false allow-similarity-to-own-names: true only-check-new-extensions: true + name-similarity: + enabled: true + name-threshold: 0.7 + display-name-threshold: 0.7 + min-fuzzy-length: 4 + max-matches: 10 + statement-timeout: 10s + popular-namespace-downloads: 10000 + popular-namespace-ratio: 10 secret-detection: enabled: true enforced: false diff --git a/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingAPI.java b/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingAPI.java new file mode 100644 index 000000000..93d585299 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingAPI.java @@ -0,0 +1,299 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.admin; + +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.Pattern; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.CrossOrigin; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.server.ResponseStatusException; + +import org.eclipse.openvsx.admin.NameSquattingService.NamespaceSort; +import org.eclipse.openvsx.entities.Permission; +import org.eclipse.openvsx.json.NameSquattingJson; +import org.eclipse.openvsx.json.ResultJson; +import org.eclipse.openvsx.settings.MutatingOperation; +import org.eclipse.openvsx.util.ErrorResultException; + +/** + * The name squatting admin dashboard: extensions whose names match or resemble an extension published + * earlier in another namespace, namespaces whose names resemble each other, and the pairs admins allowed. + * Deleting a look-alike goes through the admin extension delete endpoint. + */ +@RestController +@Validated +@RequestMapping("/admin/name-squatting") +@ApiResponse( + responseCode = "403", + description = "The manage_extensions permission is required", + content = @Content() +) +public class NameSquattingAPI { + + private final AdminService admins; + private final NameSquattingService nameSquatting; + + public NameSquattingAPI(AdminService admins, NameSquattingService nameSquatting) { + this.admins = admins; + this.nameSquatting = nameSquatting; + } + + @GetMapping(path = "/collisions", produces = MediaType.APPLICATION_JSON_VALUE) + @CrossOrigin + @Operation( + summary = "List look-alikes, grouped under the extension each resembles that was published first", + description = "Looks up again the extensions the NAME_SIMILARITY publish check flagged, the most recently " + + "flagged first, then those sharing a display name with another namespace's extension. Allowed " + + "pairs and pairs within one namespace are left out." + ) + @ApiResponse( + responseCode = "503", + description = "A lookup ran longer than ovsx.scanning.name-similarity.statement-timeout and was stopped", + content = @Content() + ) + @ApiResponse( + responseCode = "200", + description = "A page of groups", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = NameSquattingJson.Collisions.class) + ) + ) + public ResponseEntity getCollisions( + @RequestParam(defaultValue = "0") + @Parameter(description = "The nextOffset of the previous page, 0 for the first") + @Min(value = 0, message = "parameter must not be negative") int offset, + @RequestParam(defaultValue = "25") + @Parameter(description = "How many candidates to look up per batch") + @Min(value = 1, message = "parameter must be positive") + @Max(value = 100, message = "parameter must not be larger than 100") int size + ) { + admins.checkPermission(Permission.MANAGE_EXTENSIONS); + try { + return ResponseEntity.ok(nameSquatting.findCollisions(offset, size)); + } catch (ErrorResultException exc) { + throw toResponseStatus(exc); + } + } + + @PostMapping( + path = "/allowlist", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE + ) + @CrossOrigin + @MutatingOperation + @Operation(summary = "Allow a look-alike alongside an extension it resembles") + @ApiResponse( + responseCode = "200", + description = "The pair is allowed", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = ResultJson.class) + ) + ) + @ApiResponse( + responseCode = "400", + description = "The two extensions are the same or no longer resemble each other, or the reason is too long", + content = @Content() + ) + @ApiResponse(responseCode = "404", description = "An extension was not found", content = @Content()) + public ResponseEntity allow(@RequestBody NameSquattingJson.AllowRequest request) { + var admin = admins.checkPermission(Permission.MANAGE_EXTENSIONS); + try { + return ResponseEntity.ok(nameSquatting.allow(request, admin)); + } catch (ErrorResultException exc) { + throw toResponseStatus(exc); + } + } + + @GetMapping(path = "/allowlist", produces = MediaType.APPLICATION_JSON_VALUE) + @CrossOrigin + @Operation(summary = "List the allowed look-alikes, the most recently allowed first, with their allowed pairs") + @ApiResponse( + responseCode = "200", + description = "A page of allowed look-alikes", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = NameSquattingJson.Allowlist.class) + ) + ) + public ResponseEntity getAllowlist( + @RequestParam(defaultValue = "0") + @Min(value = 0, message = "parameter must not be negative") int page, + @RequestParam(defaultValue = "25") + @Min(value = 1, message = "parameter must be positive") + @Max(value = 100, message = "parameter must not be larger than 100") int size + ) { + admins.checkPermission(Permission.MANAGE_EXTENSIONS); + return ResponseEntity.ok(nameSquatting.findAllowlist(page, size)); + } + + @DeleteMapping(path = "/allowlist/{id}", produces = MediaType.APPLICATION_JSON_VALUE) + @CrossOrigin + @MutatingOperation + @Operation( + summary = "Remove an allowed pair of extensions or of namespaces, so it is reported again while the two still resemble each other" + ) + @ApiResponse( + responseCode = "200", + description = "The allow is removed", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = ResultJson.class) + ) + ) + @ApiResponse(responseCode = "404", description = "The allowed pair was not found", content = @Content()) + public ResponseEntity removeAllow( + @PathVariable + @Parameter(description = "Allowed pair ID") long id + ) { + var admin = admins.checkPermission(Permission.MANAGE_EXTENSIONS); + try { + return ResponseEntity.ok(nameSquatting.removeAllow(id, admin)); + } catch (ErrorResultException exc) { + throw toResponseStatus(exc); + } + } + + @GetMapping(path = "/namespaces", produces = MediaType.APPLICATION_JSON_VALUE) + @CrossOrigin + @Operation( + summary = "List pairs of namespaces whose names resemble each other", + description = "Names resemble each other when, ignoring case, they are equal up to 4 characters, within one " + + "edit up to 8 and within two for longer ones, or only differ in characters other than letters and " + + "digits. The namespace with more downloads is the target. Allowed pairs and pairs without an " + + "active extension on either side are left out. The pairs are looked up again at most once a " + + "minute, while allows apply at once." + ) + @ApiResponse( + responseCode = "503", + description = "The lookup ran longer than ovsx.scanning.name-similarity.statement-timeout and was stopped", + content = @Content() + ) + @ApiResponse( + responseCode = "200", + description = "A page of pairs", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = NameSquattingJson.NamespacePairs.class) + ) + ) + public ResponseEntity getNamespacePairs( + @RequestParam(defaultValue = "true") + @Parameter( + description = "Whether to list only the pairs whose target counts as popular" + ) boolean popularOnly, + @RequestParam(defaultValue = "downloads") + @Parameter( + description = "downloads: the most downloaded target first; newest: the look-alike that published first most recently first" + ) + @Pattern(regexp = "downloads|newest", message = "parameter must be downloads or newest") String sort, + @RequestParam(defaultValue = "0") + @Parameter(description = "How many pairs to skip, 0 for the first page") + @Min(value = 0, message = "parameter must not be negative") int offset, + @RequestParam(defaultValue = "25") + @Parameter(description = "How many pairs to return") + @Min(value = 1, message = "parameter must be positive") + @Max(value = 100, message = "parameter must not be larger than 100") int size + ) { + admins.checkPermission(Permission.MANAGE_EXTENSIONS); + var order = sort.equals("newest") ? NamespaceSort.NEWEST : NamespaceSort.DOWNLOADS; + try { + return ResponseEntity.ok(nameSquatting.findNamespacePairs(popularOnly, order, offset, size)); + } catch (ErrorResultException exc) { + throw toResponseStatus(exc); + } + } + + @PostMapping( + path = "/namespaces/allowlist", + consumes = MediaType.APPLICATION_JSON_VALUE, + produces = MediaType.APPLICATION_JSON_VALUE + ) + @CrossOrigin + @MutatingOperation + @Operation( + summary = "Allow a namespace alongside a namespace it resembles", + description = "The pair is no longer listed, whichever way round it was allowed. Allowing a pair already " + + "allowed succeeds without change." + ) + @ApiResponse( + responseCode = "200", + description = "The pair is allowed", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = ResultJson.class) + ) + ) + @ApiResponse( + responseCode = "400", + description = "The two namespaces are the same or do not resemble each other, or the reason is too long", + content = @Content() + ) + @ApiResponse(responseCode = "404", description = "A namespace was not found", content = @Content()) + public ResponseEntity allowNamespaces(@RequestBody NameSquattingJson.NamespaceAllowRequest request) { + var admin = admins.checkPermission(Permission.MANAGE_EXTENSIONS); + try { + return ResponseEntity.ok(nameSquatting.allowNamespaces(request, admin)); + } catch (ErrorResultException exc) { + throw toResponseStatus(exc); + } + } + + @GetMapping(path = "/namespaces/allowlist", produces = MediaType.APPLICATION_JSON_VALUE) + @CrossOrigin + @Operation(summary = "List the allowed pairs of namespaces, the most recently allowed first") + @ApiResponse( + responseCode = "200", + description = "A page of allowed pairs", + content = @Content( + mediaType = MediaType.APPLICATION_JSON_VALUE, + schema = @Schema(implementation = NameSquattingJson.NamespaceAllowlist.class) + ) + ) + public ResponseEntity getNamespaceAllowlist( + @RequestParam(defaultValue = "0") + @Parameter(description = "The page, 0 for the first") + @Min(value = 0, message = "parameter must not be negative") int page, + @RequestParam(defaultValue = "25") + @Parameter(description = "How many pairs per page") + @Min(value = 1, message = "parameter must be positive") + @Max(value = 100, message = "parameter must not be larger than 100") int size + ) { + admins.checkPermission(Permission.MANAGE_EXTENSIONS); + return ResponseEntity.ok(nameSquatting.findNamespaceAllowlist(page, size)); + } + + private static ResponseStatusException toResponseStatus(ErrorResultException exc) { + var status = exc.getStatus() != null ? exc.getStatus() : HttpStatus.BAD_REQUEST; + return new ResponseStatusException(status, exc.getMessage()); + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingService.java b/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingService.java new file mode 100644 index 000000000..5e2263b28 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/admin/NameSquattingService.java @@ -0,0 +1,741 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.admin; + +import java.sql.SQLException; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import org.jspecify.annotations.Nullable; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; + +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.NameSimilarityAllow; +import org.eclipse.openvsx.entities.NameSimilarityField; +import org.eclipse.openvsx.entities.Namespace; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.json.NameSquattingJson; +import org.eclipse.openvsx.json.ResultJson; +import org.eclipse.openvsx.repositories.NameSimilarityAllowRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Candidate; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.ExtensionNames; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Match; +import org.eclipse.openvsx.repositories.NamespaceSimilarityJooqRepository; +import org.eclipse.openvsx.repositories.RepositoryService; +import org.eclipse.openvsx.scanning.NameSimilarityCheckConfig; +import org.eclipse.openvsx.scanning.NameSimilarityCheckService; +import org.eclipse.openvsx.util.ErrorResultException; +import org.eclipse.openvsx.util.LogService; +import org.eclipse.openvsx.util.TimeUtil; + +/** + * The name squatting admin dashboard: looks up again the extensions the NAME_SIMILARITY check flagged and + * those sharing a display name across namespaces, lists the namespaces whose names resemble each other, + * and keeps the allowlist of pairs that are not squatting on each other. + *

+ * Nothing about a match is stored: every page looks its candidates up live, so a look-alike that was + * deleted, renamed or allowed since it was flagged no longer shows. Namespace pairs are the exception: + * finding them reads every namespace, so they are kept for {@link #NAMESPACE_PAIRS_TTL}, though allows + * still apply at once. + */ +@Service +public class NameSquattingService { + + /** Candidates are looked up in batches until a page is full, giving up after this many. */ + static final int MAX_BATCHES = 4; + + static final int MAX_REASON_LENGTH = 2048; + + /** + * How long the namespace pairs are reused before they are looked up again: a namespace created since + * shows up at most this late, while allows apply at once. + */ + static final Duration NAMESPACE_PAIRS_TTL = Duration.ofMinutes(1); + + /** How the namespaces view orders its pairs. */ + public enum NamespaceSort { + /** The pairs whose target has the most downloads first. */ + DOWNLOADS, + /** The pairs whose look-alike first published most recently first; look-alikes without any last. */ + NEWEST + } + + /** The SQLState of a statement cancelled by statement_timeout, among other cancellations. */ + private static final String QUERY_CANCELED = "57014"; + + /** The earliest publication date first; an unknown date counts as earliest. */ + static final Comparator PUBLISHED_FIRST = Comparator + .comparing(ExtensionNames::publishedDate, Comparator.nullsFirst(Comparator.naturalOrder())) + .thenComparingLong(ExtensionNames::id); + + private final NameSimilarityJooqRepository similarity; + private final NamespaceSimilarityJooqRepository namespaceSimilarity; + private final NameSimilarityAllowRepository allows; + private final NameSimilarityCheckService check; + private final NameSimilarityCheckConfig config; + private final RepositoryService repositories; + private final LogService logs; + private final EntityManager entityManager; + + /** + * Every namespace pair, allowed or not, under a single constant key. Local to this instance, so each + * server looks the pairs up for itself; allows are filtered out per request instead. + */ + private final Cache> namespacePairs = Caffeine + .newBuilder() + .expireAfterWrite(NAMESPACE_PAIRS_TTL) + .maximumSize(1) + .build(); + + public NameSquattingService( + NameSimilarityJooqRepository similarity, + NamespaceSimilarityJooqRepository namespaceSimilarity, + NameSimilarityAllowRepository allows, + NameSimilarityCheckService check, + NameSimilarityCheckConfig config, + RepositoryService repositories, + LogService logs, + EntityManager entityManager + ) { + this.similarity = similarity; + this.namespaceSimilarity = namespaceSimilarity; + this.allows = allows; + this.check = check; + this.config = config; + this.repositories = repositories; + this.logs = logs; + this.entityManager = entityManager; + } + + /** + * The look-alikes of the candidates from {@code offset} on, grouped under the extension each resembles + * that was published first. Groups follow the order of their most recently flagged candidate; a page + * may hold more than {@code size} look-alikes, or fewer once candidates run out. + *

+ * Deliberately not transactional: every lookup runs in a transaction of its own, so the statement + * timeout one sets cannot outlive it, and one that is cancelled fails only itself. + * + * @throws ErrorResultException with 503 when a lookup ran out of its statement timeout + */ + public NameSquattingJson.Collisions findCollisions(int offset, int size) throws ErrorResultException { + try { + return lookUpCollisions(offset, size); + } catch (RuntimeException exc) { + if (!isStatementTimeout(exc)) { + throw exc; + } + throw new ErrorResultException( + "Looking up look-alikes took longer than " + check.getStatementTimeout().toSeconds() + + " s and was stopped. Try again, or raise ovsx.scanning.name-similarity.statement-timeout.", + HttpStatus.SERVICE_UNAVAILABLE); + } + } + + private NameSquattingJson.Collisions lookUpCollisions(int offset, int size) { + var pairs = new LinkedHashMap(); + var cursor = offset; + var hasMore = true; + for (var batch = 0; batch < MAX_BATCHES && hasMore && pairs.size() < size; batch++) { + var candidates = similarity.findCandidates( + NameSimilarityCheckService.CHECK_TYPE, + cursor, + size, + check.getStatementTimeout()); + cursor += candidates.size(); + hasMore = candidates.size() == size; + collectPairs(candidates, pairs); + } + + var lookalikeIds = pairs.keySet(); + var lookalikes = byId(similarity.findNames(lookalikeIds)); + var groups = new LinkedHashMap>(); + pairs.values().forEach(pair -> groups.computeIfAbsent(pair.anchor().id(), id -> new ArrayList<>()).add(pair)); + var json = groups.values().stream() + .map( + group -> new NameSquattingJson.Group( + toJson(group.getFirst().anchor()), + group.stream() + .sorted( + Comparator.comparing( + Pair::closest, + NameSimilarityCheckService.CLOSEST_FIRST)) + .map(pair -> toJson(pair, lookalikes.get(pair.lookalikeId()))) + .toList())) + .toList(); + return new NameSquattingJson.Collisions(json, cursor, hasMore); + } + + /** + * Look the candidates up and add their pairs to {@code pairs}, keyed by look-alike, which keeps each + * look-alike under the earliest published extension it resembles. + */ + private void collectPairs(List candidates, Map pairs) { + if (candidates.isEmpty()) { + return; + } + var ids = candidates.stream().map(Candidate::extensionId).toList(); + var names = byId(similarity.findNames(ids)); + var allowed = check.allowedPartners(ids); + + var found = new ArrayList(); + for (var candidate : candidates) { + var candidateNames = names.get(candidate.extensionId()); + if (candidateNames == null || !candidateNames.active()) { + continue; + } + var partners = allowed.getOrDefault(candidate.extensionId(), Set.of()); + check.findMatches(candidateNames.namespaceName(), candidateNames.name(), candidateNames.displayNames()) + .stream() + .filter(match -> !partners.contains(match.extensionId())) + .collect(Collectors.groupingBy(Match::extensionId)) + .forEach((otherId, matches) -> found.add(new Found(candidate, candidateNames, otherId, matches))); + } + + var others = byId(similarity.findNames(found.stream().map(Found::otherId).toList())); + for (var match : found) { + var other = others.get(match.otherId()); + if (other != null) { + var pair = Pair.of(match, other); + pairs.merge(pair.lookalikeId(), pair, Pair::earlierAnchor); + } + } + } + + /** Allow the look-alike alongside the other extension, so the pair is no longer reported. */ + @Transactional(rollbackOn = ErrorResultException.class) + public ResultJson allow(NameSquattingJson.AllowRequest request, UserData admin) throws ErrorResultException { + var reason = validReason(request.reason()); + var lookalike = findExtension(request.namespace(), request.extension()); + var other = findExtension(request.otherNamespace(), request.otherExtension()); + if (lookalike.getId() == other.getId()) { + throw new ErrorResultException("An extension cannot be allowed alongside itself", HttpStatus.BAD_REQUEST); + } + if (allows.findPair(lookalike.getId(), other.getId()).isPresent()) { + return ResultJson.success("Already allowed " + toId(lookalike) + " alongside " + toId(other)); + } + + var lookalikeNames = similarity.findNames(List.of(lookalike.getId())).getFirst(); + var closest = check + .findMatches(lookalikeNames.namespaceName(), lookalikeNames.name(), lookalikeNames.displayNames()) + .stream() + .filter(match -> match.extensionId() == other.getId()) + .min(NameSimilarityCheckService.CLOSEST_FIRST) + .orElseThrow( + () -> new ErrorResultException( + toId(lookalike) + " no longer resembles " + toId(other) + + ", so there is nothing to allow", + HttpStatus.BAD_REQUEST)); + + var allow = new NameSimilarityAllow(); + allow.setExtensionId(lookalike.getId()); + allow.setOtherExtensionId(other.getId()); + allow.setField(closest.field()); + allow.setSimilarity(closest.similarity()); + allow.setLookalikeValue(closest.probeValue()); + allow.setOtherValue(closest.value()); + allow.setReason(reason); + allow.setDecidedById(admin.getId()); + allow.setDecidedAt(TimeUtil.getCurrentUTC()); + allows.save(allow); + + var result = ResultJson.success("Allowed " + toId(lookalike) + " alongside " + toId(other)); + logs.logAction(admin, result); + return result; + } + + /** + * Remove an allow of extensions or of namespaces, so the pair is reported again while the two still + * resemble each other. + * + * @throws ErrorResultException with 404 when there is no allow with the id + */ + @Transactional(rollbackOn = ErrorResultException.class) + public ResultJson removeAllow(long id, UserData admin) throws ErrorResultException { + var allow = allows.findById(id) + .orElseThrow(() -> new ErrorResultException("Allowed pair not found: " + id, HttpStatus.NOT_FOUND)); + if (allow.getField() == NameSimilarityField.NAMESPACE) { + allows.delete(allow); + var result = ResultJson.success( + "Removed the allow of namespace " + allow.getLookalikeValue() + " alongside " + + allow.getOtherValue()); + logs.logAction(admin, result); + return result; + } + var names = byId(similarity.findNames(List.of(allow.getExtensionId(), allow.getOtherExtensionId()))); + allows.delete(allow); + + var result = ResultJson.success( + "Removed the allow of " + toId(names.get(allow.getExtensionId())) + + " alongside " + toId(names.get(allow.getOtherExtensionId()))); + logs.logAction(admin, result); + return result; + } + + /** The allowed look-alikes, the most recently allowed first, each with every pair it was allowed in. */ + @Transactional + public NameSquattingJson.Allowlist findAllowlist(int page, int size) { + // One more than asked tells whether there is a next page. + var extensionIds = allows.findAllowedExtensionIds(PageRequest.of(page, size + 1)); + var hasMore = extensionIds.size() > size; + var pageIds = hasMore ? extensionIds.subList(0, size) : extensionIds; + + var pageAllows = allows.findByExtensionIdInOrderByDecidedAtDesc(pageIds); + var involved = new HashSet(pageIds); + pageAllows.forEach(allow -> involved.add(allow.getOtherExtensionId())); + var names = byId(similarity.findNames(involved)); + var deciders = new HashMap(); + + var byExtension = pageAllows.stream().collect(Collectors.groupingBy(NameSimilarityAllow::getExtensionId)); + var groups = pageIds.stream() + .filter(names::containsKey) + .map( + extensionId -> new NameSquattingJson.AllowlistGroup( + toJson(names.get(extensionId)), + byExtension.getOrDefault(extensionId, List.of()).stream() + .filter(allow -> names.containsKey(allow.getOtherExtensionId())) + .map(allow -> toJson(allow, names, deciders)) + .toList())) + .toList(); + return new NameSquattingJson.Allowlist(groups, page, hasMore); + } + + private NameSquattingJson.Allow toJson( + NameSimilarityAllow allow, + Map names, + Map deciders + ) { + var extension = names.get(allow.getExtensionId()); + var other = names.get(allow.getOtherExtensionId()); + var renamed = !hasValue(extension, allow.getField(), allow.getLookalikeValue()) + || !hasValue(other, allow.getField(), allow.getOtherValue()); + return new NameSquattingJson.Allow( + allow.getId(), + toJson(other), + allow.getField().name(), + allow.getSimilarity(), + allow.getLookalikeValue(), + allow.getOtherValue(), + renamed, + allow.getReason(), + decidedBy(allow, deciders), + TimeUtil.toUTCString(allow.getDecidedAt())); + } + + /** The login name of the admin who allowed the pair, looked up once per admin. */ + private @Nullable String decidedBy(NameSimilarityAllow allow, Map deciders) { + if (allow.getDecidedById() == null) { + return null; + } + return deciders.computeIfAbsent(allow.getDecidedById(), id -> { + var user = entityManager.find(UserData.class, id); + return user != null ? user.getLoginName() : null; + }); + } + + /** + * A page of the namespace pairs no admin allowed, each oriented with the namespace with more downloads + * as target (see {@link #TARGET_FIRST}). A pair counts as popular when its target has at least + * {@code ovsx.scanning.name-similarity.popular-namespace-downloads}, and + * {@code popular-namespace-ratio} times the look-alike's. + *

+ * The pairs come from a lookup reused for {@link #NAMESPACE_PAIRS_TTL}, but the allowlist is read on + * every call, so a pair allowed or no longer allowed shows the change on the next page. + * + * @param popularOnly whether to leave out the pairs that do not count as popular; the totals of the + * result count both + * @param sort the order of the pairs, ties broken by target and then look-alike name + * @param offset how many pairs of that order to skip + * @param size the most pairs to return + * @throws ErrorResultException with 503 when the lookup ran out of its statement timeout + */ + public NameSquattingJson.NamespacePairs findNamespacePairs( + boolean popularOnly, + NamespaceSort sort, + int offset, + int size + ) throws ErrorResultException { + List pairs; + try { + pairs = namespacePairs.get( + Boolean.TRUE, + key -> namespaceSimilarity.findSimilarPairs(check.getStatementTimeout())); + } catch (RuntimeException exc) { + if (!isStatementTimeout(exc)) { + throw exc; + } + throw new ErrorResultException( + "Looking up namespace pairs took longer than " + check.getStatementTimeout().toSeconds() + + " s and was stopped. Try again, or raise ovsx.scanning.name-similarity.statement-timeout.", + HttpStatus.SERVICE_UNAVAILABLE); + } + + var allowed = allows.findByField(NameSimilarityField.NAMESPACE).stream() + .map(allow -> pairKey(allow.getNamespaceId(), allow.getOtherNamespaceId())) + .collect(Collectors.toSet()); + var shown = pairs.stream() + .filter(pair -> !allowed.contains(pairKey(pair.first().id(), pair.second().id()))) + .map(this::orient) + .toList(); + var popular = (int) shown.stream().filter(OrientedPair::popular).count(); + var page = shown.stream() + .filter(pair -> !popularOnly || pair.popular()) + .sorted(sort == NamespaceSort.NEWEST ? NEWEST_LOOKALIKE_FIRST : MOST_DOWNLOADED_FIRST) + .skip(offset) + .limit(size + 1L) + .map(NameSquattingService::toJson) + .toList(); + var hasMore = page.size() > size; + return new NameSquattingJson.NamespacePairs( + hasMore ? page.subList(0, size) : page, + shown.size(), + popular, + offset, + hasMore); + } + + /** + * Forget the namespace pairs, so the next page looks them up again rather than waiting out + * {@link #NAMESPACE_PAIRS_TTL}. For tests that change namespaces between pages. + */ + void forgetNamespacePairs() { + namespacePairs.invalidateAll(); + } + + /** + * Allow two namespaces alongside each other, so the pair is no longer reported in either view. The + * names are stored as they are now, with their similarity, so the allowlist still reads after a rename. + * Allowing a pair already allowed, either way round, succeeds without storing it again. + * + * @throws ErrorResultException with 404 when either namespace does not exist, or with 400 when they + * are the same namespace, do not resemble each other by the rule of + * {@link NamespaceSimilarityJooqRepository#compare}, or the reason is + * longer than {@link #MAX_REASON_LENGTH} + */ + @Transactional(rollbackOn = ErrorResultException.class) + public ResultJson allowNamespaces(NameSquattingJson.NamespaceAllowRequest request, UserData admin) + throws ErrorResultException { + var reason = validReason(request.reason()); + var lookalike = findNamespace(request.namespace()); + var other = findNamespace(request.otherNamespace()); + if (lookalike.getId() == other.getId()) { + throw new ErrorResultException("A namespace cannot be allowed alongside itself", HttpStatus.BAD_REQUEST); + } + if (allows.findNamespacePair(lookalike.getId(), other.getId()).isPresent()) { + return ResultJson.success( + "Already allowed namespace " + lookalike.getName() + " alongside " + other.getName()); + } + var comparison = namespaceSimilarity.compare(lookalike.getName(), other.getName()); + if (!comparison.resembles()) { + throw new ErrorResultException( + "Namespace " + lookalike.getName() + " does not resemble " + other.getName() + + ", so there is nothing to allow", + HttpStatus.BAD_REQUEST); + } + + var allow = new NameSimilarityAllow(); + allow.setNamespaceId(lookalike.getId()); + allow.setOtherNamespaceId(other.getId()); + allow.setField(NameSimilarityField.NAMESPACE); + allow.setSimilarity(comparison.similarity()); + allow.setLookalikeValue(lookalike.getName()); + allow.setOtherValue(other.getName()); + allow.setReason(reason); + allow.setDecidedById(admin.getId()); + allow.setDecidedAt(TimeUtil.getCurrentUTC()); + allows.save(allow); + + var result = ResultJson.success( + "Allowed namespace " + lookalike.getName() + " alongside " + other.getName()); + logs.logAction(admin, result); + return result; + } + + /** + * The allowed pairs of namespaces, the most recently allowed first, under the names they had when + * allowed. Unlike the extension allowlist they are not grouped: each pair is one entry. + * + * @param page the page, from 0 + * @param size the most pairs per page; one more is fetched to tell whether another page follows + */ + @Transactional + public NameSquattingJson.NamespaceAllowlist findNamespaceAllowlist(int page, int size) { + // One more than asked tells whether there is a next page. + var found = allows.findByFieldOrderByDecidedAtDescIdDesc( + NameSimilarityField.NAMESPACE, + PageRequest.of(page, size + 1)); + var hasMore = found.size() > size; + var deciders = new HashMap(); + var json = (hasMore ? found.subList(0, size) : found).stream() + .map( + allow -> new NameSquattingJson.NamespaceAllow( + allow.getId(), + allow.getLookalikeValue(), + allow.getOtherValue(), + allow.getSimilarity(), + allow.getReason(), + decidedBy(allow, deciders), + TimeUtil.toUTCString(allow.getDecidedAt()))) + .toList(); + return new NameSquattingJson.NamespaceAllowlist(json, page, hasMore); + } + + /** + * A namespace pair with the likelier target picked out. + * + * @param pair the pair as looked up, for the measures of how the names compare + * @param popular whether the target counts as popular next to the look-alike + */ + private record OrientedPair( + NamespaceSimilarityJooqRepository.Side target, + NamespaceSimilarityJooqRepository.Side lookalike, + NamespaceSimilarityJooqRepository.Pair pair, + boolean popular + ) {} + + /** Pick out the target of the pair by {@link #TARGET_FIRST} and tell whether it counts as popular. */ + private OrientedPair orient(NamespaceSimilarityJooqRepository.Pair pair) { + var firstIsTarget = TARGET_FIRST.compare(pair.first(), pair.second()) <= 0; + var target = firstIsTarget ? pair.first() : pair.second(); + var lookalike = firstIsTarget ? pair.second() : pair.first(); + var popular = target.downloads() >= config.getPopularNamespaceDownloads() + && target.downloads() >= config.getPopularNamespaceRatio() * lookalike.downloads(); + return new OrientedPair(target, lookalike, pair, popular); + } + + private static NameSquattingJson.NamespacePair toJson(OrientedPair oriented) { + var pair = oriented.pair(); + return new NameSquattingJson.NamespacePair( + toJson(oriented.target()), + toJson(oriented.lookalike()), + pair.editDistance(), + pair.similarity(), + pair.separatorOnly(), + pair.sharedMember(), + oriented.popular()); + } + + private static NameSquattingJson.NamespaceSummary toJson(NamespaceSimilarityJooqRepository.Side side) { + return new NameSquattingJson.NamespaceSummary( + side.name(), + side.downloads(), + side.activeExtensions(), + side.firstPublished() != null ? TimeUtil.toUTCString(side.firstPublished()) : null); + } + + /** + * The likelier target of a pair first: more downloads, then the earlier first publication, a namespace + * without any last, then the lower id so the order is total. The id says nothing of age: namespace ids + * are handed out in blocks per server instance. + */ + static final Comparator TARGET_FIRST = Comparator + .comparingLong(NamespaceSimilarityJooqRepository.Side::downloads) + .reversed() + .thenComparing( + NamespaceSimilarityJooqRepository.Side::firstPublished, + Comparator.nullsLast(Comparator.naturalOrder())) + .thenComparingLong(NamespaceSimilarityJooqRepository.Side::id); + + /** {@link NamespaceSort#DOWNLOADS}: the most downloaded target first, then by names ignoring case. */ + private static final Comparator MOST_DOWNLOADED_FIRST = Comparator + .comparingLong((OrientedPair pair) -> pair.target().downloads()) + .reversed() + .thenComparing(pair -> pair.target().name().toLowerCase(Locale.ROOT)) + .thenComparing(pair -> pair.lookalike().name().toLowerCase(Locale.ROOT)); + + /** + * {@link NamespaceSort#NEWEST}: the look-alike whose first active extension was published most recently + * first, look-alikes without one last, then as {@link #MOST_DOWNLOADED_FIRST}. + */ + private static final Comparator NEWEST_LOOKALIKE_FIRST = Comparator + .comparing( + (OrientedPair pair) -> pair.lookalike().firstPublished(), + Comparator.nullsLast(Comparator.reverseOrder())) + .thenComparing(MOST_DOWNLOADED_FIRST); + + /** + * Identifies a pair of namespaces whichever way round it is given. Both ids are set on a namespace + * allow, which the database checks. + */ + private static String pairKey(@Nullable Long first, @Nullable Long second) { + return Math.min(first, second) + ":" + Math.max(first, second); + } + + /** + * The reason stripped of surrounding whitespace, {@code null} when blank. + * + * @throws ErrorResultException with 400 when it is longer than {@link #MAX_REASON_LENGTH} + */ + private static @Nullable String validReason(@Nullable String reason) throws ErrorResultException { + var stripped = reason == null || reason.isBlank() ? null : reason.strip(); + if (stripped != null && stripped.length() > MAX_REASON_LENGTH) { + throw new ErrorResultException( + "The reason must not be longer than " + MAX_REASON_LENGTH + " characters", + HttpStatus.BAD_REQUEST); + } + return stripped; + } + + /** + * The namespace of the name, ignoring case as {@link RepositoryService#findNamespace} does. + * + * @throws ErrorResultException with 404 when there is none + */ + private Namespace findNamespace(@Nullable String name) throws ErrorResultException { + var namespace = name == null ? null : repositories.findNamespace(name); + if (namespace == null) { + throw new ErrorResultException("Namespace not found: " + name, HttpStatus.NOT_FOUND); + } + return namespace; + } + + /** Whether PostgreSQL cancelled the statement for running out of its statement timeout. */ + static boolean isStatementTimeout(Throwable exc) { + for (var cause = exc; cause != null; cause = cause.getCause()) { + if (cause instanceof SQLException sql && QUERY_CANCELED.equals(sql.getSQLState())) { + return true; + } + } + return false; + } + + /** Whether the extension still has the value it had for the field when the pair was allowed. */ + static boolean hasValue(ExtensionNames names, NameSimilarityField field, String value) { + return switch (field) { + case NAME -> names.name().equalsIgnoreCase(value); + case NAMESPACE -> names.namespaceName().equalsIgnoreCase(value); + case DISPLAY_NAME -> { + var normalized = NameSimilarityJooqRepository.normalizeDisplayName(value); + yield names.displayNames().stream() + .map(NameSimilarityJooqRepository::normalizeDisplayName) + .anyMatch(normalized::equals); + } + }; + } + + private Extension findExtension(@Nullable String namespace, @Nullable String name) throws ErrorResultException { + var extension = namespace == null || name == null ? null : repositories.findExtension(name, namespace); + if (extension == null) { + throw new ErrorResultException("Extension not found: " + namespace + "." + name, HttpStatus.NOT_FOUND); + } + return extension; + } + + private static Map byId(List names) { + return names.stream().collect(Collectors.toMap(ExtensionNames::id, Function.identity())); + } + + private static String toId(Extension extension) { + return extension.getNamespace().getName() + "." + extension.getName(); + } + + private static String toId(@Nullable ExtensionNames names) { + return names == null ? "a removed extension" : names.namespaceName() + "." + names.name(); + } + + private static NameSquattingJson.Extension toJson(ExtensionNames names) { + var displayName = names.displayNames().stream() + .min(Comparator.comparing(name -> name.toLowerCase(Locale.ROOT))) + .orElse(null); + return new NameSquattingJson.Extension( + names.namespaceName(), + names.name(), + displayName, + names.downloadCount(), + names.publishedDate() != null ? TimeUtil.toUTCString(names.publishedDate()) : null, + names.activeVersionCount(), + names.active()); + } + + private static NameSquattingJson.Lookalike toJson(Pair pair, ExtensionNames lookalike) { + return new NameSquattingJson.Lookalike( + toJson(lookalike), + pair.matches(), + pair.namespaceSimilarity(), + pair.flaggedAt() != null ? TimeUtil.toUTCString(pair.flaggedAt()) : null); + } + + /** A candidate's matches with one other extension, as looked up from the candidate's side. */ + private record Found(Candidate candidate, ExtensionNames candidateNames, long otherId, List matches) {} + + /** A look-alike, the extension it resembles that was published first, and how they compare. */ + private record Pair( + ExtensionNames anchor, + long lookalikeId, + List matches, + Match closest, + float namespaceSimilarity, + @Nullable LocalDateTime flaggedAt + ) { + static Pair of(Found found, ExtensionNames other) { + var candidateFirst = PUBLISHED_FIRST.compare(found.candidateNames(), other) < 0; + var sorted = found.matches().stream().sorted(NameSimilarityCheckService.CLOSEST_FIRST).toList(); + // Matches are looked up from the candidate's side: value is the other extension's. + var matches = sorted.stream() + .map( + m -> candidateFirst + ? new NameSquattingJson.Match( + m.field().name(), + m.probeValue(), + m.value(), + m.similarity(), + m.exact()) + : new NameSquattingJson.Match( + m.field().name(), + m.value(), + m.probeValue(), + m.similarity(), + m.exact())) + .toList(); + return new Pair( + candidateFirst ? found.candidateNames() : other, + candidateFirst ? other.id() : found.candidateNames().id(), + matches, + sorted.getFirst(), + sorted.getFirst().namespaceSimilarity(), + found.candidate().flaggedAt()); + } + + /** Of two pairs of one look-alike, the one with the earlier anchor, with the later of their flags. */ + Pair earlierAnchor(Pair other) { + var earlier = PUBLISHED_FIRST.compare(anchor, other.anchor) <= 0 ? this : other; + var flag = flaggedAt == null || (other.flaggedAt != null && other.flaggedAt.isAfter(flaggedAt)) + ? other.flaggedAt + : flaggedAt; + return new Pair( + earlier.anchor, + earlier.lookalikeId, + earlier.matches, + earlier.closest, + earlier.namespaceSimilarity, + flag); + } + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityAllow.java b/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityAllow.java new file mode 100644 index 000000000..da5fdb681 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityAllow.java @@ -0,0 +1,181 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.entities; + +import java.io.Serial; +import java.io.Serializable; +import java.time.LocalDateTime; + +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.EnumType; +import jakarta.persistence.Enumerated; +import jakarta.persistence.GeneratedValue; +import jakarta.persistence.Id; +import jakarta.persistence.SequenceGenerator; +import jakarta.persistence.Table; +import org.jspecify.annotations.Nullable; + +/** + * A pair of extensions, or of namespaces, an admin has confirmed are not squatting on each other, so + * the pair is no longer reported. A pair is stored once, whichever way round it was allowed. + *

+ * A {@link NameSimilarityField#NAMESPACE} pair sets the namespace ids, any other the extension ids. + */ +@Entity +@Table(name = "name_similarity_allow") +public class NameSimilarityAllow implements Serializable { + + @Serial + private static final long serialVersionUID = 1L; + + @Id + @GeneratedValue(generator = "nameSimilarityAllowSeq") + @SequenceGenerator(name = "nameSimilarityAllowSeq", sequenceName = "name_similarity_allow_seq", allocationSize = 1) + private long id; + + /** The look-alike that was allowed, for a pair of extensions. */ + @Column(name = "extension_id") + private @Nullable Long extensionId; + + /** The extension the look-alike was allowed alongside. */ + @Column(name = "other_extension_id") + private @Nullable Long otherExtensionId; + + /** The look-alike that was allowed, for a pair of namespaces. */ + @Column(name = "namespace_id") + private @Nullable Long namespaceId; + + /** The namespace the look-alike was allowed alongside. */ + @Column(name = "other_namespace_id") + private @Nullable Long otherNamespaceId; + + /** The field that matched most closely when the pair was allowed. */ + @Enumerated(EnumType.STRING) + @Column(nullable = false, length = 16) + private NameSimilarityField field; + + /** Trigram similarity of the two values, from 0 to 1. */ + @Column(nullable = false) + private float similarity; + + /** The look-alike's value of {@link #field} when the pair was allowed. */ + @Column(name = "lookalike_value", nullable = false) + private String lookalikeValue; + + /** The other side's value of {@link #field} when the pair was allowed. */ + @Column(name = "other_value", nullable = false) + private String otherValue; + + @Column(length = 2048) + private @Nullable String reason; + + /** The admin who allowed the pair; {@code null} once that user is gone. */ + @Column(name = "decided_by_id") + private @Nullable Long decidedById; + + @Column(name = "decided_at", nullable = false) + private LocalDateTime decidedAt; + + public long getId() { + return id; + } + + public @Nullable Long getExtensionId() { + return extensionId; + } + + public void setExtensionId(@Nullable Long extensionId) { + this.extensionId = extensionId; + } + + public @Nullable Long getOtherExtensionId() { + return otherExtensionId; + } + + public void setOtherExtensionId(@Nullable Long otherExtensionId) { + this.otherExtensionId = otherExtensionId; + } + + public @Nullable Long getNamespaceId() { + return namespaceId; + } + + public void setNamespaceId(@Nullable Long namespaceId) { + this.namespaceId = namespaceId; + } + + public @Nullable Long getOtherNamespaceId() { + return otherNamespaceId; + } + + public void setOtherNamespaceId(@Nullable Long otherNamespaceId) { + this.otherNamespaceId = otherNamespaceId; + } + + public NameSimilarityField getField() { + return field; + } + + public void setField(NameSimilarityField field) { + this.field = field; + } + + public float getSimilarity() { + return similarity; + } + + public void setSimilarity(float similarity) { + this.similarity = similarity; + } + + public String getLookalikeValue() { + return lookalikeValue; + } + + public void setLookalikeValue(String lookalikeValue) { + this.lookalikeValue = lookalikeValue; + } + + public String getOtherValue() { + return otherValue; + } + + public void setOtherValue(String otherValue) { + this.otherValue = otherValue; + } + + public @Nullable String getReason() { + return reason; + } + + public void setReason(@Nullable String reason) { + this.reason = reason; + } + + public @Nullable Long getDecidedById() { + return decidedById; + } + + public void setDecidedById(@Nullable Long decidedById) { + this.decidedById = decidedById; + } + + public LocalDateTime getDecidedAt() { + return decidedAt; + } + + public void setDecidedAt(LocalDateTime decidedAt) { + this.decidedAt = decidedAt; + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityField.java b/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityField.java new file mode 100644 index 000000000..28c13cd21 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/entities/NameSimilarityField.java @@ -0,0 +1,25 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.entities; + +/** + * The name of an extension that two extensions are compared on when looking for name squatting. + */ +public enum NameSimilarityField { + /** The extension name, compared case-insensitively. */ + NAME, + /** The display name of an active version, compared ignoring case and surrounding whitespace. */ + DISPLAY_NAME, + /** The namespace name, compared case-insensitively. Only ever reported alongside another field. */ + NAMESPACE +} diff --git a/server/src/main/java/org/eclipse/openvsx/json/NameSquattingJson.java b/server/src/main/java/org/eclipse/openvsx/json/NameSquattingJson.java new file mode 100644 index 000000000..6bd90323f --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/json/NameSquattingJson.java @@ -0,0 +1,170 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.json; + +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import io.swagger.v3.oas.annotations.media.Schema; +import org.jspecify.annotations.Nullable; + +/** The bodies of the name squatting admin endpoints. */ +public final class NameSquattingJson { + + private NameSquattingJson() { + } + + @Schema(name = "NameSquattingExtension", description = "An extension as the name squatting dashboard shows it") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Extension( + String namespace, + String name, + @Schema(description = "A display name of one of its active versions") @Nullable String displayName, + int downloadCount, + @Schema(description = "UTC timestamp of its first publication") @Nullable String publishedDate, + int activeVersionCount, + boolean active + ) {} + + @Schema( + name = "NameSquattingMatch", + description = "How a look-alike's name compares with the extension published first" + ) + public record Match( + @Schema(allowableValues = { "NAME", "DISPLAY_NAME" }) String field, + @Schema(description = "The value of the extension published first") String value, + @Schema(description = "The look-alike's value") String lookalikeValue, + @Schema(description = "Trigram similarity, from 0 to 1") float similarity, + @Schema(description = "Whether the values are equal ignoring case and surrounding whitespace") boolean exact + ) {} + + @Schema(name = "NameSquattingLookalike") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Lookalike( + Extension extension, + @Schema(description = "Closest first") List matches, + @Schema( + description = "Trigram similarity of the two namespace names, from 0 to 1" + ) float namespaceSimilarity, + @Schema( + description = "UTC timestamp of the latest NAME_SIMILARITY flag of either extension, absent for a display name only shared" + ) @Nullable String flaggedAt + ) {} + + @Schema(name = "NameSquattingGroup", description = "An extension and the later extensions that resemble it") + public record Group(Extension anchor, List lookalikes) {} + + @Schema(name = "NameSquattingCollisions") + public record Collisions( + List groups, + @Schema(description = "Pass as offset to load the next groups") int nextOffset, + boolean hasMore + ) {} + + @Schema( + name = "NameSquattingAllowRequest", + description = "A look-alike to allow alongside an extension it resembles" + ) + @JsonInclude(JsonInclude.Include.NON_NULL) + public record AllowRequest( + String namespace, + String extension, + String otherNamespace, + String otherExtension, + @Nullable String reason + ) {} + + @Schema(name = "NameSquattingAllow", description = "A pair an admin allowed") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record Allow( + long id, + Extension other, + @Schema(allowableValues = { "NAME", "DISPLAY_NAME", "NAMESPACE" }) String field, + float similarity, + @Schema(description = "The allowed extension's value when it was allowed") String value, + @Schema(description = "The other extension's value when it was allowed") String otherValue, + @Schema(description = "Whether either value has changed since") boolean renamed, + @Nullable String reason, + @Schema(description = "Login name of the admin, absent once that user is gone") @Nullable String decidedBy, + String decidedAt + ) {} + + @Schema(name = "NameSquattingAllowlistGroup", description = "An allowed extension and the pairs it was allowed in") + public record AllowlistGroup(Extension extension, List allows) {} + + @Schema(name = "NameSquattingAllowlist") + public record Allowlist(List groups, int page, boolean hasMore) {} + + @Schema(name = "NameSquattingNamespace", description = "A namespace as the name squatting dashboard shows it") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record NamespaceSummary( + String name, + @Schema(description = "Downloads of its active extensions") long downloads, + @Schema(description = "How many active extensions it has") int activeExtensions, + @Schema( + description = "UTC timestamp of its earliest active extension's publication, absent without any" + ) @Nullable String firstPublished + ) {} + + @Schema( + name = "NameSquattingNamespacePair", + description = "Two namespaces whose names resemble each other, the one with more downloads as target" + ) + public record NamespacePair( + NamespaceSummary target, + NamespaceSummary lookalike, + @Schema(description = "Levenshtein distance of the names, ignoring case") int editDistance, + @Schema(description = "Trigram similarity of the names, from 0 to 1") float similarity, + @Schema( + description = "Whether the names only differ in characters other than letters and digits" + ) boolean separatorOnly, + @Schema(description = "Whether a user is a member of both namespaces") boolean sharedMember, + @Schema(description = "Whether the target counts as popular next to the look-alike") boolean popular + ) {} + + @Schema(name = "NameSquattingNamespacePairs") + public record NamespacePairs( + List pairs, + @Schema(description = "Pairs not allowed, popular or not") int total, + @Schema(description = "Of those, the pairs with a popular target") int popularTotal, + @Schema(description = "The offset the page starts at") int offset, + @Schema(description = "Whether more pairs follow the page") boolean hasMore + ) {} + + @Schema(name = "NameSquattingNamespaceAllowRequest", description = "Two namespaces to allow alongside each other") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record NamespaceAllowRequest( + @Schema(description = "Name of the look-alike") String namespace, + @Schema(description = "Name of the namespace it resembles") String otherNamespace, + @Schema(description = "Why the pair is not squatting, at most 2048 characters") @Nullable String reason + ) {} + + @Schema(name = "NameSquattingNamespaceAllow", description = "A pair of namespaces an admin allowed") + @JsonInclude(JsonInclude.Include.NON_NULL) + public record NamespaceAllow( + long id, + @Schema(description = "The look-alike's name when it was allowed") String namespace, + @Schema(description = "The other namespace's name when it was allowed") String otherNamespace, + @Schema(description = "Trigram similarity of the names when allowed, from 0 to 1") float similarity, + @Nullable String reason, + @Schema(description = "Login name of the admin, absent once that user is gone") @Nullable String decidedBy, + @Schema(description = "UTC timestamp of the allow") String decidedAt + ) {} + + @Schema(name = "NameSquattingNamespaceAllowlist") + public record NamespaceAllowlist( + @Schema(description = "The most recently allowed first") List allows, + int page, + @Schema(description = "Whether another page follows") boolean hasMore + ) {} +} diff --git a/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepository.java b/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepository.java new file mode 100644 index 000000000..0e5a545b8 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepository.java @@ -0,0 +1,80 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.util.Collection; +import java.util.List; +import java.util.Optional; + +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.Query; +import org.springframework.data.repository.Repository; +import org.springframework.data.repository.query.Param; + +import org.eclipse.openvsx.entities.NameSimilarityAllow; +import org.eclipse.openvsx.entities.NameSimilarityField; + +public interface NameSimilarityAllowRepository extends Repository { + + /** The allow for the pair of extensions, whichever way round it was stored. */ + @Query(""" + SELECT a FROM NameSimilarityAllow a + WHERE (a.extensionId = :first AND a.otherExtensionId = :second) + OR (a.extensionId = :second AND a.otherExtensionId = :first) + """) + Optional findPair(@Param("first") long first, @Param("second") long second); + + /** Every allow of extensions that has one of the given extensions on either side. */ + @Query(""" + SELECT a FROM NameSimilarityAllow a + WHERE a.extensionId IN :extensionIds OR a.otherExtensionId IN :extensionIds + """) + List findInvolving(@Param("extensionIds") Collection extensionIds); + + /** The extensions that were allowed as look-alikes, the most recently allowed first. */ + @Query(""" + SELECT a.extensionId FROM NameSimilarityAllow a + WHERE a.extensionId IS NOT NULL + GROUP BY a.extensionId + ORDER BY MAX(a.decidedAt) DESC, a.extensionId + """) + List findAllowedExtensionIds(Pageable pageable); + + /** The allow for the pair of namespaces, whichever way round it was stored. */ + @Query(""" + SELECT a FROM NameSimilarityAllow a + WHERE (a.namespaceId = :first AND a.otherNamespaceId = :second) + OR (a.namespaceId = :second AND a.otherNamespaceId = :first) + """) + Optional findNamespacePair(@Param("first") long first, @Param("second") long second); + + /** + * A page of the allows of the field, the most recently allowed first; the id breaks ties so pages + * neither repeat nor skip an allow. + */ + List findByFieldOrderByDecidedAtDescIdDesc(NameSimilarityField field, Pageable pageable); + + /** + * Every allow of the field, in no particular order. Meant for {@link NameSimilarityField#NAMESPACE}, + * whose allows the dashboard filters every namespace pair against. + */ + List findByField(NameSimilarityField field); + + List findByExtensionIdInOrderByDecidedAtDesc(Collection extensionIds); + + Optional findById(long id); + + NameSimilarityAllow save(NameSimilarityAllow allow); + + void delete(NameSimilarityAllow allow); +} diff --git a/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepository.java b/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepository.java new file mode 100644 index 000000000..aa0a2c2fd --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepository.java @@ -0,0 +1,606 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Locale; +import java.util.function.Supplier; + +import jakarta.transaction.Transactional; +import org.jooq.Condition; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.ResultQuery; +import org.jooq.impl.DSL; +import org.jooq.impl.SQLDataType; +import org.jspecify.annotations.Nullable; +import org.springframework.stereotype.Component; + +import org.eclipse.openvsx.entities.NameSimilarityField; + +import static org.eclipse.openvsx.jooq.Tables.EXTENSION; +import static org.eclipse.openvsx.jooq.Tables.EXTENSION_SCAN; +import static org.eclipse.openvsx.jooq.Tables.EXTENSION_VALIDATION_FAILURE; +import static org.eclipse.openvsx.jooq.Tables.EXTENSION_VERSION; +import static org.eclipse.openvsx.jooq.Tables.NAMESPACE; + +/** + * Trigram lookups of the active extensions whose name or display name matches or resembles a given + * one, for the NAME_SIMILARITY publish check and the name squatting admin dashboard. + *

+ * Results come back in no particular order: ordering by similarity in SQL makes the planner give up + * the trigram indexes, so callers sort what they get. Each lookup sets a statement timeout local to its + * transaction; a cancelled statement aborts that transaction, so callers should not hold one open. + */ +@Component +public class NameSimilarityJooqRepository { + + /** + * Every Unicode space separator, trimmed from both ends of a display name. Must stay identical to the + * expression of extension_version_display_name_trgm_idx (V1_87), or the lookups scan every version. + */ + static final String DISPLAY_NAME_TRIM_CHARS = " \u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000"; + + /** {@link #DISPLAY_NAME_TRIM_CHARS} as the Unicode escape string literal V1_87 spells out. */ + static final String DISPLAY_NAME_TRIM_LITERAL = toUnicodeEscapeLiteral(DISPLAY_NAME_TRIM_CHARS); + + private final DSLContext dsl; + + public NameSimilarityJooqRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * What to look for: the names of one extension, which need not exist yet. Extensions in the same + * namespace never match. A normalized value shorter than {@code minFuzzyLength} only matches exactly, + * as trigram scores of very short strings say little. + */ + public record Probe( + String namespaceName, + String extensionName, + Collection displayNames, + float nameThreshold, + float displayNameThreshold, + int minFuzzyLength, + int limit, + Duration statementTimeout + ) { + public Probe { + requireThreshold(nameThreshold); + requireThreshold(displayNameThreshold); + if (limit < 1) { + throw new IllegalArgumentException("limit must be positive: " + limit); + } + requireTimeout(statementTimeout); + } + + private static void requireThreshold(float threshold) { + if (!(threshold > 0 && threshold <= 1)) { + throw new IllegalArgumentException("similarity threshold must be in (0, 1]: " + threshold); + } + } + } + + /** + * One active extension that matched a probe on one field. + * + * @param value the matched extension's value of {@code field}, as published + * @param probeValue the probed value it matched + * @param similarity trigram similarity of the normalized values, from 0 to 1 + * @param exact whether the normalized values are equal, which a similarity of 1 does + * not imply: trigrams are a set, so repeating a word does not change them + * @param namespaceSimilarity trigram similarity of the two namespace names + */ + public record Match( + long extensionId, + String namespaceName, + String extensionName, + NameSimilarityField field, + String value, + String probeValue, + float similarity, + boolean exact, + float namespaceSimilarity, + LocalDateTime publishedDate, + int downloadCount + ) {} + + /** + * Find the active extensions outside the probe's namespace that match it, up to {@code limit} per + * field and display name. Which matches are cut off beyond the limit is unspecified. + *

+ * Transactional because the similarity threshold and the timeout are settings local to the transaction. + */ + @Transactional + public List findSimilar(Probe probe) { + var displayNames = new LinkedHashSet(); + for (var displayName : probe.displayNames()) { + if (displayName != null && !displayName.isBlank()) { + displayNames.add(displayName); + } + } + + return withStatementTimeout(dsl, probe.statementTimeout(), () -> { + applyThreshold(dsl, probe); + var matches = new ArrayList(); + if (!probe.extensionName().isBlank()) { + matches.addAll( + namesQuery(dsl, probe) + .fetch(record -> toMatch(record, NameSimilarityField.NAME, probe.extensionName()))); + } + for (var displayName : displayNames) { + matches.addAll( + displayNamesQuery(dsl, probe, displayName) + .fetch(record -> toMatch(record, NameSimilarityField.DISPLAY_NAME, displayName))); + } + return matches; + }); + } + + /** The % operator compares against this setting. */ + static void applyThreshold(DSLContext tx, Probe probe) { + setLocal( + tx, + "pg_trgm.similarity_threshold", + Float.toString(Math.min(probe.nameThreshold(), probe.displayNameThreshold()))); + } + + // The column layout of namesQuery and displayNamesQuery is the same, and toMatch relies on it. + // + // Both filter through the trigram index in a MATERIALIZED step first. Inlined, the GROUP BY and LIMIT + // around it lead the planner to walk the table in key order hoping to stop early, testing every row. + + static ResultQuery namesQuery(DSLContext tx, Probe probe) { + var probed = DSL.lower(DSL.val(probe.extensionName())); + var lowerName = DSL.lower(EXTENSION.NAME); + var exactOnly = probe.extensionName().length() < probe.minFuzzyLength(); + + var hit = DSL.name("name_hit").fields("extension_id", "normalized").asMaterialized( + DSL.select(EXTENSION.ID, lowerName) + .from(EXTENSION) + .where(EXTENSION.ACTIVE.isTrue()) + .and(exactOnly ? lowerName.eq(probed) : trigramMatch(lowerName, probed))); + var hitId = hit.field("extension_id", Long.class); + var hitNormalized = hit.field("normalized", String.class); + var similarity = similarity(hitNormalized, probed); + + return tx.with(hit) + .select( + EXTENSION.ID, + NAMESPACE.NAME, + EXTENSION.NAME, + EXTENSION.NAME.as("matched_value"), + similarity, + DSL.field(hitNormalized.eq(probed)), + namespaceSimilarity(probe), + EXTENSION.PUBLISHED_DATE, + EXTENSION.DOWNLOAD_COUNT) + .from(hit) + .join(EXTENSION).on(EXTENSION.ID.eq(hitId)) + .join(NAMESPACE).on(NAMESPACE.ID.eq(EXTENSION.NAMESPACE_ID)) + .where(exactOnly ? DSL.noCondition() : similarity.ge(probe.nameThreshold())) + .and(DSL.lower(NAMESPACE.NAME).ne(DSL.lower(DSL.val(probe.namespaceName())))) + .limit(probe.limit()); + } + + static ResultQuery displayNamesQuery(DSLContext tx, Probe probe, String displayName) { + var probed = normalizedDisplayName(DSL.val(displayName)); + var candidate = normalizedDisplayName(EXTENSION_VERSION.DISPLAY_NAME); + var exactOnly = normalizeDisplayName(displayName).length() < probe.minFuzzyLength(); + + var hit = DSL.name("display_name_hit").fields("extension_id", "display_name", "normalized").asMaterialized( + DSL.select(EXTENSION_VERSION.EXTENSION_ID, EXTENSION_VERSION.DISPLAY_NAME, candidate) + .from(EXTENSION_VERSION) + .where(EXTENSION_VERSION.ACTIVE.isTrue()) + .and(exactOnly ? candidate.eq(probed) : trigramMatch(candidate, probed))); + var hitId = hit.field("extension_id", Long.class); + var hitDisplayName = hit.field("display_name", String.class); + var hitNormalized = hit.field("normalized", String.class); + var similarity = similarity(hitNormalized, probed); + + // Versions of one extension share their display name, so they collapse to one row per value. + return tx.with(hit) + .select( + EXTENSION.ID, + NAMESPACE.NAME, + EXTENSION.NAME, + DSL.min(hitDisplayName).as("matched_value"), + similarity, + DSL.field(hitNormalized.eq(probed)), + namespaceSimilarity(probe), + EXTENSION.PUBLISHED_DATE, + EXTENSION.DOWNLOAD_COUNT) + .from(hit) + .join(EXTENSION).on(EXTENSION.ID.eq(hitId)) + .join(NAMESPACE).on(NAMESPACE.ID.eq(EXTENSION.NAMESPACE_ID)) + .where(EXTENSION.ACTIVE.isTrue()) + .and(exactOnly ? DSL.noCondition() : similarity.ge(probe.displayNameThreshold())) + .and(DSL.lower(NAMESPACE.NAME).ne(DSL.lower(DSL.val(probe.namespaceName())))) + .groupBy( + EXTENSION.ID, + NAMESPACE.NAME, + EXTENSION.NAME, + hitNormalized, + EXTENSION.PUBLISHED_DATE, + EXTENSION.DOWNLOAD_COUNT) + .limit(probe.limit()); + } + + private static Field namespaceSimilarity(Probe probe) { + return similarity(DSL.lower(NAMESPACE.NAME), DSL.lower(DSL.val(probe.namespaceName()))); + } + + /** + * An active extension worth looking up again. + * + * @param flaggedAt when a check last flagged one of its versions, {@code null} for an extension that + * only shares a display name with another namespace's + */ + public record Candidate(long extensionId, @Nullable LocalDateTime flaggedAt) {} + + /** The first step of the walk over flagged extensions reads this many failures, each later one twice as many. */ + static final int WALK_FIRST_CHUNK = 1024; + + /** Steps the walk takes before it gives up and looks every flagged extension up in one go. */ + static final int WALK_MAX_STEPS = 4; + + /** + * The active extensions a publish check of type {@code checkType} flagged, most recently flagged + * first, followed by the others whose display name another namespace's active extension shares. + * Flagged extensions flagged at the same instant follow the scan that flagged them last, newest first. + *

+ * The second kind costs a pass over every active version, so it is only looked for once a page + * reaches past the flagged ones. + */ + @Transactional + public List findCandidates(String checkType, int offset, int limit, Duration statementTimeout) { + return findCandidates(checkType, offset, limit, statementTimeout, WALK_FIRST_CHUNK, WALK_MAX_STEPS); + } + + @Transactional + List findCandidates( + String checkType, + int offset, + int limit, + Duration statementTimeout, + int firstChunk, + int maxSteps + ) { + requireTimeout(statementTimeout); + var needed = (int) Math.min(Integer.MAX_VALUE, (long) offset + limit); + return withStatementTimeout(dsl, statementTimeout, () -> { + var flagged = walkFlagged(checkType, needed, firstChunk, maxSteps); + if (flagged == null) { + flagged = allFlaggedQuery(dsl, checkType).fetch(this::toCandidate); + } + if (flagged.size() >= needed) { + return List.copyOf(flagged.subList(offset, needed)); + } + + // Short of the page, the flagged list is complete, so it is also what the shared ones exclude. + var candidates = new ArrayList<>(flagged.subList(Math.min(offset, flagged.size()), flagged.size())); + var flaggedIds = flagged.stream().map(Candidate::extensionId).toList(); + var sharedOffset = Math.max(0, offset - flagged.size()); + candidates.addAll( + sharedDisplayNameQuery(dsl, flaggedIds, sharedOffset, limit - candidates.size()) + .fetch(record -> new Candidate(record.get(0, Long.class), null))); + return candidates; + }); + } + + /** + * Walk the check type's failures newest first, a growing chunk at a time, until {@code needed} + * flagged extensions are found or the failures run out, in which case the list holds all of them. + * + * @return {@code null} when {@code maxSteps} chunks were not enough + */ + private @Nullable List walkFlagged(String checkType, int needed, int firstChunk, int maxSteps) { + var flagged = new LinkedHashMap(); + LocalDateTime beforeAt = null; + Long beforeScanId = null; + var chunk = firstChunk; + for (var step = 0; step < maxSteps; step++) { + var scans = flaggedStepQuery(dsl, checkType, beforeAt, beforeScanId, chunk).fetch(); + if (scans.isEmpty()) { + return List.copyOf(flagged.values()); + } + for (var scan : scans) { + beforeAt = scan.get(0, LocalDateTime.class); + beforeScanId = scan.get(1, Long.class); + var extensionId = scan.get(2, Long.class); + if (extensionId != null) { + flagged.putIfAbsent(extensionId, new Candidate(extensionId, beforeAt)); + } + } + if (flagged.size() >= needed) { + return List.copyOf(flagged.values()); + } + chunk = (int) Math.min(Integer.MAX_VALUE, chunk * 2L); + } + return null; + } + + /** + * The scans behind the next {@code chunk} failures of the check type older than the given position, + * newest first, each with the active extension it was for, or {@code null} when there is none: every + * scan comes back, as the last one is where the next step resumes. + *

+ * The chunk is read off extension_validation_failure_type_detected_idx (V1_87) and deduped by scan + * before the joins, as one scan records a failure per extension it matched. + */ + static ResultQuery flaggedStepQuery( + DSLContext tx, + String checkType, + @Nullable LocalDateTime beforeAt, + @Nullable Long beforeScanId, + int chunk + ) { + var failure = EXTENSION_VALIDATION_FAILURE; + var resume = beforeAt == null || beforeScanId == null + ? DSL.noCondition() + : DSL.row(failure.DETECTED_AT, failure.SCAN_ID).lt(beforeAt, beforeScanId); + var failures = DSL.name("failures").fields("detected_at", "scan_id").asMaterialized( + DSL.select(failure.DETECTED_AT, failure.SCAN_ID) + .from(failure) + .where(failure.VALIDATION_TYPE.eq(checkType)) + .and(resume) + .orderBy(failure.DETECTED_AT.desc(), failure.SCAN_ID.desc()) + .limit(chunk)); + var scans = DSL.name("scans").fields("detected_at", "scan_id").as( + DSL.selectDistinct(failures.field("detected_at"), failures.field("scan_id")).from(failures)); + var detectedAt = scans.field("detected_at", LocalDateTime.class); + var scanId = scans.field("scan_id", Long.class); + + return tx.with(failures) + .with(scans) + .select(detectedAt, scanId, EXTENSION.ID) + .from(scans) + .join(EXTENSION_SCAN).on(EXTENSION_SCAN.ID.eq(scanId)) + .leftJoin(NAMESPACE).on(namespaceOfScan()) + .leftJoin(EXTENSION).on(extensionOfScan()) + .orderBy(detectedAt.desc(), scanId.desc()); + } + + /** + * Every active extension the check type flagged, in the order {@link #walkFlagged} finds them: by the + * scan that flagged each last, newest first. + */ + static ResultQuery allFlaggedQuery(DSLContext tx, String checkType) { + var failure = EXTENSION_VALIDATION_FAILURE; + var scans = DSL.name("scans").fields("detected_at", "scan_id").as( + DSL.selectDistinct(failure.DETECTED_AT, failure.SCAN_ID) + .from(failure) + .where(failure.VALIDATION_TYPE.eq(checkType))); + var detectedAt = scans.field("detected_at", LocalDateTime.class); + var scanId = scans.field("scan_id", Long.class); + + var latest = DSL.name("latest").fields("extension_id", "detected_at", "scan_id").as( + DSL.selectDistinct(EXTENSION.ID, detectedAt, scanId) + .on(EXTENSION.ID) + .from(scans) + .join(EXTENSION_SCAN).on(EXTENSION_SCAN.ID.eq(scanId)) + .join(NAMESPACE).on(namespaceOfScan()) + .join(EXTENSION).on(extensionOfScan()) + .orderBy(EXTENSION.ID, detectedAt.desc(), scanId.desc())); + var latestAt = latest.field("detected_at", LocalDateTime.class); + return tx.with(scans) + .with(latest) + .select(latest.field("extension_id", Long.class), latestAt) + .from(latest) + .orderBy(latestAt.desc(), latest.field("scan_id", Long.class).desc()); + } + + // Scans keep the names as published; upper() is what the unique indexes on both tables are built on. + + private static Condition namespaceOfScan() { + return DSL.upper(NAMESPACE.NAME).eq(DSL.upper(EXTENSION_SCAN.NAMESPACE_NAME)); + } + + private static Condition extensionOfScan() { + return EXTENSION.NAMESPACE_ID.eq(NAMESPACE.ID) + .and(DSL.upper(EXTENSION.NAME).eq(DSL.upper(EXTENSION_SCAN.EXTENSION_NAME))) + .and(EXTENSION.ACTIVE.isTrue()); + } + + /** + * The active extensions outside {@code excludedIds} whose display name another namespace's active + * extension shares once normalized, by id. One pass over the active versions normalizes each name + * once and dedupes it per extension before grouping. + */ + static ResultQuery sharedDisplayNameQuery( + DSLContext tx, + Collection excludedIds, + int offset, + int limit + ) { + var names = DSL.name("names").fields("extension_id", "namespace_id", "normalized").as( + DSL.selectDistinct( + EXTENSION_VERSION.EXTENSION_ID, + EXTENSION.NAMESPACE_ID, + normalizedDisplayName(EXTENSION_VERSION.DISPLAY_NAME)) + .from(EXTENSION_VERSION) + .join(EXTENSION).on(EXTENSION.ID.eq(EXTENSION_VERSION.EXTENSION_ID)) + .where(EXTENSION_VERSION.ACTIVE.isTrue()) + .and(EXTENSION.ACTIVE.isTrue()) + .and(EXTENSION_VERSION.DISPLAY_NAME.isNotNull())); + var namesExtensionId = names.field("extension_id", Long.class); + var namesNamespaceId = names.field("namespace_id", Long.class); + var namesNormalized = names.field("normalized", String.class); + + var shared = DSL.name("shared").fields("normalized").as( + DSL.select(namesNormalized) + .from(names) + .where(namesNormalized.ne("")) + .groupBy(namesNormalized) + .having(DSL.countDistinct(namesNamespaceId).gt(1))); + var sharedNormalized = shared.field("normalized", String.class); + + // One array parameter rather than a bind per id, and NOT IN over a subquery hashes it once, where + // <> ALL would compare every row against every element. + var excluded = DSL.select( + DSL.field( + "unnest({0})", + Long.class, + DSL.val(excludedIds.toArray(Long[]::new), SQLDataType.BIGINT.array()))); + return tx.with(names) + .with(shared) + .selectDistinct(namesExtensionId) + .from(names) + .join(shared).on(sharedNormalized.eq(namesNormalized)) + .where(namesExtensionId.notIn(excluded)) + .orderBy(namesExtensionId) + .offset(offset) + .limit(limit); + } + + private Candidate toCandidate(Record record) { + return new Candidate(record.get(0, Long.class), record.get(1, LocalDateTime.class)); + } + + /** + * The names of an extension. + * + * @param displayNames the distinct display names of its active versions + */ + public record ExtensionNames( + long id, + String namespaceName, + String name, + boolean active, + @Nullable LocalDateTime publishedDate, + int downloadCount, + int activeVersionCount, + List displayNames + ) {} + + /** The names of the given extensions, active or not, in no particular order. */ + public List findNames(Collection extensionIds) { + if (extensionIds.isEmpty()) { + return List.of(); + } + + var activeVersions = DSL.count(EXTENSION_VERSION.ID).filterWhere(EXTENSION_VERSION.ACTIVE.isTrue()); + var displayNames = DSL.arrayAggDistinct(EXTENSION_VERSION.DISPLAY_NAME) + .filterWhere(EXTENSION_VERSION.ACTIVE.isTrue().and(EXTENSION_VERSION.DISPLAY_NAME.isNotNull())); + return dsl.select( + EXTENSION.ID, + NAMESPACE.NAME, + EXTENSION.NAME, + EXTENSION.ACTIVE, + EXTENSION.PUBLISHED_DATE, + EXTENSION.DOWNLOAD_COUNT, + activeVersions, + displayNames) + .from(EXTENSION) + .join(NAMESPACE).on(NAMESPACE.ID.eq(EXTENSION.NAMESPACE_ID)) + .leftJoin(EXTENSION_VERSION).on(EXTENSION_VERSION.EXTENSION_ID.eq(EXTENSION.ID)) + .where(EXTENSION.ID.in(extensionIds)) + .groupBy( + EXTENSION.ID, + NAMESPACE.NAME, + EXTENSION.NAME, + EXTENSION.ACTIVE, + EXTENSION.PUBLISHED_DATE, + EXTENSION.DOWNLOAD_COUNT) + .fetch(record -> { + var names = record.get(displayNames); + return new ExtensionNames( + record.get(EXTENSION.ID), + record.get(NAMESPACE.NAME), + record.get(EXTENSION.NAME), + record.get(EXTENSION.ACTIVE), + record.get(EXTENSION.PUBLISHED_DATE), + record.get(EXTENSION.DOWNLOAD_COUNT), + record.get(activeVersions), + names == null ? List.of() : List.of(names)); + }); + } + + /** + * Run {@code work} with the statement timeout set, then put the previous one back, so the timeout does + * not outlive the lookup in a caller's transaction. A cancelled statement aborts the transaction, and + * the setting goes with it. + */ + static T withStatementTimeout(DSLContext dsl, Duration timeout, Supplier work) { + var previous = dsl.select(DSL.function("current_setting", String.class, DSL.inline("statement_timeout"))) + .fetchOne(0, String.class); + setLocal(dsl, "statement_timeout", timeout.toMillis() + "ms"); + var result = work.get(); + setLocal(dsl, "statement_timeout", previous); + return result; + } + + static void setLocal(DSLContext tx, String setting, String value) { + tx.select(DSL.function("set_config", String.class, DSL.inline(setting), DSL.val(value), DSL.inline(true))) + .fetch(); + } + + static void requireTimeout(Duration timeout) { + if (timeout.isNegative() || timeout.isZero()) { + throw new IllegalArgumentException("statement timeout must be positive: " + timeout); + } + } + + static Field normalizedDisplayName(Field displayName) { + return DSL.field("lower(btrim({0}, " + DISPLAY_NAME_TRIM_LITERAL + "))", String.class, displayName); + } + + /** The Java side of {@link #normalizedDisplayName(Field)}, apart from casing. */ + public static String normalizeDisplayName(String displayName) { + int start = 0; + int end = displayName.length(); + while (start < end && DISPLAY_NAME_TRIM_CHARS.indexOf(displayName.charAt(start)) >= 0) { + start++; + } + while (end > start && DISPLAY_NAME_TRIM_CHARS.indexOf(displayName.charAt(end - 1)) >= 0) { + end--; + } + return displayName.substring(start, end).toLowerCase(Locale.ROOT); + } + + private static String toUnicodeEscapeLiteral(String chars) { + var literal = new StringBuilder("U&'"); + chars.chars().forEach(c -> literal.append(c < 0x80 ? String.valueOf((char) c) : String.format("\\%04X", c))); + return literal.append('\'').toString(); + } + + static Field similarity(Field first, Field second) { + return DSL.function("similarity", Float.class, first, second); + } + + static Condition trigramMatch(Field indexed, Field probed) { + return DSL.condition("{0} % {1}", indexed, probed); + } + + private static Match toMatch(Record record, NameSimilarityField field, String probeValue) { + return new Match( + record.get(EXTENSION.ID), + record.get(NAMESPACE.NAME), + record.get(EXTENSION.NAME), + field, + record.get(3, String.class), + probeValue, + record.get(4, Float.class), + record.get(5, Boolean.class), + record.get(6, Float.class), + record.get(EXTENSION.PUBLISHED_DATE), + record.get(EXTENSION.DOWNLOAD_COUNT)); + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepository.java b/server/src/main/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepository.java new file mode 100644 index 000000000..7961b8e95 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepository.java @@ -0,0 +1,289 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; + +import jakarta.transaction.Transactional; +import org.jooq.DSLContext; +import org.jooq.Field; +import org.jooq.Record; +import org.jooq.ResultQuery; +import org.jooq.impl.DSL; +import org.jspecify.annotations.Nullable; +import org.springframework.stereotype.Component; + +import static org.eclipse.openvsx.jooq.Tables.EXTENSION; +import static org.eclipse.openvsx.jooq.Tables.NAMESPACE; +import static org.eclipse.openvsx.jooq.Tables.NAMESPACE_MEMBERSHIP; +import static org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.requireTimeout; +import static org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.setLocal; +import static org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.similarity; +import static org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.trigramMatch; +import static org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.withStatementTimeout; + +/** + * Pairs of namespaces whose names resemble each other, for the name squatting admin dashboard. + *

+ * Names are compared ignoring case. A pair matches when the names are within an edit distance that + * grows with the longer name (see {@link #allowedEdits(int)}), or when they only differ in characters + * other than letters and digits, such as {@code my-tools} and {@code my_tools}. + */ +@Component +public class NamespaceSimilarityJooqRepository { + + /** + * Trigram similarity a pair needs before its edit distance is computed, low enough to lose no pair + * within the allowed edits: it only spares the edit distance of every pair of namespaces. + */ + static final float PREFILTER_THRESHOLD = 0.3f; + + /** Names up to this long only match by {@link #separatorOnly}: one edit is too much of them. */ + static final int EXACT_MAX_LENGTH = 4; + + /** Names up to this long match within one edit, longer ones within {@link #MAX_EDITS}. */ + static final int ONE_EDIT_MAX_LENGTH = 8; + + static final int MAX_EDITS = 2; + + private final DSLContext dsl; + + public NamespaceSimilarityJooqRepository(DSLContext dsl) { + this.dsl = dsl; + } + + /** + * One namespace of a pair. + * + * @param downloads the downloads of its active extensions + * @param activeExtensions how many active extensions it has + * @param firstPublished when the earliest of its active extensions was published, {@code null} + * without any + */ + public record Side( + long id, + String name, + long downloads, + int activeExtensions, + @Nullable LocalDateTime firstPublished + ) {} + + /** + * Two namespaces whose names resemble each other, {@code first} having the lower id. + * + * @param editDistance Levenshtein distance of the lowercased names + * @param similarity trigram similarity of the lowercased names, from 0 to 1 + * @param separatorOnly whether the names only differ in characters other than letters and digits + * @param sharedMember whether a user is a member of both namespaces + */ + public record Pair( + Side first, + Side second, + int editDistance, + float similarity, + boolean separatorOnly, + boolean sharedMember + ) {} + + /** The edits allowed between two names, the longer of which has {@code length} characters. */ + public static int allowedEdits(int length) { + if (length <= EXACT_MAX_LENGTH) { + return 0; + } + return length <= ONE_EDIT_MAX_LENGTH ? 1 : MAX_EDITS; + } + + /** + * Every pair of namespaces whose names resemble each other, ordered by id, leaving out pairs where + * neither namespace has an active extension. Pairs an admin allowed are included: callers filter them. + *

+ * It probes the trigram index once per namespace, so it takes time in proportion to their number. + * Transactional because the trigram threshold and the timeout are settings local to the transaction. + */ + @Transactional + public List findSimilarPairs(Duration statementTimeout) { + requireTimeout(statementTimeout); + return withStatementTimeout(dsl, statementTimeout, () -> { + applyThreshold(dsl); + return pairsQuery(dsl).fetch(NamespaceSimilarityJooqRepository::toPair); + }); + } + + /** + * How two namespace names compare, by the measures of {@link Pair}. + * + * @param editDistance Levenshtein distance of the lowercased names + * @param similarity trigram similarity of the lowercased names, from 0 to 1 + * @param separatorOnly whether the names only differ in characters other than letters and digits + * @param resembles whether {@link #findSimilarPairs} reports them, as far as their names go: it also + * needs an active extension on either side + */ + public record Comparison(int editDistance, float similarity, boolean separatorOnly, boolean resembles) {} + + /** + * Compare two namespace names the way {@link #findSimilarPairs} does, in a single query that reads no + * table, so the namespaces need not exist. The allowed edits follow the longer name's length. + */ + public Comparison compare(String first, String second) { + var firstName = DSL.lower(DSL.val(first)); + var secondName = DSL.lower(DSL.val(second)); + var record = dsl.select( + DSL.function("levenshtein", Integer.class, firstName, secondName), + similarity(firstName, secondName), + DSL.field(stripped(firstName).eq(stripped(secondName)))) + .fetchSingle(); + int editDistance = record.value1(); + float similarity = record.value2(); + boolean separatorOnly = record.value3(); + var resembles = separatorOnly || similarity >= PREFILTER_THRESHOLD + && editDistance <= allowedEdits(Math.max(first.length(), second.length())); + return new Comparison(editDistance, similarity, separatorOnly, resembles); + } + + /** The % operator compares against this setting. */ + static void applyThreshold(DSLContext tx) { + setLocal(tx, "pg_trgm.similarity_threshold", Float.toString(PREFILTER_THRESHOLD)); + } + + static ResultQuery pairsQuery(DSLContext tx) { + // Materialized so each namespace is lowercased once and the probe below runs once per namespace. + var names = DSL.name("names").fields("id", "normalized", "stripped").asMaterialized( + DSL.select(NAMESPACE.ID, DSL.lower(NAMESPACE.NAME), stripped(DSL.lower(NAMESPACE.NAME))) + .from(NAMESPACE)); + + var probe = names.as("probe"); + var probeId = probe.field("id", Long.class); + var probeNormalized = probe.field("normalized", String.class); + var hit = NAMESPACE.as("hit"); + var hitNormalized = DSL.lower(hit.NAME); + var longer = DSL.greatest(DSL.length(probeNormalized), DSL.length(hitNormalized)); + var editsAllowed = DSL.when(longer.le(EXACT_MAX_LENGTH), DSL.inline(0)) + .when(longer.le(ONE_EDIT_MAX_LENGTH), DSL.inline(1)) + .otherwise(DSL.inline(MAX_EDITS)); + // Each pair turns up from both sides, and the union dedupes it: hit.id > probe.id would offer the + // planner a primary key range scan in place of the trigram probe. + var withinEdits = DSL.select(DSL.least(probeId, hit.ID), DSL.greatest(probeId, hit.ID)) + .from(probe) + .join(hit).on(trigramMatch(hitNormalized, probeNormalized)).and(hit.ID.ne(probeId)) + .where(levenshteinLessEqual(probeNormalized, hitNormalized, MAX_EDITS).le(editsAllowed)); + + var left = names.as("left_name"); + var right = names.as("right_name"); + var leftId = left.field("id", Long.class); + var leftStripped = left.field("stripped", String.class); + var rightId = right.field("id", Long.class); + var separatorsOnly = DSL.select(leftId, rightId) + .from(left) + .join(right).on(right.field("stripped", String.class).eq(leftStripped)).and(rightId.gt(leftId)) + .where(leftStripped.ne("")); + + var pairs = DSL.name("pairs").fields("first_id", "second_id").as(withinEdits.union(separatorsOnly)); + var firstId = pairs.field("first_id", Long.class); + var secondId = pairs.field("second_id", Long.class); + + var stats = DSL.name("stats").fields("namespace_id", "downloads", "extensions", "first_published").as( + DSL.select( + EXTENSION.NAMESPACE_ID, + DSL.sum(EXTENSION.DOWNLOAD_COUNT), + DSL.count(), + DSL.min(EXTENSION.PUBLISHED_DATE)) + .from(EXTENSION) + .where(EXTENSION.ACTIVE.isTrue()) + .and( + EXTENSION.NAMESPACE_ID.in( + DSL.select(firstId).from(pairs).union(DSL.select(secondId).from(pairs)))) + .groupBy(EXTENSION.NAMESPACE_ID)); + var firstStats = stats.as("first_stats"); + var secondStats = stats.as("second_stats"); + + var first = NAMESPACE.as("first"); + var second = NAMESPACE.as("second"); + var firstName = DSL.lower(first.NAME); + var secondName = DSL.lower(second.NAME); + + var firstMember = NAMESPACE_MEMBERSHIP.as("first_member"); + var secondMember = NAMESPACE_MEMBERSHIP.as("second_member"); + var sharedMember = DSL.exists( + DSL.selectOne() + .from(firstMember) + .join(secondMember).on(secondMember.USER_DATA.eq(firstMember.USER_DATA)) + .where(firstMember.NAMESPACE.eq(firstId)) + .and(secondMember.NAMESPACE.eq(secondId))); + + return tx.with(names) + .with(pairs) + .with(stats) + .select( + first.ID, + first.NAME, + firstStats.field("downloads"), + firstStats.field("extensions"), + firstStats.field("first_published"), + second.ID, + second.NAME, + secondStats.field("downloads"), + secondStats.field("extensions"), + secondStats.field("first_published"), + DSL.function("levenshtein", Integer.class, firstName, secondName), + similarity(firstName, secondName), + DSL.field(stripped(firstName).eq(stripped(secondName))), + DSL.field(sharedMember)) + .from(pairs) + .join(first).on(first.ID.eq(firstId)) + .join(second).on(second.ID.eq(secondId)) + .leftJoin(firstStats).on(firstStats.field("namespace_id", Long.class).eq(firstId)) + .leftJoin(secondStats).on(secondStats.field("namespace_id", Long.class).eq(secondId)) + .where( + firstStats.field("namespace_id").isNotNull() + .or(secondStats.field("namespace_id").isNotNull())) + .orderBy(firstId, secondId); + } + + /** Lowercased name without the characters other than letters and digits. */ + private static Field stripped(Field lowerName) { + return DSL.function( + "regexp_replace", + String.class, + lowerName, + DSL.inline("[^[:alnum:]]"), + DSL.inline(""), + DSL.inline("g")); + } + + private static Field levenshteinLessEqual(Field first, Field second, int max) { + return DSL.function("levenshtein_less_equal", Integer.class, first, second, DSL.inline(max)); + } + + private static Pair toPair(Record record) { + return new Pair( + toSide(record, 0), + toSide(record, 5), + record.get(10, Integer.class), + record.get(11, Float.class), + record.get(12, Boolean.class), + record.get(13, Boolean.class)); + } + + private static Side toSide(Record record, int offset) { + var downloads = record.get(offset + 2, Long.class); + var extensions = record.get(offset + 3, Integer.class); + return new Side( + record.get(offset, Long.class), + record.get(offset + 1, String.class), + downloads == null ? 0 : downloads, + extensions == null ? 0 : extensions, + record.get(offset + 4, LocalDateTime.class)); + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfig.java b/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfig.java new file mode 100644 index 000000000..67052bcc4 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfig.java @@ -0,0 +1,190 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.scanning; + +import java.time.Duration; + +import jakarta.annotation.PostConstruct; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + +/** + * Configuration of the NAME_SIMILARITY publish check, which flags a version whose extension name or + * display name matches or resembles another namespace's active extension, and of the name squatting + * admin dashboard that looks those flags up again. + *

+ * The check never blocks publication, whether it finds a match or fails: it only flags the version for + * an admin to review. Like every publish check it runs only while {@code ovsx.scanning.enabled} is set. + *

+ * Configuration example: + *

+ * ovsx:
+ *   scanning:
+ *     name-similarity:
+ *       enabled: true               # default: true
+ *       name-threshold: 0.7         # trigram similarity of extension names, default: 0.7
+ *       display-name-threshold: 0.7 # trigram similarity of display names, default: 0.7
+ *       min-fuzzy-length: 4         # shorter names only match exactly, default: 4
+ *       max-matches: 10             # matches looked up per field and name, default: 10
+ *       statement-timeout: 10s      # cancels a lookup that runs longer, default: 10s
+ *       popular-namespace-downloads: 10000 # see below, default: 10000
+ *       popular-namespace-ratio: 10        # see below, default: 10
+ * 
+ * The dashboard's namespaces view shows popular targets by default: pairs where the namespace with more + * downloads has at least {@code popular-namespace-downloads} of them, and {@code popular-namespace-ratio} + * times as many as the other. + */ +@Configuration +public class NameSimilarityCheckConfig { + + /** + * Property: {@code ovsx.scanning.name-similarity.enabled} + * Default: {@code true} + */ + @Value("${ovsx.scanning.name-similarity.enabled:true}") + private boolean enabled; + + /** + * Lowest trigram similarity, above 0 and at most 1, at which two extension names count as a match. + *

+ * Property: {@code ovsx.scanning.name-similarity.name-threshold} + * Default: {@code 0.7} + */ + @Value("${ovsx.scanning.name-similarity.name-threshold:0.7}") + private float nameThreshold; + + /** + * Lowest trigram similarity, above 0 and at most 1, at which two display names count as a match. + *

+ * Property: {@code ovsx.scanning.name-similarity.display-name-threshold} + * Default: {@code 0.7} + */ + @Value("${ovsx.scanning.name-similarity.display-name-threshold:0.7}") + private float displayNameThreshold; + + /** + * Names shorter than this, once normalized, only match exactly: trigram scores of very short strings + * say little. + *

+ * Property: {@code ovsx.scanning.name-similarity.min-fuzzy-length} + * Default: {@code 4} + */ + @Value("${ovsx.scanning.name-similarity.min-fuzzy-length:4}") + private int minFuzzyLength; + + /** + * Most matches looked up per field and name, which bounds the work a very generic name causes. + *

+ * Property: {@code ovsx.scanning.name-similarity.max-matches} + * Default: {@code 10} + */ + @Value("${ovsx.scanning.name-similarity.max-matches:10}") + private int maxMatches; + + /** + * How long one lookup may run before the database cancels it. A cancelled lookup fails the check, + * which does not block publication, or the dashboard page that asked for it. + *

+ * Property: {@code ovsx.scanning.name-similarity.statement-timeout} + * Default: {@code 10s} + */ + @Value("${ovsx.scanning.name-similarity.statement-timeout:10s}") + private Duration statementTimeout; + + /** + * Downloads of its active extensions from which the namespace of a pair counts as a popular target, so + * the dashboard's default namespaces view shows the pair. Must not be negative. + *

+ * Property: {@code ovsx.scanning.name-similarity.popular-namespace-downloads} + * Default: {@code 10000} + */ + @Value("${ovsx.scanning.name-similarity.popular-namespace-downloads:10000}") + private long popularNamespaceDownloads; + + /** + * How many times the other namespace's downloads a popular target needs, at least 1. It keeps out pairs + * of two established namespaces, which are rarely one squatting on the other. + *

+ * Property: {@code ovsx.scanning.name-similarity.popular-namespace-ratio} + * Default: {@code 10} + */ + @Value("${ovsx.scanning.name-similarity.popular-namespace-ratio:10}") + private double popularNamespaceRatio; + + @PostConstruct + void validate() { + requireThreshold("name-threshold", nameThreshold); + requireThreshold("display-name-threshold", displayNameThreshold); + if (minFuzzyLength < 1) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity.min-fuzzy-length must be at least 1: " + minFuzzyLength); + } + if (maxMatches < 1) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity.max-matches must be at least 1: " + maxMatches); + } + if (statementTimeout == null || statementTimeout.isNegative() || statementTimeout.isZero()) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity.statement-timeout must be positive: " + statementTimeout); + } + if (popularNamespaceDownloads < 0) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity.popular-namespace-downloads must not be negative: " + + popularNamespaceDownloads); + } + if (!(popularNamespaceRatio >= 1)) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity.popular-namespace-ratio must be at least 1: " + + popularNamespaceRatio); + } + } + + private static void requireThreshold(String property, float value) { + if (!(value > 0 && value <= 1)) { + throw new IllegalStateException( + "ovsx.scanning.name-similarity." + property + " must be above 0 and at most 1: " + value); + } + } + + public boolean isEnabled() { + return enabled; + } + + public float getNameThreshold() { + return nameThreshold; + } + + public float getDisplayNameThreshold() { + return displayNameThreshold; + } + + public int getMinFuzzyLength() { + return minFuzzyLength; + } + + public int getMaxMatches() { + return maxMatches; + } + + public Duration getStatementTimeout() { + return statementTimeout; + } + + public long getPopularNamespaceDownloads() { + return popularNamespaceDownloads; + } + + public double getPopularNamespaceRatio() { + return popularNamespaceRatio; + } +} diff --git a/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckService.java b/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckService.java new file mode 100644 index 000000000..77bcaa2e7 --- /dev/null +++ b/server/src/main/java/org/eclipse/openvsx/scanning/NameSimilarityCheckService.java @@ -0,0 +1,173 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.scanning; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.springframework.core.annotation.Order; +import org.springframework.stereotype.Service; + +import org.eclipse.openvsx.entities.NameSimilarityField; +import org.eclipse.openvsx.repositories.NameSimilarityAllowRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Match; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Probe; +import org.eclipse.openvsx.repositories.RepositoryService; + +/** + * Flags a version whose extension name or display name matches or resembles another namespace's active + * extension, for the name squatting admin dashboard to look up again. It never blocks publication: the + * flag is a validation failure that is not enforced, and an error is not required to pass. + */ +@Service +@Order(4) // After the checks that can block publication, so a rejected package is not looked up. +public class NameSimilarityCheckService implements PublishCheck { + + public static final String CHECK_TYPE = "NAME_SIMILARITY"; + + /** Exact matches first, then the most similar. */ + public static final Comparator CLOSEST_FIRST = Comparator.comparing(Match::exact) + .thenComparing(Match::similarity) + .reversed(); + + private static final int MAX_VALUE_LENGTH = 120; + + private final NameSimilarityCheckConfig config; + private final NameSimilarityJooqRepository similarity; + private final NameSimilarityAllowRepository allows; + private final RepositoryService repositories; + + public NameSimilarityCheckService( + NameSimilarityCheckConfig config, + NameSimilarityJooqRepository similarity, + NameSimilarityAllowRepository allows, + RepositoryService repositories + ) { + this.config = config; + this.similarity = similarity; + this.allows = allows; + this.repositories = repositories; + } + + @Override + public String getCheckType() { + return CHECK_TYPE; + } + + @Override + public boolean isEnabled() { + return config.isEnabled(); + } + + @Override + public boolean isEnforced() { + return false; + } + + @Override + public boolean isRequired() { + return false; + } + + /** How long one lookup may run before the database cancels it. */ + public java.time.Duration getStatementTimeout() { + return config.getStatementTimeout(); + } + + @Override + public Result check(Context context) { + var scan = context.scan(); + var namespaceName = scan.getNamespaceName(); + var extensionName = scan.getExtensionName(); + + // The scan falls back to the extension name for a package that declares no display name, and + // comparing that against other display names would report matches the package never claimed. + var displayName = scan.getExtensionDisplayName(); + var displayNames = displayName == null || displayName.equals(extensionName) + ? List.of() + : List.of(displayName); + + var matches = findMatches(namespaceName, extensionName, displayNames); + var existing = repositories.findExtension(extensionName, namespaceName); + if (existing != null) { + var allowed = allowedPartners(List.of(existing.getId())).getOrDefault(existing.getId(), Set.of()); + matches.removeIf(match -> allowed.contains(match.extensionId())); + } + + var closest = closestPerExtension(matches); + if (closest.isEmpty()) { + return Result.pass(); + } + return Result.fail(closest.stream().map(NameSimilarityCheckService::toFailure).toList()); + } + + /** Matches of the given names against other namespaces' active extensions, in no particular order. */ + public List findMatches(String namespaceName, String extensionName, Collection displayNames) { + var probe = new Probe( + namespaceName, + extensionName, + displayNames, + config.getNameThreshold(), + config.getDisplayNameThreshold(), + config.getMinFuzzyLength(), + config.getMaxMatches(), + config.getStatementTimeout()); + return new ArrayList<>(similarity.findSimilar(probe)); + } + + /** For each of the given extensions, the extensions it has been allowed alongside. */ + public Map> allowedPartners(Collection extensionIds) { + var partners = new HashMap>(); + for (var allow : allows.findInvolving(extensionIds)) { + partners.computeIfAbsent(allow.getExtensionId(), id -> new HashSet<>()).add(allow.getOtherExtensionId()); + partners.computeIfAbsent(allow.getOtherExtensionId(), id -> new HashSet<>()).add(allow.getExtensionId()); + } + return partners; + } + + /** The closest match with each extension, closest first. */ + public static List closestPerExtension(Collection matches) { + var closest = new LinkedHashMap(); + matches.stream() + .sorted(CLOSEST_FIRST) + .forEach(match -> closest.putIfAbsent(match.extensionId(), match)); + return List.copyOf(closest.values()); + } + + private static Failure toFailure(Match match) { + var field = match.field() == NameSimilarityField.NAME ? "Extension name" : "Display name"; + var other = match.namespaceName() + "." + match.extensionName(); + var reason = match.exact() + ? String.format("%s \"%s\" is also used by %s", field, shorten(match.probeValue()), other) + : String.format( + "%s \"%s\" resembles %s (\"%s\", %d%% similar)", + field, + shorten(match.probeValue()), + other, + shorten(match.value()), + Math.round(match.similarity() * 100)); + return new Failure(match.field().name(), reason); + } + + private static String shorten(String value) { + return value.length() <= MAX_VALUE_LENGTH ? value : value.substring(0, MAX_VALUE_LENGTH) + "..."; + } +} diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Indexes.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Indexes.java index 3ba89d2d2..93c35c4f2 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Indexes.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Indexes.java @@ -16,6 +16,7 @@ import org.eclipse.openvsx.jooq.tables.ExtensionVersionChange; import org.eclipse.openvsx.jooq.tables.FileDecision; import org.eclipse.openvsx.jooq.tables.FileResource; +import org.eclipse.openvsx.jooq.tables.NameSimilarityAllow; import org.eclipse.openvsx.jooq.tables.NamespaceMembership; import org.eclipse.openvsx.jooq.tables.PersistedLog; import org.eclipse.openvsx.jooq.tables.PublisherAgreementEvent; @@ -45,6 +46,7 @@ public class Indexes { public static final Index EXTENSION__NAMESPACE_ID__IDX = Internal.createIndex(DSL.name("extension__namespace_id__idx"), Extension.EXTENSION, new OrderField[] { Extension.EXTENSION.NAMESPACE_ID }, false); public static final Index EXTENSION_REVIEW__EXTENSION_ID__IDX = Internal.createIndex(DSL.name("extension_review__extension_id__idx"), ExtensionReview.EXTENSION_REVIEW, new OrderField[] { ExtensionReview.EXTENSION_REVIEW.EXTENSION_ID }, false); public static final Index EXTENSION_REVIEW__USER_ID__IDX = Internal.createIndex(DSL.name("extension_review__user_id__idx"), ExtensionReview.EXTENSION_REVIEW, new OrderField[] { ExtensionReview.EXTENSION_REVIEW.USER_ID }, false); + public static final Index EXTENSION_VALIDATION_FAILURE_TYPE_DETECTED_IDX = Internal.createIndex(DSL.name("extension_validation_failure_type_detected_idx"), ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE, new OrderField[] { ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.VALIDATION_TYPE, ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.DETECTED_AT.desc(), ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.SCAN_ID.desc() }, false); public static final Index EXTENSION_VERSION__EXTENSION_ID__IDX = Internal.createIndex(DSL.name("extension_version__extension_id__idx"), ExtensionVersion.EXTENSION_VERSION, new OrderField[] { ExtensionVersion.EXTENSION_VERSION.EXTENSION_ID }, false); public static final Index EXTENSION_VERSION__PUBLISHED_BY_ID__IDX = Internal.createIndex(DSL.name("extension_version__published_by_id__idx"), ExtensionVersion.EXTENSION_VERSION, new OrderField[] { ExtensionVersion.EXTENSION_VERSION.PUBLISHED_BY_ID }, false); public static final Index EXTENSION_VERSION__PUBLISHED_WITH_ID__IDX = Internal.createIndex(DSL.name("extension_version__published_with_id__idx"), ExtensionVersion.EXTENSION_VERSION, new OrderField[] { ExtensionVersion.EXTENSION_VERSION.PUBLISHED_WITH_ID }, false); @@ -78,6 +80,11 @@ public class Indexes { public static final Index IDX_VALIDATION_FAILURE_DETECTED_AT = Internal.createIndex(DSL.name("idx_validation_failure_detected_at"), ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE, new OrderField[] { ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.DETECTED_AT }, false); public static final Index IDX_VALIDATION_FAILURE_SCAN = Internal.createIndex(DSL.name("idx_validation_failure_scan"), ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE, new OrderField[] { ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.SCAN_ID }, false); public static final Index IDX_VALIDATION_FAILURE_VALIDATION_TYPE = Internal.createIndex(DSL.name("idx_validation_failure_validation_type"), ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE, new OrderField[] { ExtensionValidationFailure.EXTENSION_VALIDATION_FAILURE.VALIDATION_TYPE }, false); + public static final Index NAME_SIMILARITY_ALLOW_DECIDED_BY_IDX = Internal.createIndex(DSL.name("name_similarity_allow_decided_by_idx"), NameSimilarityAllow.NAME_SIMILARITY_ALLOW, new OrderField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.DECIDED_BY_ID }, false); + public static final Index NAME_SIMILARITY_ALLOW_EXTENSION_IDX = Internal.createIndex(DSL.name("name_similarity_allow_extension_idx"), NameSimilarityAllow.NAME_SIMILARITY_ALLOW, new OrderField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.EXTENSION_ID }, false); + public static final Index NAME_SIMILARITY_ALLOW_NAMESPACE_IDX = Internal.createIndex(DSL.name("name_similarity_allow_namespace_idx"), NameSimilarityAllow.NAME_SIMILARITY_ALLOW, new OrderField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.NAMESPACE_ID }, false); + public static final Index NAME_SIMILARITY_ALLOW_OTHER_EXTENSION_IDX = Internal.createIndex(DSL.name("name_similarity_allow_other_extension_idx"), NameSimilarityAllow.NAME_SIMILARITY_ALLOW, new OrderField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.OTHER_EXTENSION_ID }, false); + public static final Index NAME_SIMILARITY_ALLOW_OTHER_NAMESPACE_IDX = Internal.createIndex(DSL.name("name_similarity_allow_other_namespace_idx"), NameSimilarityAllow.NAME_SIMILARITY_ALLOW, new OrderField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.OTHER_NAMESPACE_ID }, false); public static final Index NAMESPACE_MEMBERSHIP__NAMESPACE__IDX = Internal.createIndex(DSL.name("namespace_membership__namespace__idx"), NamespaceMembership.NAMESPACE_MEMBERSHIP, new OrderField[] { NamespaceMembership.NAMESPACE_MEMBERSHIP.NAMESPACE }, false); public static final Index NAMESPACE_MEMBERSHIP__USER_DATA__IDX = Internal.createIndex(DSL.name("namespace_membership__user_data__idx"), NamespaceMembership.NAMESPACE_MEMBERSHIP, new OrderField[] { NamespaceMembership.NAMESPACE_MEMBERSHIP.USER_DATA }, false); public static final Index PERSISTED_LOG__USER_DATA__IDX = Internal.createIndex(DSL.name("persisted_log__user_data__idx"), PersistedLog.PERSISTED_LOG, new OrderField[] { PersistedLog.PERSISTED_LOG.USER_DATA }, false); diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Keys.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Keys.java index 1aff929d9..9ad2ef47e 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Keys.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Keys.java @@ -24,6 +24,7 @@ import org.eclipse.openvsx.jooq.tables.FileDecision; import org.eclipse.openvsx.jooq.tables.FileResource; import org.eclipse.openvsx.jooq.tables.MigrationItem; +import org.eclipse.openvsx.jooq.tables.NameSimilarityAllow; import org.eclipse.openvsx.jooq.tables.Namespace; import org.eclipse.openvsx.jooq.tables.NamespaceMembership; import org.eclipse.openvsx.jooq.tables.NamespaceSocialLinks; @@ -59,6 +60,7 @@ import org.eclipse.openvsx.jooq.tables.records.FileDecisionRecord; import org.eclipse.openvsx.jooq.tables.records.FileResourceRecord; import org.eclipse.openvsx.jooq.tables.records.MigrationItemRecord; +import org.eclipse.openvsx.jooq.tables.records.NameSimilarityAllowRecord; import org.eclipse.openvsx.jooq.tables.records.NamespaceMembershipRecord; import org.eclipse.openvsx.jooq.tables.records.NamespaceRecord; import org.eclipse.openvsx.jooq.tables.records.NamespaceSocialLinksRecord; @@ -110,6 +112,7 @@ public class Keys { public static final UniqueKey FILE_DECISION_PKEY = Internal.createUniqueKey(FileDecision.FILE_DECISION, DSL.name("file_decision_pkey"), new TableField[] { FileDecision.FILE_DECISION.ID }, true); public static final UniqueKey FILE_RESOURCE_PKEY = Internal.createUniqueKey(FileResource.FILE_RESOURCE, DSL.name("file_resource_pkey"), new TableField[] { FileResource.FILE_RESOURCE.ID }, true); public static final UniqueKey MIGRATION_ITEM_PKEY = Internal.createUniqueKey(MigrationItem.MIGRATION_ITEM, DSL.name("migration_item_pkey"), new TableField[] { MigrationItem.MIGRATION_ITEM.ID }, true); + public static final UniqueKey NAME_SIMILARITY_ALLOW_PKEY = Internal.createUniqueKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_pkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.ID }, true); public static final UniqueKey NAMESPACE_PKEY = Internal.createUniqueKey(Namespace.NAMESPACE, DSL.name("namespace_pkey"), new TableField[] { Namespace.NAMESPACE.ID }, true); public static final UniqueKey UNIQUE_NAMESPACE_PUBLIC_ID = Internal.createUniqueKey(Namespace.NAMESPACE, DSL.name("unique_namespace_public_id"), new TableField[] { Namespace.NAMESPACE.PUBLIC_ID }, true); public static final UniqueKey NAMESPACE_MEMBERSHIP_PKEY = Internal.createUniqueKey(NamespaceMembership.NAMESPACE_MEMBERSHIP, DSL.name("namespace_membership_pkey"), new TableField[] { NamespaceMembership.NAMESPACE_MEMBERSHIP.ID }, true); @@ -161,6 +164,11 @@ public class Keys { public static final ForeignKey FILE_DECISION__FK_FILE_DECISION_SCAN = Internal.createForeignKey(FileDecision.FILE_DECISION, DSL.name("fk_file_decision_scan"), new TableField[] { FileDecision.FILE_DECISION.SCAN_ID }, Keys.EXTENSION_SCAN_PKEY, new TableField[] { ExtensionScan.EXTENSION_SCAN.ID }, true); public static final ForeignKey FILE_DECISION__FK_FILE_DECISION_USER = Internal.createForeignKey(FileDecision.FILE_DECISION, DSL.name("fk_file_decision_user"), new TableField[] { FileDecision.FILE_DECISION.DECIDED_BY_ID }, Keys.USER_DATA_PKEY, new TableField[] { UserData.USER_DATA.ID }, true); public static final ForeignKey FILE_RESOURCE__FILE_RESOURCE_EXTENSION_FKEY = Internal.createForeignKey(FileResource.FILE_RESOURCE, DSL.name("file_resource_extension_fkey"), new TableField[] { FileResource.FILE_RESOURCE.EXTENSION_ID }, Keys.EXTENSION_VERSION_PKEY, new TableField[] { ExtensionVersion.EXTENSION_VERSION.ID }, true); + public static final ForeignKey NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_DECIDED_BY_ID_FKEY = Internal.createForeignKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_decided_by_id_fkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.DECIDED_BY_ID }, Keys.USER_DATA_PKEY, new TableField[] { UserData.USER_DATA.ID }, true); + public static final ForeignKey NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_EXTENSION_ID_FKEY = Internal.createForeignKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_extension_id_fkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.EXTENSION_ID }, Keys.EXTENSION_PKEY, new TableField[] { Extension.EXTENSION.ID }, true); + public static final ForeignKey NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_NAMESPACE_ID_FKEY = Internal.createForeignKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_namespace_id_fkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.NAMESPACE_ID }, Keys.NAMESPACE_PKEY, new TableField[] { Namespace.NAMESPACE.ID }, true); + public static final ForeignKey NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_OTHER_EXTENSION_ID_FKEY = Internal.createForeignKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_other_extension_id_fkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.OTHER_EXTENSION_ID }, Keys.EXTENSION_PKEY, new TableField[] { Extension.EXTENSION.ID }, true); + public static final ForeignKey NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_OTHER_NAMESPACE_ID_FKEY = Internal.createForeignKey(NameSimilarityAllow.NAME_SIMILARITY_ALLOW, DSL.name("name_similarity_allow_other_namespace_id_fkey"), new TableField[] { NameSimilarityAllow.NAME_SIMILARITY_ALLOW.OTHER_NAMESPACE_ID }, Keys.NAMESPACE_PKEY, new TableField[] { Namespace.NAMESPACE.ID }, true); public static final ForeignKey NAMESPACE_MEMBERSHIP__FKGFHWHKNULA6DO2N6WYVQETM3N = Internal.createForeignKey(NamespaceMembership.NAMESPACE_MEMBERSHIP, DSL.name("fkgfhwhknula6do2n6wyvqetm3n"), new TableField[] { NamespaceMembership.NAMESPACE_MEMBERSHIP.NAMESPACE }, Keys.NAMESPACE_PKEY, new TableField[] { Namespace.NAMESPACE.ID }, true); public static final ForeignKey NAMESPACE_MEMBERSHIP__FKNSAMEKUTXYWVSB3S1MJDCJKYP = Internal.createForeignKey(NamespaceMembership.NAMESPACE_MEMBERSHIP, DSL.name("fknsamekutxywvsb3s1mjdcjkyp"), new TableField[] { NamespaceMembership.NAMESPACE_MEMBERSHIP.USER_DATA }, Keys.USER_DATA_PKEY, new TableField[] { UserData.USER_DATA.ID }, true); public static final ForeignKey NAMESPACE_SOCIAL_LINKS__NAMESPACE_SOCIAL_LINKS_FKEY = Internal.createForeignKey(NamespaceSocialLinks.NAMESPACE_SOCIAL_LINKS, DSL.name("namespace_social_links_fkey"), new TableField[] { NamespaceSocialLinks.NAMESPACE_SOCIAL_LINKS.NAMESPACE_ID }, Keys.NAMESPACE_PKEY, new TableField[] { Namespace.NAMESPACE.ID }, true); diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Public.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Public.java index a18e7c372..2ffe4a583 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Public.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Public.java @@ -27,6 +27,7 @@ import org.eclipse.openvsx.jooq.tables.FileDecision; import org.eclipse.openvsx.jooq.tables.FileResource; import org.eclipse.openvsx.jooq.tables.MigrationItem; +import org.eclipse.openvsx.jooq.tables.NameSimilarityAllow; import org.eclipse.openvsx.jooq.tables.Namespace; import org.eclipse.openvsx.jooq.tables.NamespaceMembership; import org.eclipse.openvsx.jooq.tables.NamespaceSocialLinks; @@ -165,6 +166,11 @@ public class Public extends SchemaImpl { */ public final MigrationItem MIGRATION_ITEM = MigrationItem.MIGRATION_ITEM; + /** + * The table public.name_similarity_allow. + */ + public final NameSimilarityAllow NAME_SIMILARITY_ALLOW = NameSimilarityAllow.NAME_SIMILARITY_ALLOW; + /** * The table public.namespace. */ @@ -271,6 +277,7 @@ public final List> getSequences() { Sequences.FILE_RESOURCE_SEQ, Sequences.HIBERNATE_SEQUENCE, Sequences.MIGRATION_ITEM_SEQ, + Sequences.NAME_SIMILARITY_ALLOW_SEQ, Sequences.NAMESPACE_MEMBERSHIP_SEQ, Sequences.NAMESPACE_SEQ, Sequences.PERSISTED_LOG_SEQ, @@ -308,6 +315,7 @@ public final List> getTables() { FileDecision.FILE_DECISION, FileResource.FILE_RESOURCE, MigrationItem.MIGRATION_ITEM, + NameSimilarityAllow.NAME_SIMILARITY_ALLOW, Namespace.NAMESPACE, NamespaceMembership.NAMESPACE_MEMBERSHIP, NamespaceSocialLinks.NAMESPACE_SOCIAL_LINKS, diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Sequences.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Sequences.java index fd1af3cf9..b1feabd22 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Sequences.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Sequences.java @@ -90,6 +90,11 @@ public class Sequences { */ public static final Sequence MIGRATION_ITEM_SEQ = Internal.createSequence("migration_item_seq", Public.PUBLIC, SQLDataType.BIGINT.nullable(false), null, 50, null, null, false, null); + /** + * The sequence public.name_similarity_allow_seq + */ + public static final Sequence NAME_SIMILARITY_ALLOW_SEQ = Internal.createSequence("name_similarity_allow_seq", Public.PUBLIC, SQLDataType.BIGINT.nullable(false), null, null, null, null, false, null); + /** * The sequence public.namespace_membership_seq */ diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Tables.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Tables.java index 65f9c9f44..8decca74d 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Tables.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/Tables.java @@ -24,6 +24,7 @@ import org.eclipse.openvsx.jooq.tables.FileDecision; import org.eclipse.openvsx.jooq.tables.FileResource; import org.eclipse.openvsx.jooq.tables.MigrationItem; +import org.eclipse.openvsx.jooq.tables.NameSimilarityAllow; import org.eclipse.openvsx.jooq.tables.Namespace; import org.eclipse.openvsx.jooq.tables.NamespaceMembership; import org.eclipse.openvsx.jooq.tables.NamespaceSocialLinks; @@ -151,6 +152,11 @@ public class Tables { */ public static final MigrationItem MIGRATION_ITEM = MigrationItem.MIGRATION_ITEM; + /** + * The table public.name_similarity_allow. + */ + public static final NameSimilarityAllow NAME_SIMILARITY_ALLOW = NameSimilarityAllow.NAME_SIMILARITY_ALLOW; + /** * The table public.namespace. */ diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/ExtensionValidationFailure.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/ExtensionValidationFailure.java index a5445f49a..a975fe2de 100644 --- a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/ExtensionValidationFailure.java +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/ExtensionValidationFailure.java @@ -131,7 +131,7 @@ public Schema getSchema() { @Override public List getIndexes() { - return Arrays.asList(Indexes.IDX_VALIDATION_FAILURE_DETECTED_AT, Indexes.IDX_VALIDATION_FAILURE_SCAN, Indexes.IDX_VALIDATION_FAILURE_VALIDATION_TYPE); + return Arrays.asList(Indexes.EXTENSION_VALIDATION_FAILURE_TYPE_DETECTED_IDX, Indexes.IDX_VALIDATION_FAILURE_DETECTED_AT, Indexes.IDX_VALIDATION_FAILURE_SCAN, Indexes.IDX_VALIDATION_FAILURE_VALIDATION_TYPE); } @Override diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/NameSimilarityAllow.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/NameSimilarityAllow.java new file mode 100644 index 000000000..ceeafec50 --- /dev/null +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/NameSimilarityAllow.java @@ -0,0 +1,309 @@ +/* + * This file is generated by jOOQ. + */ +package org.eclipse.openvsx.jooq.tables; + + +import java.time.LocalDateTime; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +import org.eclipse.openvsx.jooq.Indexes; +import org.eclipse.openvsx.jooq.Keys; +import org.eclipse.openvsx.jooq.Public; +import org.eclipse.openvsx.jooq.tables.records.NameSimilarityAllowRecord; +import org.jooq.Check; +import org.jooq.Condition; +import org.jooq.Field; +import org.jooq.ForeignKey; +import org.jooq.Identity; +import org.jooq.Index; +import org.jooq.Name; +import org.jooq.PlainSQL; +import org.jooq.QueryPart; +import org.jooq.SQL; +import org.jooq.Schema; +import org.jooq.Select; +import org.jooq.Stringly; +import org.jooq.Table; +import org.jooq.TableField; +import org.jooq.TableOptions; +import org.jooq.UniqueKey; +import org.jooq.impl.DSL; +import org.jooq.impl.Internal; +import org.jooq.impl.SQLDataType; +import org.jooq.impl.TableImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class NameSimilarityAllow extends TableImpl { + + private static final long serialVersionUID = 1L; + + /** + * The reference instance of public.name_similarity_allow + */ + public static final NameSimilarityAllow NAME_SIMILARITY_ALLOW = new NameSimilarityAllow(); + + /** + * The class holding records for this type + */ + @Override + public Class getRecordType() { + return NameSimilarityAllowRecord.class; + } + + /** + * The column public.name_similarity_allow.id. + */ + public final TableField ID = createField(DSL.name("id"), SQLDataType.BIGINT.nullable(false).identity(true), this, ""); + + /** + * The column public.name_similarity_allow.extension_id. + */ + public final TableField EXTENSION_ID = createField(DSL.name("extension_id"), SQLDataType.BIGINT, this, ""); + + /** + * The column public.name_similarity_allow.other_extension_id. + */ + public final TableField OTHER_EXTENSION_ID = createField(DSL.name("other_extension_id"), SQLDataType.BIGINT, this, ""); + + /** + * The column public.name_similarity_allow.field. + */ + public final TableField FIELD = createField(DSL.name("field"), SQLDataType.VARCHAR(16).nullable(false), this, ""); + + /** + * The column public.name_similarity_allow.similarity. + */ + public final TableField SIMILARITY = createField(DSL.name("similarity"), SQLDataType.REAL.nullable(false), this, ""); + + /** + * The column public.name_similarity_allow.lookalike_value. + */ + public final TableField LOOKALIKE_VALUE = createField(DSL.name("lookalike_value"), SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.name_similarity_allow.other_value. + */ + public final TableField OTHER_VALUE = createField(DSL.name("other_value"), SQLDataType.VARCHAR(255).nullable(false), this, ""); + + /** + * The column public.name_similarity_allow.reason. + */ + public final TableField REASON = createField(DSL.name("reason"), SQLDataType.VARCHAR(2048), this, ""); + + /** + * The column public.name_similarity_allow.decided_by_id. + */ + public final TableField DECIDED_BY_ID = createField(DSL.name("decided_by_id"), SQLDataType.BIGINT, this, ""); + + /** + * The column public.name_similarity_allow.decided_at. + */ + public final TableField DECIDED_AT = createField(DSL.name("decided_at"), SQLDataType.LOCALDATETIME(6).nullable(false), this, ""); + + /** + * The column public.name_similarity_allow.namespace_id. + */ + public final TableField NAMESPACE_ID = createField(DSL.name("namespace_id"), SQLDataType.BIGINT, this, ""); + + /** + * The column public.name_similarity_allow.other_namespace_id. + */ + public final TableField OTHER_NAMESPACE_ID = createField(DSL.name("other_namespace_id"), SQLDataType.BIGINT, this, ""); + + private NameSimilarityAllow(Name alias, Table aliased) { + this(alias, aliased, (Field[]) null, null); + } + + private NameSimilarityAllow(Name alias, Table aliased, Field[] parameters, Condition where) { + super(alias, null, aliased, parameters, DSL.comment(""), TableOptions.table(), where); + } + + /** + * Create an aliased public.name_similarity_allow table + * reference + */ + public NameSimilarityAllow(String alias) { + this(DSL.name(alias), NAME_SIMILARITY_ALLOW); + } + + /** + * Create an aliased public.name_similarity_allow table + * reference + */ + public NameSimilarityAllow(Name alias) { + this(alias, NAME_SIMILARITY_ALLOW); + } + + /** + * Create a public.name_similarity_allow table reference + */ + public NameSimilarityAllow() { + this(DSL.name("name_similarity_allow"), null); + } + + @Override + public Schema getSchema() { + return aliased() ? null : Public.PUBLIC; + } + + @Override + public List getIndexes() { + return Arrays.asList(Indexes.NAME_SIMILARITY_ALLOW_DECIDED_BY_IDX, Indexes.NAME_SIMILARITY_ALLOW_EXTENSION_IDX, Indexes.NAME_SIMILARITY_ALLOW_NAMESPACE_IDX, Indexes.NAME_SIMILARITY_ALLOW_OTHER_EXTENSION_IDX, Indexes.NAME_SIMILARITY_ALLOW_OTHER_NAMESPACE_IDX); + } + + @Override + public Identity getIdentity() { + return (Identity) super.getIdentity(); + } + + @Override + public UniqueKey getPrimaryKey() { + return Keys.NAME_SIMILARITY_ALLOW_PKEY; + } + + @Override + public List> getReferences() { + return Arrays.asList(Keys.NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_DECIDED_BY_ID_FKEY, Keys.NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_EXTENSION_ID_FKEY, Keys.NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_NAMESPACE_ID_FKEY, Keys.NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_OTHER_EXTENSION_ID_FKEY, Keys.NAME_SIMILARITY_ALLOW__NAME_SIMILARITY_ALLOW_OTHER_NAMESPACE_ID_FKEY); + } + + @Override + public List> getChecks() { + return Arrays.asList( + Internal.createCheck(this, DSL.name("name_similarity_allow_distinct_ck"), "((extension_id <> other_extension_id))", true), + Internal.createCheck(this, DSL.name("name_similarity_allow_field_ck"), "(((field)::text = ANY ((ARRAY['NAME'::character varying, 'DISPLAY_NAME'::character varying, 'NAMESPACE'::character varying])::text[])))", true), + Internal.createCheck(this, DSL.name("name_similarity_allow_kind_ck"), "(\nCASE\n WHEN ((field)::text = 'NAMESPACE'::text) THEN ((namespace_id IS NOT NULL) AND (other_namespace_id IS NOT NULL) AND (extension_id IS NULL) AND (other_extension_id IS NULL))\n ELSE ((extension_id IS NOT NULL) AND (other_extension_id IS NOT NULL) AND (namespace_id IS NULL) AND (other_namespace_id IS NULL))\nEND)", true), + Internal.createCheck(this, DSL.name("name_similarity_allow_namespace_distinct_ck"), "((namespace_id <> other_namespace_id))", true), + Internal.createCheck(this, DSL.name("name_similarity_allow_similarity_ck"), "(((similarity >= (0)::double precision) AND (similarity <= (1)::double precision)))", true) + ); + } + + @Override + public NameSimilarityAllow as(String alias) { + return new NameSimilarityAllow(DSL.name(alias), this); + } + + @Override + public NameSimilarityAllow as(Name alias) { + return new NameSimilarityAllow(alias, this); + } + + @Override + public NameSimilarityAllow as(Table alias) { + return new NameSimilarityAllow(alias.getQualifiedName(), this); + } + + /** + * Rename this table + */ + @Override + public NameSimilarityAllow rename(String name) { + return new NameSimilarityAllow(DSL.name(name), null); + } + + /** + * Rename this table + */ + @Override + public NameSimilarityAllow rename(Name name) { + return new NameSimilarityAllow(name, null); + } + + /** + * Rename this table + */ + @Override + public NameSimilarityAllow rename(Table name) { + return new NameSimilarityAllow(name.getQualifiedName(), null); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow where(Condition condition) { + return new NameSimilarityAllow(getQualifiedName(), aliased() ? this : null, null, condition); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow where(Collection conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow where(Condition... conditions) { + return where(DSL.and(conditions)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow where(Field condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public NameSimilarityAllow where(SQL condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public NameSimilarityAllow where(@Stringly.SQL String condition) { + return where(DSL.condition(condition)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public NameSimilarityAllow where(@Stringly.SQL String condition, Object... binds) { + return where(DSL.condition(condition, binds)); + } + + /** + * Create an inline derived table from this table + */ + @Override + @PlainSQL + public NameSimilarityAllow where(@Stringly.SQL String condition, QueryPart... parts) { + return where(DSL.condition(condition, parts)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow whereExists(Select select) { + return where(DSL.exists(select)); + } + + /** + * Create an inline derived table from this table + */ + @Override + public NameSimilarityAllow whereNotExists(Select select) { + return where(DSL.notExists(select)); + } +} diff --git a/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/records/NameSimilarityAllowRecord.java b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/records/NameSimilarityAllowRecord.java new file mode 100644 index 000000000..4c631e3b4 --- /dev/null +++ b/server/src/main/jooq-gen/org/eclipse/openvsx/jooq/tables/records/NameSimilarityAllowRecord.java @@ -0,0 +1,230 @@ +/* + * This file is generated by jOOQ. + */ +package org.eclipse.openvsx.jooq.tables.records; + + +import java.time.LocalDateTime; + +import org.eclipse.openvsx.jooq.tables.NameSimilarityAllow; +import org.jooq.Record1; +import org.jooq.impl.UpdatableRecordImpl; + + +/** + * This class is generated by jOOQ. + */ +@SuppressWarnings({ "all", "unchecked", "rawtypes", "this-escape" }) +public class NameSimilarityAllowRecord extends UpdatableRecordImpl { + + private static final long serialVersionUID = 1L; + + /** + * Setter for public.name_similarity_allow.id. + */ + public void setId(Long value) { + set(0, value); + } + + /** + * Getter for public.name_similarity_allow.id. + */ + public Long getId() { + return (Long) get(0); + } + + /** + * Setter for public.name_similarity_allow.extension_id. + */ + public void setExtensionId(Long value) { + set(1, value); + } + + /** + * Getter for public.name_similarity_allow.extension_id. + */ + public Long getExtensionId() { + return (Long) get(1); + } + + /** + * Setter for public.name_similarity_allow.other_extension_id. + */ + public void setOtherExtensionId(Long value) { + set(2, value); + } + + /** + * Getter for public.name_similarity_allow.other_extension_id. + */ + public Long getOtherExtensionId() { + return (Long) get(2); + } + + /** + * Setter for public.name_similarity_allow.field. + */ + public void setField(String value) { + set(3, value); + } + + /** + * Getter for public.name_similarity_allow.field. + */ + public String getField() { + return (String) get(3); + } + + /** + * Setter for public.name_similarity_allow.similarity. + */ + public void setSimilarity(Float value) { + set(4, value); + } + + /** + * Getter for public.name_similarity_allow.similarity. + */ + public Float getSimilarity() { + return (Float) get(4); + } + + /** + * Setter for public.name_similarity_allow.lookalike_value. + */ + public void setLookalikeValue(String value) { + set(5, value); + } + + /** + * Getter for public.name_similarity_allow.lookalike_value. + */ + public String getLookalikeValue() { + return (String) get(5); + } + + /** + * Setter for public.name_similarity_allow.other_value. + */ + public void setOtherValue(String value) { + set(6, value); + } + + /** + * Getter for public.name_similarity_allow.other_value. + */ + public String getOtherValue() { + return (String) get(6); + } + + /** + * Setter for public.name_similarity_allow.reason. + */ + public void setReason(String value) { + set(7, value); + } + + /** + * Getter for public.name_similarity_allow.reason. + */ + public String getReason() { + return (String) get(7); + } + + /** + * Setter for public.name_similarity_allow.decided_by_id. + */ + public void setDecidedById(Long value) { + set(8, value); + } + + /** + * Getter for public.name_similarity_allow.decided_by_id. + */ + public Long getDecidedById() { + return (Long) get(8); + } + + /** + * Setter for public.name_similarity_allow.decided_at. + */ + public void setDecidedAt(LocalDateTime value) { + set(9, value); + } + + /** + * Getter for public.name_similarity_allow.decided_at. + */ + public LocalDateTime getDecidedAt() { + return (LocalDateTime) get(9); + } + + /** + * Setter for public.name_similarity_allow.namespace_id. + */ + public void setNamespaceId(Long value) { + set(10, value); + } + + /** + * Getter for public.name_similarity_allow.namespace_id. + */ + public Long getNamespaceId() { + return (Long) get(10); + } + + /** + * Setter for public.name_similarity_allow.other_namespace_id. + */ + public void setOtherNamespaceId(Long value) { + set(11, value); + } + + /** + * Getter for public.name_similarity_allow.other_namespace_id. + */ + public Long getOtherNamespaceId() { + return (Long) get(11); + } + + // ------------------------------------------------------------------------- + // Primary key information + // ------------------------------------------------------------------------- + + @Override + public Record1 key() { + return (Record1) super.key(); + } + + // ------------------------------------------------------------------------- + // Constructors + // ------------------------------------------------------------------------- + + /** + * Create a detached NameSimilarityAllowRecord + */ + public NameSimilarityAllowRecord() { + super(NameSimilarityAllow.NAME_SIMILARITY_ALLOW); + } + + /** + * Create a detached, initialised NameSimilarityAllowRecord + */ + public NameSimilarityAllowRecord(Long id, Long extensionId, Long otherExtensionId, String field, Float similarity, String lookalikeValue, String otherValue, String reason, Long decidedById, LocalDateTime decidedAt, Long namespaceId, Long otherNamespaceId) { + super(NameSimilarityAllow.NAME_SIMILARITY_ALLOW); + + setId(id); + setExtensionId(extensionId); + setOtherExtensionId(otherExtensionId); + setField(field); + setSimilarity(similarity); + setLookalikeValue(lookalikeValue); + setOtherValue(otherValue); + setReason(reason); + setDecidedById(decidedById); + setDecidedAt(decidedAt); + setNamespaceId(namespaceId); + setOtherNamespaceId(otherNamespaceId); + resetChangedOnNotNull(); + } +} diff --git a/server/src/main/resources/db/migration/V1_86__Name_Similarity_Allowlist.sql b/server/src/main/resources/db/migration/V1_86__Name_Similarity_Allowlist.sql new file mode 100644 index 000000000..04a8b0a66 --- /dev/null +++ b/server/src/main/resources/db/migration/V1_86__Name_Similarity_Allowlist.sql @@ -0,0 +1,39 @@ +-- Trigram similarity (similarity(), the % operator and the gin_trgm_ops index class) behind the +-- NAME_SIMILARITY publish check and the name squatting admin dashboard. pg_trgm is a trusted +-- extension since PostgreSQL 13, so a database owner without superuser rights can create it. +CREATE EXTENSION IF NOT EXISTS pg_trgm; + +CREATE SEQUENCE IF NOT EXISTS name_similarity_allow_seq START WITH 1 INCREMENT BY 1; + +-- Pairs of extensions an admin has confirmed are not squatting on each other. A pair is stored once, +-- whichever way round it was allowed: extension_id is the look-alike that was allowed and +-- other_extension_id the extension it was allowed alongside. field, similarity and the two values +-- record the match as the admin saw it, to tell when either name has changed since. +CREATE TABLE IF NOT EXISTS public.name_similarity_allow +( + id BIGINT NOT NULL PRIMARY KEY DEFAULT nextval('name_similarity_allow_seq'), + extension_id BIGINT NOT NULL REFERENCES public.extension(id) ON DELETE CASCADE, + other_extension_id BIGINT NOT NULL REFERENCES public.extension(id) ON DELETE CASCADE, + field VARCHAR(16) NOT NULL, + similarity REAL NOT NULL, + extension_value VARCHAR(255) NOT NULL, + other_value VARCHAR(255) NOT NULL, + reason VARCHAR(2048), + decided_by_id BIGINT REFERENCES public.user_data(id) ON DELETE SET NULL, + decided_at TIMESTAMP without time zone NOT NULL, + CONSTRAINT name_similarity_allow_distinct_ck CHECK (extension_id <> other_extension_id), + CONSTRAINT name_similarity_allow_field_ck CHECK (field IN ('NAME', 'DISPLAY_NAME', 'NAMESPACE')), + CONSTRAINT name_similarity_allow_similarity_ck CHECK (similarity >= 0 AND similarity <= 1) +); + +-- Without this pg_get_serial_sequence cannot find the sequence, which defeats +-- scripts/import-db-dump.sh's sequence reset after loading a dump. +ALTER SEQUENCE name_similarity_allow_seq OWNED BY public.name_similarity_allow.id; + +CREATE UNIQUE INDEX IF NOT EXISTS name_similarity_allow_pair_idx + ON public.name_similarity_allow (LEAST(extension_id, other_extension_id), GREATEST(extension_id, other_extension_id)); + +-- The unique index leads with LEAST(...), so it cannot serve the ON DELETE CASCADE lookups by either column. +CREATE INDEX IF NOT EXISTS name_similarity_allow_extension_idx ON public.name_similarity_allow (extension_id); +CREATE INDEX IF NOT EXISTS name_similarity_allow_other_extension_idx ON public.name_similarity_allow (other_extension_id); +CREATE INDEX IF NOT EXISTS name_similarity_allow_decided_by_idx ON public.name_similarity_allow (decided_by_id); diff --git a/server/src/main/resources/db/migration/V1_87__Name_Similarity_Indexes.sql b/server/src/main/resources/db/migration/V1_87__Name_Similarity_Indexes.sql new file mode 100644 index 000000000..b533974f2 --- /dev/null +++ b/server/src/main/resources/db/migration/V1_87__Name_Similarity_Indexes.sql @@ -0,0 +1,38 @@ +-- Indexes for the NAME_SIMILARITY check (see NameSimilarityJooqRepository): trigram indexes to find the +-- active extensions whose name or display name resembles a given one with the % operator, and one to +-- list the extensions the check flagged, most recently flagged first. +-- +-- The display name expression has to match the one used by the query, or the planner falls back to a +-- sequential scan over every version: casing and surrounding whitespace are normalised away, the +-- trimmed set being every Unicode space separator. It is the same normalisation as the +-- DISPLAY_NAME_CONFLICT check's extension_version_display_name_idx. +-- +-- The trigram indexes are restricted to the versions and extensions that are publicly visible, which is +-- all the lookups look at, and which keeps the inactive versions that make up the bulk of the table out. +-- +-- Deliberately not CONCURRENTLY: Flyway holds a transaction open on a second connection for the whole +-- run, and CREATE INDEX CONCURRENTLY waits for every transaction open alongside it, Flyway's own +-- included, so it never returns. The plain build blocks writes to each table until it completes, and +-- lock_timeout makes it give up, to be retried, rather than queue every writer behind a build that is +-- itself waiting on a long-running transaction. To deploy without a write pause, create the indexes +-- CONCURRENTLY out of band first; IF NOT EXISTS then turns this migration into a no-op. A failed +-- CONCURRENTLY build leaves an invalid index behind that IF NOT EXISTS will not replace, so drop it +-- before retrying. + +SET LOCAL lock_timeout = '5s'; + +CREATE INDEX IF NOT EXISTS extension_version_display_name_trgm_idx + ON public.extension_version + USING gin (lower(btrim(display_name, U&' \00A0\1680\2000\2001\2002\2003\2004\2005\2006\2007\2008\2009\200A\202F\205F\3000')) gin_trgm_ops) + WHERE active; + +CREATE INDEX IF NOT EXISTS extension_name_trgm_idx + ON public.extension + USING gin (lower(name) gin_trgm_ops) + WHERE active; + +-- Lets the name squatting dashboard walk a check type's failures newest first and stop once a page is +-- full, instead of aggregating every failure ever recorded. scan_id makes the walk index-only and gives +-- failures recorded at the same instant a stable order to resume from. +CREATE INDEX IF NOT EXISTS extension_validation_failure_type_detected_idx + ON public.extension_validation_failure (validation_type, detected_at DESC, scan_id DESC); diff --git a/server/src/main/resources/db/migration/V1_88__Namespace_Similarity.sql b/server/src/main/resources/db/migration/V1_88__Namespace_Similarity.sql new file mode 100644 index 000000000..46b9e6692 --- /dev/null +++ b/server/src/main/resources/db/migration/V1_88__Namespace_Similarity.sql @@ -0,0 +1,41 @@ +-- Schema behind the namespaces view of the name squatting admin dashboard: pairs of namespaces whose +-- names resemble each other (see NamespaceSimilarityJooqRepository), and the pairs an admin allowed. +-- pg_trgm (V1_86) and fuzzystrmatch (V1_58) are already in place. +-- +-- Adding the foreign keys and building the index block writes to namespace. The table is small (tens of +-- thousands of rows), so the pause is short; lock_timeout makes the migration give up, to be retried, +-- rather than queue every writer behind it. +SET LOCAL lock_timeout = '5s'; + +-- name_similarity_allow (V1_86) also holds allowed pairs of namespaces: field 'NAMESPACE' marks them, +-- and they fill namespace_id and other_namespace_id where pairs of extensions fill the extension ids. +-- lookalike_value holds the name of whichever kind the look-alike is. +ALTER TABLE public.name_similarity_allow RENAME COLUMN extension_value TO lookalike_value; + +ALTER TABLE public.name_similarity_allow + ALTER COLUMN extension_id DROP NOT NULL, + ALTER COLUMN other_extension_id DROP NOT NULL, + ADD COLUMN namespace_id BIGINT REFERENCES public.namespace(id) ON DELETE CASCADE, + ADD COLUMN other_namespace_id BIGINT REFERENCES public.namespace(id) ON DELETE CASCADE, + ADD CONSTRAINT name_similarity_allow_namespace_distinct_ck CHECK (namespace_id <> other_namespace_id), + ADD CONSTRAINT name_similarity_allow_kind_ck CHECK ( + CASE WHEN field = 'NAMESPACE' + THEN namespace_id IS NOT NULL AND other_namespace_id IS NOT NULL + AND extension_id IS NULL AND other_extension_id IS NULL + ELSE extension_id IS NOT NULL AND other_extension_id IS NOT NULL + AND namespace_id IS NULL AND other_namespace_id IS NULL + END + ); + +-- Rows of the other kind have NULL here, which a unique index never counts as a duplicate. +CREATE UNIQUE INDEX IF NOT EXISTS name_similarity_allow_namespace_pair_idx + ON public.name_similarity_allow (LEAST(namespace_id, other_namespace_id), GREATEST(namespace_id, other_namespace_id)); + +-- The unique index leads with LEAST(...), so it cannot serve the ON DELETE CASCADE lookups by either column. +CREATE INDEX IF NOT EXISTS name_similarity_allow_namespace_idx ON public.name_similarity_allow (namespace_id); +CREATE INDEX IF NOT EXISTS name_similarity_allow_other_namespace_idx ON public.name_similarity_allow (other_namespace_id); + +-- Finds the namespaces whose name resembles a given one with the % operator. +CREATE INDEX IF NOT EXISTS namespace_name_trgm_idx + ON public.namespace + USING gin (lower(name) gin_trgm_ops); diff --git a/server/src/test/java/org/eclipse/openvsx/admin/NameSquattingServiceTest.java b/server/src/test/java/org/eclipse/openvsx/admin/NameSquattingServiceTest.java new file mode 100644 index 000000000..f30c1a577 --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/admin/NameSquattingServiceTest.java @@ -0,0 +1,597 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.admin; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import jakarta.persistence.EntityManager; +import org.assertj.core.api.ThrowableAssert.ThrowingCallable; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpStatus; +import org.springframework.transaction.annotation.Transactional; + +import org.eclipse.openvsx.AbstractPostgresContainerTest; +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.ExtensionScan; +import org.eclipse.openvsx.entities.ExtensionValidationFailure; +import org.eclipse.openvsx.entities.ExtensionVersion; +import org.eclipse.openvsx.entities.Namespace; +import org.eclipse.openvsx.entities.ScanStatus; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.json.NameSquattingJson; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository; +import org.eclipse.openvsx.repositories.RepositoryService; +import org.eclipse.openvsx.scanning.NameSimilarityCheckService; +import org.eclipse.openvsx.util.ErrorResultException; +import org.eclipse.openvsx.util.TargetPlatform; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Every test class shares one database, so fixtures carry random words and assertions only look at the + * extensions a test created. + */ +@Tag("integration") +@SpringBootTest +@Transactional +class NameSquattingServiceTest extends AbstractPostgresContainerTest { + + private static final LocalDateTime EARLY = LocalDateTime.of(2020, 3, 1, 0, 0); + private static final LocalDateTime MIDDLE = LocalDateTime.of(2023, 3, 1, 0, 0); + private static final LocalDateTime LATE = LocalDateTime.of(2026, 10, 1, 0, 0); + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + @Autowired + EntityManager em; + + @Autowired + NameSquattingService service; + + @Autowired + NameSimilarityJooqRepository similarity; + + @Autowired + RepositoryService repositories; + + private UserData admin; + + @BeforeEach + void persistAdmin() { + admin = new UserData(); + admin.setLoginName("name-squatting-admin-" + UUID.randomUUID()); + admin.setProvider("github"); + em.persist(admin); + } + + @Test + void groupsAFlaggedLookalikeUnderTheExtensionPublishedFirst() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + flag(lookalike, LATE.plusDays(1)); + + var group = groupOf(original); + + assertThat(group.lookalikes()).singleElement().satisfies(found -> { + assertThat(found.extension().name()).isEqualTo(lookalike.getName()); + assertThat(found.flaggedAt()).isNotNull(); + assertThat(found.matches()).first().satisfies(match -> { + assertThat(match.field()).isEqualTo("DISPLAY_NAME"); + assertThat(match.value()).isEqualTo(word + " Formatter"); + assertThat(match.lookalikeValue()).isEqualTo(word + " Formater"); + assertThat(match.exact()).isFalse(); + }); + }); + } + + @Test + void groupsTheSameWayWhenTheExtensionPublishedFirstWasFlagged() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + flag(original, LATE.plusDays(1)); + + var group = groupOf(original); + + assertThat(group.lookalikes()).singleElement().satisfies(found -> { + assertThat(found.extension().name()).isEqualTo(lookalike.getName()); + assertThat(found.matches().getFirst().value()).isEqualTo(word + " Formatter"); + assertThat(found.matches().getFirst().lookalikeValue()).isEqualTo(word + " Formater"); + }); + } + + @Test + void listsALookalikeOnceUnderTheEarliestExtensionItResembles() throws ErrorResultException { + var word = word(); + var earliest = persistExtension(word + " Tools", EARLY); + var later = persistExtension(word + " Tools", MIDDLE); + var lookalike = persistExtension(word + " Tools", LATE); + flag(lookalike, LATE.plusDays(1)); + em.flush(); + + var placements = service.findCollisions(0, 100).groups().stream() + .filter( + group -> group.lookalikes().stream() + .anyMatch(found -> found.extension().name().equals(lookalike.getName()))) + .map(group -> group.anchor().name()) + .toList(); + + assertThat(placements).containsExactly(earliest.getName()); + assertThat(placements).doesNotContain(later.getName()); + } + + @Test + void allowedPairsLeaveTheCollisionsAndJoinTheAllowlist() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + flag(lookalike, LATE.plusDays(1)); + em.flush(); + + service.allow(allowRequest(lookalike, original, "Official fork"), admin); + em.flush(); + + assertThat(lookalikeNames(service.findCollisions(0, 100))).doesNotContain(lookalike.getName()); + assertThat(allowlistGroupOf(lookalike).allows()).singleElement().satisfies(allow -> { + assertThat(allow.other().name()).isEqualTo(original.getName()); + assertThat(allow.field()).isEqualTo("DISPLAY_NAME"); + assertThat(allow.value()).isEqualTo(word + " Formater"); + assertThat(allow.otherValue()).isEqualTo(word + " Formatter"); + assertThat(allow.renamed()).isFalse(); + assertThat(allow.reason()).isEqualTo("Official fork"); + assertThat(allow.decidedBy()).isEqualTo(admin.getLoginName()); + }); + } + + @Test + void allowingTwiceKeepsOneAllow() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + em.flush(); + + service.allow(allowRequest(lookalike, original, null), admin); + em.flush(); + var again = service.allow(allowRequest(original, lookalike, null), admin); + em.flush(); + + assertThat(again.getSuccess()).startsWith("Already allowed"); + assertThat(allowlistGroupOf(lookalike).allows()).hasSize(1); + } + + @Test + void refusesToAllowExtensionsThatDoNotResembleEachOther() { + var original = persistExtension(word() + " Formatter", EARLY); + var unrelated = persistExtension(word() + " Linter", LATE); + em.flush(); + + assertThatThrownBy(() -> service.allow(allowRequest(unrelated, original, null), admin)) + .isInstanceOfSatisfying( + ErrorResultException.class, + exc -> assertThat(exc.getStatus()).isEqualTo(HttpStatus.BAD_REQUEST)); + } + + @Test + void removingAnAllowReportsThePairAgain() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + flag(lookalike, LATE.plusDays(1)); + em.flush(); + service.allow(allowRequest(lookalike, original, null), admin); + em.flush(); + + service.removeAllow(allowlistGroupOf(lookalike).allows().getFirst().id(), admin); + + assertThat(groupOf(original).lookalikes()).extracting(found -> found.extension().name()) + .containsExactly(lookalike.getName()); + } + + @Test + void marksAnAllowWhoseNamesChangedSince() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Formatter", EARLY); + var lookalike = persistExtension(word + " Formater", LATE); + em.flush(); + service.allow(allowRequest(lookalike, original, null), admin); + lookalike.getVersions().getFirst().setActive(false); + persistVersion(lookalike, "2.0.0", word + " Formatter Pro"); + em.flush(); + + assertThat(allowlistGroupOf(lookalike).allows()).singleElement() + .satisfies(allow -> assertThat(allow.renamed()).isTrue()); + } + + @Test + void findsDisplayNamesSharedAcrossNamespacesWithoutAFlag() throws ErrorResultException { + var word = word(); + var original = persistExtension(word + " Tools", EARLY); + var grandfathered = persistExtension(word + " TOOLS", MIDDLE); + var flagged = persistExtension(word() + " Other", LATE); + flag(flagged, LATE.plusDays(1)); + em.flush(); + + var candidates = similarity.findCandidates(NameSimilarityCheckService.CHECK_TYPE, 0, 100_000, TIMEOUT); + + var ids = candidates.stream().map(NameSimilarityJooqRepository.Candidate::extensionId).toList(); + assertThat(ids).contains(original.getId(), grandfathered.getId(), flagged.getId()); + assertThat(ids.indexOf(flagged.getId())).isLessThan(ids.indexOf(original.getId())); + assertThat(candidates).filteredOn(candidate -> candidate.extensionId() == original.getId()) + .singleElement() + .satisfies(candidate -> assertThat(candidate.flaggedAt()).isNull()); + } + + @Test + void pagesContinueFromTheFlaggedCandidatesIntoSharedDisplayNames() { + var word = word(); + persistExtension(word + " Tools", EARLY); + persistExtension(word + " Tools", MIDDLE); + flag(persistExtension(word() + " Other", LATE), LATE.plusDays(1)); + flag(persistExtension(word() + " Else", LATE), LATE.plusDays(2)); + em.flush(); + var all = similarity.findCandidates(NameSimilarityCheckService.CHECK_TYPE, 0, 100_000, TIMEOUT); + var flaggedCount = (int) all.stream().filter(candidate -> candidate.flaggedAt() != null).count(); + + var acrossTheBoundary = similarity.findCandidates( + NameSimilarityCheckService.CHECK_TYPE, + flaggedCount - 1, + 2, + TIMEOUT); + var pastIt = similarity.findCandidates( + NameSimilarityCheckService.CHECK_TYPE, + flaggedCount + 1, + 1, + TIMEOUT); + + assertThat(acrossTheBoundary).containsExactly(all.get(flaggedCount - 1), all.get(flaggedCount)); + assertThat(acrossTheBoundary.get(1).flaggedAt()).isNull(); + assertThat(pastIt).containsExactly(all.get(flaggedCount + 1)); + } + + @Test + void recognizesAStatementCancelledByItsTimeout() { + var cancelled = new RuntimeException( + new java.sql.SQLException("canceling statement due to statement timeout", "57014")); + + assertThat(NameSquattingService.isStatementTimeout(cancelled)).isTrue(); + assertThat( + NameSquattingService + .isStatementTimeout(new RuntimeException(new java.sql.SQLException("other", "23505")))) + .isFalse(); + } + + @Test + void ordersANamespacePairWithTheMoreDownloadedNamespaceAsTarget() throws ErrorResultException { + var name = word() + "xy"; + var lookalike = persistNamespace(oneEditFrom(name)); + var target = persistNamespace(name); + persistNamespaceExtension(target, 50_000, EARLY); + + assertThat(namespacePairOf(target, lookalike, false)).satisfies(pair -> { + assertThat(pair.target().name()).isEqualTo(target.getName()); + assertThat(pair.target().downloads()).isEqualTo(50_000); + assertThat(pair.target().activeExtensions()).isEqualTo(1); + assertThat(pair.target().firstPublished()).isNotNull(); + assertThat(pair.lookalike().name()).isEqualTo(lookalike.getName()); + assertThat(pair.lookalike().firstPublished()).isNull(); + assertThat(pair.editDistance()).isEqualTo(1); + assertThat(pair.popular()).isTrue(); + }); + } + + @Test + void popularOnlyLeavesOutPairsWithoutAPopularTargetButCountsThem() throws ErrorResultException { + var popular = persistNamespacePair(50_000, 0); + var closeRival = persistNamespacePair(20_000, 5_000); + var niche = persistNamespacePair(500, 0); + + var all = namespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS); + var popularOnly = namespacePairs(true, NameSquattingService.NamespaceSort.DOWNLOADS); + + assertThat(targets(all)).contains(popular, closeRival, niche); + assertThat(targets(popularOnly)).contains(popular).doesNotContain(closeRival, niche); + assertThat(popularOnly.pairs()).allMatch(NameSquattingJson.NamespacePair::popular); + assertThat(popularOnly.total()).isEqualTo(all.total()); + assertThat(all.popularTotal()).isEqualTo(popularOnly.popularTotal()).isLessThanOrEqualTo(all.total() - 2); + } + + @Test + void sortsNamespacePairsByTargetDownloadsOrByTheNewestLookalike() throws ErrorResultException { + var olderSquat = persistNamespacePair(90_000, 10, EARLY); + var newerSquat = persistNamespacePair(30_000, 10, LATE); + + var byDownloads = targets(namespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS)); + var byNewest = targets(namespacePairs(false, NameSquattingService.NamespaceSort.NEWEST)); + + assertThat(byDownloads.indexOf(olderSquat)).isLessThan(byDownloads.indexOf(newerSquat)); + assertThat(byNewest.indexOf(newerSquat)).isLessThan(byNewest.indexOf(olderSquat)); + } + + @Test + void pagesThroughTheNamespacePairs() throws ErrorResultException { + persistNamespacePair(50_000, 0); + persistNamespacePair(60_000, 0); + var all = namespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS); + + var page = service.findNamespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS, 1, 1); + + assertThat(page.pairs()).containsExactly(all.pairs().get(1)); + assertThat(page.offset()).isEqualTo(1); + assertThat(page.hasMore()).isEqualTo(all.total() > 2); + } + + @Test + void allowingNamespacesTakesEffectWhilePairsAreReused() throws ErrorResultException { + var target = persistNamespacePair(50_000, 0); + var lookalike = repositories.findNamespace(namespacePairOf(target, false).lookalike().name()); + + service.allowNamespaces( + namespaceAllowRequest(lookalike, repositories.findNamespace(target), "Same publisher"), + admin); + em.flush(); + var afterAllow = service.findNamespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS, 0, 100_000); + + assertThat(targets(afterAllow)).doesNotContain(target); + assertThat(service.findNamespaceAllowlist(0, 100).allows()) + .filteredOn(allow -> allow.namespace().equals(lookalike.getName())) + .singleElement() + .satisfies(allow -> { + assertThat(allow.otherNamespace()).isEqualTo(target); + assertThat(allow.reason()).isEqualTo("Same publisher"); + assertThat(allow.decidedBy()).isEqualTo(admin.getLoginName()); + }); + + var allowId = service.findNamespaceAllowlist(0, 100).allows().stream() + .filter(allow -> allow.namespace().equals(lookalike.getName())) + .findFirst() + .orElseThrow() + .id(); + service.removeAllow(allowId, admin); + em.flush(); + var afterRemove = service.findNamespacePairs(false, NameSquattingService.NamespaceSort.DOWNLOADS, 0, 100_000); + + assertThat(targets(afterRemove)).contains(target); + } + + @Test + void allowingNamespacesTwiceKeepsOneAllowAndLeavesTheExtensionAllowlistAlone() throws ErrorResultException { + var target = persistNamespacePair(50_000, 0); + var lookalike = repositories.findNamespace(namespacePairOf(target, false).lookalike().name()); + var targetNamespace = repositories.findNamespace(target); + + service.allowNamespaces(namespaceAllowRequest(lookalike, targetNamespace, null), admin); + em.flush(); + var again = service.allowNamespaces(namespaceAllowRequest(targetNamespace, lookalike, null), admin); + em.flush(); + + assertThat(again.getSuccess()).startsWith("Already allowed"); + assertThat(service.findNamespaceAllowlist(0, 100).allows()) + .filteredOn(allow -> allow.otherNamespace().equals(target)) + .hasSize(1); + assertThat(service.findAllowlist(0, 100).groups()) + .noneMatch(group -> group.extension().namespace().equals(target)); + } + + @Test + void refusesToAllowNamespacesThatAreUnknownTheSameOrUnalike() { + var namespace = persistNamespace(word() + "xy"); + var unrelated = persistNamespace(word() + "xy"); + em.flush(); + + assertStatus( + () -> service.allowNamespaces(namespaceAllowRequest(namespace, unrelated, null), admin), + HttpStatus.BAD_REQUEST); + assertStatus( + () -> service.allowNamespaces(namespaceAllowRequest(namespace, namespace, null), admin), + HttpStatus.BAD_REQUEST); + assertStatus( + () -> service.allowNamespaces( + new NameSquattingJson.NamespaceAllowRequest(namespace.getName(), "missing" + word(), null), + admin), + HttpStatus.NOT_FOUND); + } + + private NameSquattingJson.NamespacePairs namespacePairs( + boolean popularOnly, + NameSquattingService.NamespaceSort sort + ) throws ErrorResultException { + em.flush(); + service.forgetNamespacePairs(); + return service.findNamespacePairs(popularOnly, sort, 0, 100_000); + } + + private NameSquattingJson.NamespacePair namespacePairOf(Namespace target, Namespace lookalike, boolean popularOnly) + throws ErrorResultException { + return namespacePairs(popularOnly, NameSquattingService.NamespaceSort.DOWNLOADS).pairs().stream() + .filter(pair -> pair.target().name().equals(target.getName())) + .filter(pair -> pair.lookalike().name().equals(lookalike.getName())) + .findFirst() + .orElseThrow( + () -> new AssertionError("no pair of " + target.getName() + " and " + lookalike.getName())); + } + + private NameSquattingJson.NamespacePair namespacePairOf(String target, boolean popularOnly) + throws ErrorResultException { + return namespacePairs(popularOnly, NameSquattingService.NamespaceSort.DOWNLOADS).pairs().stream() + .filter(pair -> pair.target().name().equals(target)) + .findFirst() + .orElseThrow(() -> new AssertionError("no pair with target " + target)); + } + + private static List targets(NameSquattingJson.NamespacePairs pairs) { + return pairs.pairs().stream().map(pair -> pair.target().name()).toList(); + } + + /** Two namespaces one edit apart, the target published early; returns the target's name. */ + private String persistNamespacePair(int targetDownloads, int lookalikeDownloads) { + return persistNamespacePair(targetDownloads, lookalikeDownloads, LATE); + } + + private String persistNamespacePair(int targetDownloads, int lookalikeDownloads, LocalDateTime lookalikePublished) { + var name = word() + "xy"; + var target = persistNamespace(name); + persistNamespaceExtension(target, targetDownloads, EARLY); + var lookalike = persistNamespace(oneEditFrom(name)); + if (lookalikeDownloads > 0) { + persistNamespaceExtension(lookalike, lookalikeDownloads, lookalikePublished); + } + return name; + } + + private Namespace persistNamespace(String name) { + var namespace = new Namespace(); + namespace.setName(name); + namespace.setPublicId(UUID.randomUUID().toString()); + em.persist(namespace); + return namespace; + } + + private void persistNamespaceExtension(Namespace namespace, int downloads, LocalDateTime publishedDate) { + var extension = new Extension(); + extension.setName("ext" + word()); + extension.setNamespace(namespace); + extension.setPublicId(UUID.randomUUID().toString()); + extension.setActive(true); + extension.setDownloadCount(downloads); + extension.setPublishedDate(publishedDate); + em.persist(extension); + } + + /** The name with its first letter swapped for a digit. */ + private static String oneEditFrom(String name) { + return ThreadLocalRandom.current().nextInt(10) + name.substring(1); + } + + private static NameSquattingJson.NamespaceAllowRequest namespaceAllowRequest( + Namespace lookalike, + Namespace other, + @Nullable String reason + ) { + return new NameSquattingJson.NamespaceAllowRequest(lookalike.getName(), other.getName(), reason); + } + + private static void assertStatus(ThrowingCallable call, HttpStatus status) { + assertThatThrownBy(call).isInstanceOfSatisfying( + ErrorResultException.class, + exc -> assertThat(exc.getStatus()).isEqualTo(status)); + } + + private NameSquattingJson.Group groupOf(Extension anchor) throws ErrorResultException { + em.flush(); + return service.findCollisions(0, 100).groups().stream() + .filter(group -> group.anchor().name().equals(anchor.getName())) + .findFirst() + .orElseThrow(() -> new AssertionError("no group for " + anchor.getName())); + } + + private NameSquattingJson.AllowlistGroup allowlistGroupOf(Extension extension) { + return service.findAllowlist(0, 100).groups().stream() + .filter(group -> group.extension().name().equals(extension.getName())) + .findFirst() + .orElseThrow(() -> new AssertionError("no allowlist group for " + extension.getName())); + } + + private static List lookalikeNames(NameSquattingJson.Collisions collisions) { + return collisions.groups().stream() + .flatMap(group -> group.lookalikes().stream()) + .map(found -> found.extension().name()) + .toList(); + } + + private static NameSquattingJson.AllowRequest allowRequest( + Extension lookalike, + Extension other, + @Nullable String reason + ) { + return new NameSquattingJson.AllowRequest( + lookalike.getNamespace().getName(), + lookalike.getName(), + other.getNamespace().getName(), + other.getName(), + reason); + } + + /** Records a NAME_SIMILARITY flag on a scan of the extension, as the publish check would. */ + private void flag(Extension extension, LocalDateTime detectedAt) { + var scan = new ExtensionScan(); + scan.setNamespaceName(extension.getNamespace().getName()); + scan.setExtensionName(extension.getName()); + scan.setExtensionVersion("1.0.0"); + scan.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL); + scan.setUniversalTargetPlatform(true); + scan.setPublisher("name-squatting-publisher"); + scan.setStartedAt(detectedAt); + scan.setStatus(ScanStatus.PASSED); + em.persist(scan); + + var failure = new ExtensionValidationFailure(); + failure.setScan(scan); + failure.setCheckType(NameSimilarityCheckService.CHECK_TYPE); + failure.setRuleName("DISPLAY_NAME"); + failure.setValidationFailureReason("flagged by the test"); + failure.setEnforced(false); + failure.setDetectedAt(detectedAt); + em.persist(failure); + } + + /** An extension in a namespace of its own, so every pair a test makes spans two namespaces. */ + private Extension persistExtension(String displayName, LocalDateTime publishedDate) { + var namespace = new Namespace(); + namespace.setName("ns" + word()); + namespace.setPublicId(UUID.randomUUID().toString()); + em.persist(namespace); + + var extension = new Extension(); + extension.setName("ext" + word()); + extension.setNamespace(namespace); + extension.setPublicId(UUID.randomUUID().toString()); + extension.setActive(true); + extension.setPublishedDate(publishedDate); + em.persist(extension); + persistVersion(extension, "1.0.0", displayName); + return extension; + } + + private void persistVersion(Extension extension, String version, String displayName) { + var extVersion = new ExtensionVersion(); + extVersion.setVersion(version); + extVersion.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL); + extVersion.setExtension(extension); + extVersion.setPublishedBy(admin); + extVersion.setActive(true); + extVersion.setDisplayName(displayName); + extVersion.setTimestamp(extension.getPublishedDate()); + em.persist(extVersion); + extension.getVersions().add(extVersion); + } + + /** Eight random letters: their trigrams are as good as unique within the shared database. */ + private static String word() { + var random = ThreadLocalRandom.current(); + var word = new StringBuilder(); + for (var i = 0; i < 8; i++) { + word.append((char) ('a' + random.nextInt(26))); + } + return word.toString(); + } +} diff --git a/server/src/test/java/org/eclipse/openvsx/repositories/JooqOnlyTestConfig.java b/server/src/test/java/org/eclipse/openvsx/repositories/JooqOnlyTestConfig.java index 94fed84a4..7ad8403fd 100644 --- a/server/src/test/java/org/eclipse/openvsx/repositories/JooqOnlyTestConfig.java +++ b/server/src/test/java/org/eclipse/openvsx/repositories/JooqOnlyTestConfig.java @@ -48,6 +48,14 @@ } ) @EntityScan("org.eclipse.openvsx.entities") -@Import({ ExtensionVersionJooqRepository.class, ExtensionJooqRepository.class, UserDataJooqRepository.class }) +@Import( + { + ExtensionVersionJooqRepository.class, + ExtensionJooqRepository.class, + UserDataJooqRepository.class, + NameSimilarityJooqRepository.class, + NamespaceSimilarityJooqRepository.class + } +) public class JooqOnlyTestConfig { } diff --git a/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepositoryTest.java b/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepositoryTest.java new file mode 100644 index 000000000..d30748eae --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityAllowRepositoryTest.java @@ -0,0 +1,224 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.time.LocalDateTime; +import java.util.List; +import java.util.UUID; + +import jakarta.persistence.EntityManager; +import jakarta.persistence.PersistenceException; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.domain.PageRequest; +import org.springframework.transaction.annotation.Transactional; + +import org.eclipse.openvsx.AbstractPostgresContainerTest; +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.NameSimilarityAllow; +import org.eclipse.openvsx.entities.NameSimilarityField; +import org.eclipse.openvsx.entities.Namespace; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.util.TimeUtil; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +@Tag("integration") +@SpringBootTest +@Transactional +class NameSimilarityAllowRepositoryTest extends AbstractPostgresContainerTest { + + @Autowired + EntityManager em; + + @Autowired + NameSimilarityAllowRepository allows; + + @Test + void findsThePairWhicheverWayRoundItIsAsked() { + var lookalike = persistExtension(); + var original = persistExtension(); + var allow = allows.save(allow(lookalike, original, null)); + + assertThat(allows.findPair(lookalike.getId(), original.getId())).contains(allow); + assertThat(allows.findPair(original.getId(), lookalike.getId())).contains(allow); + assertThat(allows.findPair(lookalike.getId(), persistExtension().getId())).isEmpty(); + } + + @Test + void storesAPairOnlyOnceWhicheverWayRoundItIsAllowed() { + var lookalike = persistExtension(); + var original = persistExtension(); + allows.save(allow(lookalike, original, null)); + em.flush(); + + allows.save(allow(original, lookalike, null)); + assertThatThrownBy(em::flush).isInstanceOf(PersistenceException.class); + } + + @Test + void findsAllowsInvolvingAnExtensionOnEitherSide() { + var subject = persistExtension(); + var asLookalike = allows.save(allow(subject, persistExtension(), null)); + var asOriginal = allows.save(allow(persistExtension(), subject, null)); + allows.save(allow(persistExtension(), persistExtension(), null)); + + assertThat(allows.findInvolving(List.of(subject.getId()))).containsExactlyInAnyOrder(asLookalike, asOriginal); + } + + @Test + void goesAwayWithEitherExtension() { + var lookalike = persistExtension(); + var original = persistExtension(); + var allow = allows.save(allow(lookalike, original, null)); + em.flush(); + + em.createNativeQuery("DELETE FROM extension WHERE id = :id").setParameter("id", original.getId()) + .executeUpdate(); + em.clear(); + + assertThat(allows.findById(allow.getId())).isEmpty(); + } + + @Test + void outlivesTheAdminWhoAllowedIt() { + var admin = new UserData(); + admin.setLoginName("name-similarity-admin-" + UUID.randomUUID()); + admin.setProvider("github"); + em.persist(admin); + var allow = allows.save(allow(persistExtension(), persistExtension(), admin.getId())); + em.flush(); + + em.createNativeQuery("DELETE FROM user_data WHERE id = :id").setParameter("id", admin.getId()).executeUpdate(); + em.clear(); + + assertThat(allows.findById(allow.getId())) + .hasValueSatisfying(kept -> assertThat(kept.getDecidedById()).isNull()); + } + + @Test + void findsTheNamespacePairWhicheverWayRoundItIsAsked() { + var lookalike = persistNamespace(); + var original = persistNamespace(); + var allow = allows.save(namespaceAllow(lookalike, original)); + + assertThat(allows.findNamespacePair(lookalike.getId(), original.getId())).contains(allow); + assertThat(allows.findNamespacePair(original.getId(), lookalike.getId())).contains(allow); + assertThat(allows.findNamespacePair(lookalike.getId(), persistNamespace().getId())).isEmpty(); + } + + @Test + void storesANamespacePairOnlyOnceWhicheverWayRoundItIsAllowed() { + var lookalike = persistNamespace(); + var original = persistNamespace(); + allows.save(namespaceAllow(lookalike, original)); + em.flush(); + + allows.save(namespaceAllow(original, lookalike)); + assertThatThrownBy(em::flush).isInstanceOf(PersistenceException.class); + } + + @Test + void namespaceAllowGoesAwayWithEitherNamespace() { + var lookalike = persistNamespace(); + var original = persistNamespace(); + var allow = allows.save(namespaceAllow(lookalike, original)); + em.flush(); + + em.createNativeQuery("DELETE FROM namespace WHERE id = :id").setParameter("id", lookalike.getId()) + .executeUpdate(); + em.clear(); + + assertThat(allows.findById(allow.getId())).isEmpty(); + } + + @Test + void onlyANamespacePairHasTheNamespaceField() { + var extensionPair = allow(persistExtension(), persistExtension(), null); + extensionPair.setField(NameSimilarityField.NAMESPACE); + allows.save(extensionPair); + assertThatThrownBy(em::flush).isInstanceOf(PersistenceException.class); + } + + @Test + void aNamespacePairHasNoExtensions() { + var mixed = namespaceAllow(persistNamespace(), persistNamespace()); + mixed.setExtensionId(persistExtension().getId()); + allows.save(mixed); + assertThatThrownBy(em::flush).isInstanceOf(PersistenceException.class); + } + + @Test + void allowedExtensionsLeaveOutNamespacePairs() { + // Later than anything another test stores, so it would lead the list. + var namespacePair = namespaceAllow(persistNamespace(), persistNamespace()); + namespacePair.setDecidedAt(LocalDateTime.of(2999, 1, 1, 0, 0)); + allows.save(namespacePair); + var extensionPair = allows.save(allow(persistExtension(), persistExtension(), null)); + extensionPair.setDecidedAt(LocalDateTime.of(2998, 1, 1, 0, 0)); + em.flush(); + + assertThat(allows.findAllowedExtensionIds(PageRequest.of(0, 1))) + .containsExactly(extensionPair.getExtensionId()); + } + + private static NameSimilarityAllow namespaceAllow(Namespace lookalike, Namespace original) { + var allow = new NameSimilarityAllow(); + allow.setNamespaceId(lookalike.getId()); + allow.setOtherNamespaceId(original.getId()); + allow.setField(NameSimilarityField.NAMESPACE); + allow.setSimilarity(0.5f); + allow.setLookalikeValue(lookalike.getName()); + allow.setOtherValue(original.getName()); + allow.setReason("Same publisher"); + allow.setDecidedAt(TimeUtil.getCurrentUTC()); + return allow; + } + + private static NameSimilarityAllow allow(Extension lookalike, Extension original, @Nullable Long decidedById) { + var allow = new NameSimilarityAllow(); + allow.setExtensionId(lookalike.getId()); + allow.setOtherExtensionId(original.getId()); + allow.setField(NameSimilarityField.DISPLAY_NAME); + allow.setSimilarity(0.8f); + allow.setLookalikeValue("Python Tools"); + allow.setOtherValue("Python"); + allow.setReason("Official fork"); + allow.setDecidedById(decidedById); + allow.setDecidedAt(TimeUtil.getCurrentUTC()); + return allow; + } + + /** Unique per call: every context shares one database. */ + private Namespace persistNamespace() { + var namespace = new Namespace(); + namespace.setName("allow-ns-" + UUID.randomUUID()); + namespace.setPublicId(UUID.randomUUID().toString()); + em.persist(namespace); + return namespace; + } + + private Extension persistExtension() { + var namespace = persistNamespace(); + var extension = new Extension(); + extension.setName("allow-ext"); + extension.setNamespace(namespace); + extension.setPublicId(UUID.randomUUID().toString()); + em.persist(extension); + return extension; + } +} diff --git a/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepositoryTest.java b/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepositoryTest.java new file mode 100644 index 000000000..1220fbd61 --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/repositories/NameSimilarityJooqRepositoryTest.java @@ -0,0 +1,518 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; +import java.util.Locale; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; +import java.util.stream.Collectors; + +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.jspecify.annotations.Nullable; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.core.io.ClassPathResource; + +import org.eclipse.openvsx.AbstractPostgresContainerTest; +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.ExtensionScan; +import org.eclipse.openvsx.entities.ExtensionValidationFailure; +import org.eclipse.openvsx.entities.ExtensionVersion; +import org.eclipse.openvsx.entities.NameSimilarityField; +import org.eclipse.openvsx.entities.Namespace; +import org.eclipse.openvsx.entities.ScanStatus; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Candidate; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Match; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Probe; +import org.eclipse.openvsx.util.TargetPlatform; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Every test class shares one database, and these lookups scan all of it, so fixtures carry random + * words that nothing else contains and assertions only look at the extensions a test created. + */ +@SpringBootTest(classes = JooqOnlyTestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) +@Transactional +class NameSimilarityJooqRepositoryTest extends AbstractPostgresContainerTest { + + private static final LocalDateTime PUBLISHED = LocalDateTime.of(2024, 1, 1, 0, 0); + + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + private static final LocalDateTime FLAGGED = LocalDateTime.of(2026, 10, 1, 12, 0); + + @Autowired + NameSimilarityJooqRepository repo; + + @Autowired + DSLContext dsl; + + @Autowired + EntityManager em; + + private @Nullable UserData publisher; + + @Test + void reportsNearDisplayNameWithItsScore() { + var word = word(); + var existing = persistExtension(namespace(), word + "-formatter", word + " Formatter Pro"); + + var matches = find(probe("other", "x" + word(), word + " Formatter", 0.5f), existing); + + assertThat(matches).singleElement().satisfies(match -> { + assertThat(match.field()).isEqualTo(NameSimilarityField.DISPLAY_NAME); + assertThat(match.value()).isEqualTo(word + " Formatter Pro"); + assertThat(match.probeValue()).isEqualTo(word + " Formatter"); + assertThat(match.exact()).isFalse(); + assertThat(match.similarity()).isEqualTo(sqlSimilarity(word + " formatter pro", word + " formatter")); + assertThat(match.similarity()).isBetween(0.5f, 0.99f); + }); + } + + @Test + void exactDisplayNameIgnoresCaseAndSurroundingUnicodeWhitespace() { + var word = word(); + var existing = persistExtension(namespace(), word, "\u00A0" + word.toUpperCase() + " Tools\u3000"); + + var matches = find(probe("other", "x" + word(), " " + word + " tools", 0.7f), existing); + + assertThat(matches).singleElement().satisfies(match -> { + assertThat(match.exact()).isTrue(); + assertThat(match.similarity()).isEqualTo(1.0f); + }); + } + + @Test + void repeatedWordScoresOneWithoutBeingExact() { + var word = word(); + var existing = persistExtension(namespace(), "x" + word(), word + " " + word); + + var matches = find(probe("other", "x" + word(), word, 0.7f), existing); + + assertThat(matches).singleElement().satisfies(match -> { + assertThat(match.similarity()).isEqualTo(1.0f); + assertThat(match.exact()).isFalse(); + }); + } + + @Test + void neverMatchesWithinTheProbedNamespaceWhateverItsCase() { + var word = word(); + var namespace = namespace(); + var existing = persistExtension(namespace, word, word + " Tools"); + + var matches = find(probe(namespace.getName().toUpperCase(), word, word + " Tools", 0.5f), existing); + + assertThat(matches).isEmpty(); + } + + @Test + void ignoresInactiveExtensionsAndInactiveVersions() { + var word = word(); + var inactiveExtension = persistExtension(namespace(), word + "-one", word + " Tools"); + inactiveExtension.setActive(false); + var inactiveVersion = persistExtension(namespace(), "x" + word(), word + " Tools"); + inactiveVersion.getVersions().getFirst().setActive(false); + + var matches = find(probe("other", "y" + word(), word + " Tools", 0.5f), inactiveExtension, inactiveVersion); + + assertThat(matches).isEmpty(); + } + + @Test + void versionsSharingADisplayNameMatchOnce() { + var word = word(); + var existing = persistExtension(namespace(), "x" + word(), word + " Tools"); + persistVersion(existing, "2.0.0", word + " Tools"); + persistVersion(existing, "3.0.0", word + " TOOLS"); + + var matches = find(probe("other", "y" + word(), word + " Tools", 0.5f), existing); + + assertThat(matches).singleElement().extracting(Match::exact).isEqualTo(true); + } + + @Test + void leavesOutMatchesBelowTheThreshold() { + var word = word(); + var existing = persistExtension(namespace(), "x" + word(), word + " Formatter Pro"); + + var matches = find(probe("other", "y" + word(), word + " Formatter", 0.95f), existing); + + assertThat(matches).isEmpty(); + } + + @Test + void shortNamesOnlyMatchExactly() { + var word = word().substring(0, 3); + var exact = persistExtension(namespace(), word, word.toUpperCase()); + var near = persistExtension(namespace(), word.substring(0, 2), word.substring(0, 2)); + + var matches = find(new Probe("other", word, List.of(word), 0.1f, 0.1f, 4, 50, TIMEOUT), exact, near); + + assertThat(matches).isNotEmpty().allSatisfy(match -> { + assertThat(match.extensionId()).isEqualTo(exact.getId()); + assertThat(match.exact()).isTrue(); + }); + assertThat(matches).extracting(Match::field) + .containsExactlyInAnyOrder(NameSimilarityField.NAME, NameSimilarityField.DISPLAY_NAME); + } + + @Test + void reportsNearExtensionNameWithNamespaceSimilarity() { + var word = word(); + var namespace = persistNamespace("acme" + word); + var existing = persistExtension(namespace, word + "-vscode", "Unrelated " + word()); + + var matches = find(probe("acme" + word + "x", word + "-vscodee", null, 0.5f), existing); + + assertThat(matches).singleElement().satisfies(match -> { + assertThat(match.field()).isEqualTo(NameSimilarityField.NAME); + assertThat(match.value()).isEqualTo(word + "-vscode"); + assertThat(match.exact()).isFalse(); + assertThat(match.similarity()).isEqualTo(sqlSimilarity(word + "-vscode", word + "-vscodee")); + assertThat(match.namespaceSimilarity()).isEqualTo(sqlSimilarity("acme" + word, "acme" + word + "x")); + }); + } + + @Test + void displayNameLookupUsesTheTrigramIndex() { + var probe = probe("other", "x" + word(), word() + " Tools", 0.7f); + NameSimilarityJooqRepository.applyThreshold(dsl, probe); + disablePlansThatBypassTrigramIndexes(); + + var plan = dsl.explain(NameSimilarityJooqRepository.displayNamesQuery(dsl, probe, word() + " Tools")).plan(); + + assertSearchesTrigramIndex(plan, "extension_version_display_name_trgm_idx"); + } + + @Test + void extensionNameLookupUsesTheTrigramIndex() { + var probe = probe("other", "x" + word(), null, 0.7f); + NameSimilarityJooqRepository.applyThreshold(dsl, probe); + disablePlansThatBypassTrigramIndexes(); + + var plan = dsl.explain(NameSimilarityJooqRepository.namesQuery(dsl, probe)).plan(); + + assertSearchesTrigramIndex(plan, "extension_name_trgm_idx"); + } + + @Test + void javaNormalizationAgreesWithTheSqlExpression() { + var samples = new ArrayList(); + for (var c : NameSimilarityJooqRepository.DISPLAY_NAME_TRIM_CHARS.toCharArray()) { + samples.add(c + "Ab\u00A0C" + c + c); + } + samples.add("\tKept Tab\t"); + + for (var sample : samples) { + var sql = dsl.select(NameSimilarityJooqRepository.normalizedDisplayName(DSL.val(sample))) + .fetchOne(0, String.class); + assertThat(NameSimilarityJooqRepository.normalizeDisplayName(sample)) + .as("normalizing %s", sample) + .isEqualTo(sql); + } + } + + @Test + void trimLiteralIsTheOneTheIndexMigrationUses() throws IOException { + var migration = new ClassPathResource("db/migration/V1_87__Name_Similarity_Indexes.sql") + .getContentAsString(StandardCharsets.UTF_8); + + assertThat(migration) + .contains("btrim(display_name, " + NameSimilarityJooqRepository.DISPLAY_NAME_TRIM_LITERAL + ")"); + } + + @Test + void probeRejectsThresholdsOutsideTheUnitInterval() { + assertThatThrownBy(() -> new Probe("ns", "ext", List.of(), 0f, 0.7f, 4, 10, TIMEOUT)) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> new Probe("ns", "ext", List.of(), 0.7f, 1.5f, 4, 10, TIMEOUT)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void probeRejectsATimeoutThatIsNotPositive() { + assertThatThrownBy(() -> new Probe("ns", "ext", List.of(), 0.7f, 0.7f, 4, 10, Duration.ZERO)) + .isInstanceOf(IllegalArgumentException.class); + } + + @Test + void putsTheStatementTimeoutBackAfterALookup() { + dsl.execute("SET LOCAL statement_timeout = '42s'"); + + repo.findSimilar(probe("other", "x" + word(), word() + " Tools", 0.7f)); + + assertThat( + dsl.select(DSL.function("current_setting", String.class, DSL.inline("statement_timeout"))) + .fetchOne(0, String.class)) + .isEqualTo("42s"); + } + + @Test + void listsFlaggedExtensionsByTheirLatestFlagNewestFirst() { + var fixture = flaggedFixture(); + + // One failure per step, so the walk resumes inside a scan and between scans flagged at one instant. + var walked = repo.findCandidates(fixture.checkType(), 0, 100_000, TIMEOUT, 1, 1_000); + + assertThat(ofInterest(walked, fixture)).containsExactly( + new Candidate(fixture.reflagged().getId(), FLAGGED), + new Candidate(fixture.tiedLater().getId(), FLAGGED.minusDays(1)), + new Candidate(fixture.tiedEarlier().getId(), FLAGGED.minusDays(1)), + new Candidate(fixture.manyMatches().getId(), FLAGGED.minusDays(2)), + new Candidate(fixture.otherCase().getId(), FLAGGED.minusDays(4)), + new Candidate(fixture.sharesDisplayName().getId(), null)); + } + + @Test + void walkAndOneGoLookupAgree() { + var fixture = flaggedFixture(); + + var walked = repo.findCandidates(fixture.checkType(), 0, 100_000, TIMEOUT, 1, 1_000); + var inOneGo = repo.findCandidates(fixture.checkType(), 0, 100_000, TIMEOUT, 1, 1); + + assertThat(ofInterest(inOneGo, fixture)).isEqualTo(ofInterest(walked, fixture)).hasSize(6); + } + + @Test + void pagesThroughTheFlaggedExtensions() { + var fixture = flaggedFixture(); + + var page = repo.findCandidates(fixture.checkType(), 1, 2, TIMEOUT, 1, 3); + + assertThat(page).extracting(Candidate::extensionId) + .containsExactly(fixture.tiedLater().getId(), fixture.tiedEarlier().getId()); + } + + @Test + void walkReadsFailuresOffTheirIndex() { + dsl.execute("SET LOCAL enable_seqscan = off"); + dsl.execute("SET LOCAL enable_bitmapscan = off"); + + var plan = dsl.explain( + NameSimilarityJooqRepository.flaggedStepQuery(dsl, "TEST_" + word(), FLAGGED, 42L, 1024)).plan(); + + assertThat(plan).containsPattern("Index (Only )?Scan using extension_validation_failure_type_detected_idx") + .contains("ROW(detected_at, scan_id) <") + .doesNotContain("Sort Key: extension_validation_failure"); + } + + /** + * Extensions flagged by a check type of their own, as the publish check would flag them, plus one + * never flagged whose display name another namespace's extension (the reflagged one) shares. + */ + private FlaggedFixture flaggedFixture() { + var checkType = "TEST_" + word(); + var sharedName = word() + " Tools"; + var reflagged = persistExtension(namespace(), "ext" + word(), sharedName); + var tiedEarlier = persistExtension(namespace(), "ext" + word(), word() + " Tools"); + var tiedLater = persistExtension(namespace(), "ext" + word(), word() + " Tools"); + var manyMatches = persistExtension(namespace(), "ext" + word(), word() + " Tools"); + var otherCase = persistExtension(namespace(), "ext" + word(), word() + " Tools"); + var inactive = persistExtension(namespace(), "ext" + word(), word() + " Tools"); + inactive.setActive(false); + var sharesDisplayName = persistExtension(namespace(), "ext" + word(), sharedName); + + flag(checkType, reflagged, FLAGGED.minusDays(3), 1, false); + flag(checkType, otherCase, FLAGGED.minusDays(4), 1, true); + flag(checkType, manyMatches, FLAGGED.minusDays(2), 3, false); + flag(checkType, tiedEarlier, FLAGGED.minusDays(1), 2, false); + flag(checkType, tiedLater, FLAGGED.minusDays(1), 2, false); + flag(checkType, reflagged, FLAGGED, 1, false); + flag(checkType, inactive, FLAGGED.plusDays(1), 1, false); + em.flush(); + return new FlaggedFixture( + checkType, + reflagged, + tiedEarlier, + tiedLater, + manyMatches, + otherCase, + inactive, + sharesDisplayName); + } + + private record FlaggedFixture( + String checkType, + Extension reflagged, + Extension tiedEarlier, + Extension tiedLater, + Extension manyMatches, + Extension otherCase, + Extension inactive, + Extension sharesDisplayName + ) { + Set ids() { + return Set.of( + reflagged.getId(), + tiedEarlier.getId(), + tiedLater.getId(), + manyMatches.getId(), + otherCase.getId(), + inactive.getId(), + sharesDisplayName.getId()); + } + } + + private static List ofInterest(List candidates, FlaggedFixture fixture) { + return candidates.stream().filter(candidate -> fixture.ids().contains(candidate.extensionId())).toList(); + } + + /** A scan of the extension recording {@code failures} failures of the check type, all at one instant. */ + private void flag(String checkType, Extension extension, LocalDateTime at, int failures, boolean upperCase) { + var scan = new ExtensionScan(); + var namespaceName = extension.getNamespace().getName(); + scan.setNamespaceName(upperCase ? namespaceName.toUpperCase(Locale.ROOT) : namespaceName); + scan.setExtensionName(upperCase ? extension.getName().toUpperCase(Locale.ROOT) : extension.getName()); + scan.setExtensionVersion("1.0.0"); + scan.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL); + scan.setUniversalTargetPlatform(true); + scan.setPublisher("name-similarity-publisher"); + scan.setStartedAt(at); + scan.setStatus(ScanStatus.PASSED); + em.persist(scan); + + for (var i = 0; i < failures; i++) { + var failure = new ExtensionValidationFailure(); + failure.setScan(scan); + failure.setCheckType(checkType); + failure.setRuleName("DISPLAY_NAME"); + failure.setValidationFailureReason("flagged by the test"); + failure.setEnforced(false); + failure.setDetectedAt(at); + em.persist(failure); + } + } + + private List find(Probe probe, Extension... ofInterest) { + em.flush(); + Set ids = Arrays.stream(ofInterest).map(Extension::getId).collect(Collectors.toSet()); + return repo.findSimilar(probe).stream().filter(match -> ids.contains(match.extensionId())).toList(); + } + + private static Probe probe( + String namespaceName, + String extensionName, + @Nullable String displayName, + float threshold + ) { + Collection displayNames = displayName == null ? List.of() : List.of(displayName); + return new Probe(namespaceName, extensionName, displayNames, threshold, threshold, 4, 50, TIMEOUT); + } + + /** + * The fixture tables are nearly empty, so the planner would rather read them whole. The trigram filter + * runs in a step of its own, so with sequential scans off the index is the cheapest way left to read + * it, provided the query's expression matches the index's. + */ + private void disablePlansThatBypassTrigramIndexes() { + dsl.execute("SET LOCAL enable_seqscan = off"); + } + + /** + * The index has to be searched with the % comparison. Merely reading it does not show the expressions + * match: being partial on active, it also stands in for a scan of the active rows, with % left as a + * filter on every one of them. + */ + private static void assertSearchesTrigramIndex(String plan, String index) { + var lines = plan.lines().toList(); + var scan = -1; + for (var i = 0; i < lines.size(); i++) { + if (lines.get(i).contains("Bitmap Index Scan on " + index)) { + scan = i; + } + } + assertThat(scan).as("plan reads %s:%n%s", index, plan).isNotNegative(); + assertThat(lines.get(scan + 1)).as("plan searches %s with %%:%n%s", index, plan) + .contains("Index Cond:") + .contains(" % "); + } + + private float sqlSimilarity(String first, String second) { + return dsl.select(DSL.function("similarity", Float.class, DSL.val(first), DSL.val(second))) + .fetchOne(0, Float.class); + } + + /** Eight random letters: their trigrams are as good as unique within the shared database. */ + private static String word() { + var random = ThreadLocalRandom.current(); + var word = new StringBuilder(); + for (var i = 0; i < 8; i++) { + word.append((char) ('a' + random.nextInt(26))); + } + return word.toString(); + } + + private Namespace namespace() { + return persistNamespace("ns" + word()); + } + + private Namespace persistNamespace(String name) { + var namespace = new Namespace(); + namespace.setName(name); + namespace.setPublicId(UUID.randomUUID().toString()); + em.persist(namespace); + return namespace; + } + + private Extension persistExtension(Namespace namespace, String name, String displayName) { + var extension = new Extension(); + extension.setName(name); + extension.setNamespace(namespace); + extension.setPublicId(UUID.randomUUID().toString()); + extension.setActive(true); + extension.setPublishedDate(PUBLISHED); + em.persist(extension); + persistVersion(extension, "1.0.0", displayName); + return extension; + } + + private void persistVersion(Extension extension, String version, String displayName) { + var extVersion = new ExtensionVersion(); + extVersion.setVersion(version); + extVersion.setTargetPlatform(TargetPlatform.NAME_UNIVERSAL); + extVersion.setExtension(extension); + extVersion.setPublishedBy(publisher()); + extVersion.setActive(true); + extVersion.setDisplayName(displayName); + extVersion.setTimestamp(PUBLISHED); + em.persist(extVersion); + extension.getVersions().add(extVersion); + } + + private UserData publisher() { + if (publisher == null) { + publisher = new UserData(); + publisher.setLoginName("name-similarity-" + word()); + publisher.setProvider("github"); + em.persist(publisher); + } + return publisher; + } +} diff --git a/server/src/test/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepositoryTest.java b/server/src/test/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepositoryTest.java new file mode 100644 index 000000000..cf7b1f8e7 --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/repositories/NamespaceSimilarityJooqRepositoryTest.java @@ -0,0 +1,290 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.repositories; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Optional; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import org.jooq.DSLContext; +import org.jooq.impl.DSL; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import org.eclipse.openvsx.AbstractPostgresContainerTest; +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.Namespace; +import org.eclipse.openvsx.entities.NamespaceMembership; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.repositories.NamespaceSimilarityJooqRepository.Pair; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Every test class shares one database, and the lookup reads all of it, so fixtures carry random words + * that nothing else contains and assertions only look at the namespaces a test created. + */ +@SpringBootTest(classes = JooqOnlyTestConfig.class, webEnvironment = SpringBootTest.WebEnvironment.NONE) +@Transactional +class NamespaceSimilarityJooqRepositoryTest extends AbstractPostgresContainerTest { + + private static final Duration TIMEOUT = Duration.ofSeconds(10); + + @Autowired + NamespaceSimilarityJooqRepository repo; + + @Autowired + DSLContext dsl; + + @Autowired + EntityManager em; + + @Test + void allowedEditsGrowWithTheLongerName() { + assertThat(NamespaceSimilarityJooqRepository.allowedEdits(4)).isZero(); + assertThat(NamespaceSimilarityJooqRepository.allowedEdits(5)).isEqualTo(1); + assertThat(NamespaceSimilarityJooqRepository.allowedEdits(8)).isEqualTo(1); + assertThat(NamespaceSimilarityJooqRepository.allowedEdits(9)).isEqualTo(2); + } + + @Test + void midLengthNamesMatchWithinOneEdit() { + var word = word(8); + var original = withExtension(namespace(word)); + var oneEdit = namespace(replaceAt(word, 3)); + var twoEdits = namespace(replaceAt(replaceAt(word, 3), 6)); + + var pair = pairOf(original, oneEdit); + assertThat(pair).hasValueSatisfying(found -> { + assertThat(found.editDistance()).isEqualTo(1); + assertThat(found.separatorOnly()).isFalse(); + assertThat(found.similarity()).isBetween(0f, 1f); + }); + assertThat(pairOf(original, twoEdits)).isEmpty(); + } + + @Test + void longNamesMatchWithinTwoEdits() { + var word = word(12); + var original = withExtension(namespace(word)); + var twoEdits = namespace(replaceAt(replaceAt(word, 2), 9)); + var threeEdits = namespace(replaceAt(replaceAt(replaceAt(word, 2), 6), 9)); + + assertThat(pairOf(original, twoEdits)) + .hasValueSatisfying(found -> assertThat(found.editDistance()).isEqualTo(2)); + assertThat(pairOf(original, threeEdits)).isEmpty(); + } + + @Test + void comparesNamesIgnoringCase() { + var word = word(8); + var original = withExtension(namespace(word.toUpperCase())); + var lookalike = namespace(replaceAt(word, 0)); + + assertThat(pairOf(original, lookalike)) + .hasValueSatisfying(found -> assertThat(found.editDistance()).isEqualTo(1)); + } + + @Test + void shortNamesOnlyMatchWhenTheyDifferInSeparators() { + var word = word(4); + var original = withExtension(namespace(word)); + var oneEdit = namespace(replaceAt(word, 1)); + var separated = namespace(word.charAt(0) + "-" + word.charAt(1) + "_" + word.charAt(2) + "~" + word.charAt(3)); + + assertThat(pairOf(original, oneEdit)).isEmpty(); + assertThat(pairOf(original, separated)).hasValueSatisfying(found -> { + assertThat(found.separatorOnly()).isTrue(); + assertThat(found.editDistance()).isEqualTo(3); + }); + } + + @Test + void reportsEachPairOnceWithTheLowerIdFirst() { + var word = word(10); + var original = withExtension(namespace(word)); + var lookalike = namespace(replaceAt(word, 4)); + + var pairs = pairsBetween(original, lookalike); + + assertThat(pairs).singleElement().satisfies(pair -> { + assertThat(pair.first().id()).isEqualTo(original.getId()); + assertThat(pair.second().id()).isEqualTo(lookalike.getId()); + assertThat(pair.second().name()).isEqualTo(lookalike.getName()); + }); + } + + @Test + void sumsTheActiveExtensionsOfEachSide() { + var word = word(10); + var original = namespace(word); + persistExtension(original, "one", true, 1500, LocalDateTime.of(2023, 5, 1, 0, 0)); + persistExtension(original, "two", true, 500, LocalDateTime.of(2022, 3, 1, 0, 0)); + persistExtension(original, "gone", false, 100_000, LocalDateTime.of(2020, 1, 1, 0, 0)); + var lookalike = namespace(replaceAt(word, 4)); + + assertThat(pairOf(original, lookalike)).hasValueSatisfying(pair -> { + assertThat(pair.first().downloads()).isEqualTo(2000); + assertThat(pair.first().activeExtensions()).isEqualTo(2); + assertThat(pair.first().firstPublished()).isEqualTo(LocalDateTime.of(2022, 3, 1, 0, 0)); + assertThat(pair.second().downloads()).isZero(); + assertThat(pair.second().activeExtensions()).isZero(); + assertThat(pair.second().firstPublished()).isNull(); + }); + } + + @Test + void leavesOutPairsWithoutAnActiveExtensionOnEitherSide() { + var word = word(10); + var original = namespace(word); + persistExtension(original, "gone", false, 10, LocalDateTime.of(2020, 1, 1, 0, 0)); + var lookalike = namespace(replaceAt(word, 4)); + + assertThat(pairOf(original, lookalike)).isEmpty(); + } + + @Test + void flagsPairsSharingAMember() { + var word = word(10); + var original = withExtension(namespace(word)); + var sibling = namespace(replaceAt(word, 4)); + var stranger = namespace(replaceAt(word, 7)); + var user = persistUser(); + persistMembership(original, user, NamespaceMembership.ROLE_OWNER); + persistMembership(sibling, user, NamespaceMembership.ROLE_CONTRIBUTOR); + persistMembership(stranger, persistUser(), NamespaceMembership.ROLE_OWNER); + + assertThat(pairOf(original, sibling)).hasValueSatisfying(pair -> assertThat(pair.sharedMember()).isTrue()); + assertThat(pairOf(original, stranger)).hasValueSatisfying(pair -> assertThat(pair.sharedMember()).isFalse()); + } + + @Test + void probesTheTrigramIndex() { + NamespaceSimilarityJooqRepository.applyThreshold(dsl); + // The fixture table is nearly empty, so the planner would rather read it whole. + dsl.execute("SET LOCAL enable_seqscan = off"); + + var plan = dsl.explain(NamespaceSimilarityJooqRepository.pairsQuery(dsl)).plan(); + + var lines = plan.lines().toList(); + var scan = -1; + for (var i = 0; i < lines.size(); i++) { + if (lines.get(i).contains("Bitmap Index Scan on namespace_name_trgm_idx")) { + scan = i; + } + } + assertThat(scan).as("plan reads namespace_name_trgm_idx:%n%s", plan).isNotNegative(); + assertThat(lines.get(scan + 1)).as("plan searches the index with %%:%n%s", plan) + .contains("Index Cond:") + .contains(" % "); + } + + @Test + void putsTheStatementTimeoutBackAfterTheLookup() { + dsl.execute("SET LOCAL statement_timeout = '42s'"); + + repo.findSimilarPairs(TIMEOUT); + + assertThat( + dsl.select(DSL.function("current_setting", String.class, DSL.inline("statement_timeout"))) + .fetchOne(0, String.class)) + .isEqualTo("42s"); + } + + @Test + void rejectsATimeoutThatIsNotPositive() { + assertThatThrownBy(() -> repo.findSimilarPairs(Duration.ZERO)).isInstanceOf(IllegalArgumentException.class); + } + + private Optional pairOf(Namespace first, Namespace second) { + var pairs = pairsBetween(first, second); + assertThat(pairs).hasSizeLessThanOrEqualTo(1); + return pairs.stream().findFirst(); + } + + private List pairsBetween(Namespace first, Namespace second) { + em.flush(); + var ids = List.of(first.getId(), second.getId()); + return repo.findSimilarPairs(TIMEOUT).stream() + .filter(pair -> ids.contains(pair.first().id()) && ids.contains(pair.second().id())) + .toList(); + } + + /** Random lowercase letters: as good as unique within the shared database from 8 on. */ + private static String word(int length) { + var random = ThreadLocalRandom.current(); + var word = new StringBuilder(); + for (var i = 0; i < length; i++) { + word.append((char) ('a' + random.nextInt(26))); + } + return word.toString(); + } + + /** {@code word} with the letter at {@code index} swapped for a digit, so it is one edit away. */ + private static String replaceAt(String word, int index) { + return word.substring(0, index) + ThreadLocalRandom.current().nextInt(10) + word.substring(index + 1); + } + + private Namespace namespace(String name) { + var namespace = new Namespace(); + namespace.setName(name); + namespace.setPublicId(UUID.randomUUID().toString()); + em.persist(namespace); + return namespace; + } + + private Namespace withExtension(Namespace namespace) { + persistExtension(namespace, "ext", true, 0, LocalDateTime.of(2024, 1, 1, 0, 0)); + return namespace; + } + + private void persistExtension( + Namespace namespace, + String name, + boolean active, + int downloads, + LocalDateTime published + ) { + var extension = new Extension(); + extension.setName(name); + extension.setNamespace(namespace); + extension.setPublicId(UUID.randomUUID().toString()); + extension.setActive(active); + extension.setDownloadCount(downloads); + extension.setPublishedDate(published); + em.persist(extension); + } + + private UserData persistUser() { + var user = new UserData(); + user.setLoginName("namespace-similarity-" + word(8)); + user.setProvider("github"); + em.persist(user); + return user; + } + + private void persistMembership(Namespace namespace, UserData user, String role) { + var membership = new NamespaceMembership(); + membership.setNamespace(namespace); + membership.setUser(user); + membership.setRole(role); + em.persist(membership); + } +} diff --git a/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfigTest.java b/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfigTest.java new file mode 100644 index 000000000..c35dc48b2 --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckConfigTest.java @@ -0,0 +1,89 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.scanning; + +import java.time.Duration; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.boot.convert.ApplicationConversionService; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; + +import static org.assertj.core.api.Assertions.assertThat; + +class NameSimilarityCheckConfigTest { + + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withInitializer( + context -> context.getBeanFactory() + .setConversionService(ApplicationConversionService.getSharedInstance())) + .withUserConfiguration(NameSimilarityCheckConfig.class); + + @Test + void defaults() { + runner.run(context -> { + var config = context.getBean(NameSimilarityCheckConfig.class); + assertThat(config.isEnabled()).isTrue(); + assertThat(config.getNameThreshold()).isEqualTo(0.7f); + assertThat(config.getDisplayNameThreshold()).isEqualTo(0.7f); + assertThat(config.getMinFuzzyLength()).isEqualTo(4); + assertThat(config.getMaxMatches()).isEqualTo(10); + assertThat(config.getStatementTimeout()).isEqualTo(Duration.ofSeconds(10)); + assertThat(config.getPopularNamespaceDownloads()).isEqualTo(10_000); + assertThat(config.getPopularNamespaceRatio()).isEqualTo(10); + }); + } + + @Test + void bindsTheProperties() { + runner.withPropertyValues( + "ovsx.scanning.name-similarity.enabled=false", + "ovsx.scanning.name-similarity.name-threshold=0.8", + "ovsx.scanning.name-similarity.display-name-threshold=1", + "ovsx.scanning.name-similarity.min-fuzzy-length=3", + "ovsx.scanning.name-similarity.max-matches=5", + "ovsx.scanning.name-similarity.statement-timeout=2s", + "ovsx.scanning.name-similarity.popular-namespace-downloads=0", + "ovsx.scanning.name-similarity.popular-namespace-ratio=2.5") + .run(context -> { + var config = context.getBean(NameSimilarityCheckConfig.class); + assertThat(config.isEnabled()).isFalse(); + assertThat(config.getNameThreshold()).isEqualTo(0.8f); + assertThat(config.getDisplayNameThreshold()).isEqualTo(1f); + assertThat(config.getMinFuzzyLength()).isEqualTo(3); + assertThat(config.getMaxMatches()).isEqualTo(5); + assertThat(config.getStatementTimeout()).isEqualTo(Duration.ofSeconds(2)); + assertThat(config.getPopularNamespaceDownloads()).isZero(); + assertThat(config.getPopularNamespaceRatio()).isEqualTo(2.5); + }); + } + + @ParameterizedTest + @ValueSource( + strings = { + "ovsx.scanning.name-similarity.name-threshold=0", + "ovsx.scanning.name-similarity.name-threshold=1.1", + "ovsx.scanning.name-similarity.display-name-threshold=-0.5", + "ovsx.scanning.name-similarity.min-fuzzy-length=0", + "ovsx.scanning.name-similarity.max-matches=0", + "ovsx.scanning.name-similarity.statement-timeout=0s", + "ovsx.scanning.name-similarity.popular-namespace-downloads=-1", + "ovsx.scanning.name-similarity.popular-namespace-ratio=0.5", + "ovsx.scanning.name-similarity.popular-namespace-ratio=NaN" + } + ) + void refusesToStartWithAnInvalidValue(String property) { + runner.withPropertyValues(property).run(context -> assertThat(context).hasFailed()); + } +} diff --git a/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckServiceTest.java b/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckServiceTest.java new file mode 100644 index 000000000..621e222df --- /dev/null +++ b/server/src/test/java/org/eclipse/openvsx/scanning/NameSimilarityCheckServiceTest.java @@ -0,0 +1,171 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ +package org.eclipse.openvsx.scanning; + +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; + +import org.eclipse.openvsx.entities.Extension; +import org.eclipse.openvsx.entities.ExtensionScan; +import org.eclipse.openvsx.entities.NameSimilarityAllow; +import org.eclipse.openvsx.entities.NameSimilarityField; +import org.eclipse.openvsx.entities.UserData; +import org.eclipse.openvsx.repositories.NameSimilarityAllowRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Match; +import org.eclipse.openvsx.repositories.NameSimilarityJooqRepository.Probe; +import org.eclipse.openvsx.repositories.RepositoryService; +import org.eclipse.openvsx.util.TempFile; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class NameSimilarityCheckServiceTest { + + private final NameSimilarityCheckConfig config = mock(NameSimilarityCheckConfig.class); + private final NameSimilarityJooqRepository similarity = mock(NameSimilarityJooqRepository.class); + private final NameSimilarityAllowRepository allows = mock(NameSimilarityAllowRepository.class); + private final RepositoryService repositories = mock(RepositoryService.class); + private final NameSimilarityCheckService check = new NameSimilarityCheckService( + config, + similarity, + allows, + repositories); + + @BeforeEach + void configure() { + when(config.isEnabled()).thenReturn(true); + when(config.getNameThreshold()).thenReturn(0.7f); + when(config.getDisplayNameThreshold()).thenReturn(0.6f); + when(config.getMinFuzzyLength()).thenReturn(4); + when(config.getMaxMatches()).thenReturn(10); + when(config.getStatementTimeout()).thenReturn(Duration.ofSeconds(10)); + } + + @Test + void neverBlocksPublication() { + assertThat(check.isEnforced()).isFalse(); + assertThat(check.isRequired()).isFalse(); + assertThat(check.getCheckType()).isEqualTo("NAME_SIMILARITY"); + } + + @Test + void passesWithoutMatches() { + when(similarity.findSimilar(any())).thenReturn(List.of()); + + assertThat(check.check(context("pythonn-tools", "python", "Python")).passed()).isTrue(); + } + + @Test + void probesTheScannedNamesWithTheConfiguredThresholds() { + when(similarity.findSimilar(any())).thenReturn(List.of()); + + check.check(context("pythonn-tools", "python", "Python Tools")); + + var probe = ArgumentCaptor.forClass(Probe.class); + verify(similarity).findSimilar(probe.capture()); + assertThat(probe.getValue()).isEqualTo( + new Probe( + "pythonn-tools", + "python", + List.of("Python Tools"), + 0.7f, + 0.6f, + 4, + 10, + Duration.ofSeconds(10))); + } + + @Test + void leavesOutTheDisplayNameTheScanFellBackTo() { + when(similarity.findSimilar(any())).thenReturn(List.of()); + + check.check(context("pythonn-tools", "python", "python")); + + var probe = ArgumentCaptor.forClass(Probe.class); + verify(similarity).findSimilar(probe.capture()); + assertThat(probe.getValue().displayNames()).isEmpty(); + } + + @Test + void flagsEachMatchedExtensionOnceWithItsClosestMatch() { + when(similarity.findSimilar(any())).thenReturn( + List.of( + match(1, NameSimilarityField.NAME, "python", "python", 1f, true), + match(1, NameSimilarityField.DISPLAY_NAME, "Python", "Pythom", 0.56f, false), + match(2, NameSimilarityField.DISPLAY_NAME, "Pythonic", "Pythom", 0.72f, false))); + + var result = check.check(context("pyext-labs", "python", "Pythom")); + + assertThat(result.passed()).isFalse(); + assertThat(result.failures()).containsExactly( + new PublishCheck.Failure("NAME", "Extension name \"python\" is also used by ns1.ext1"), + new PublishCheck.Failure( + "DISPLAY_NAME", + "Display name \"Pythom\" resembles ns2.ext2 (\"Pythonic\", 72% similar)")); + } + + @Test + void leavesOutExtensionsAllowedAlongsideAnExistingExtension() { + var existing = mock(Extension.class); + when(existing.getId()).thenReturn(99L); + when(repositories.findExtension("python", "pyext-labs")).thenReturn(existing); + var allow = new NameSimilarityAllow(); + allow.setExtensionId(1L); + allow.setOtherExtensionId(99L); + when(allows.findInvolving(List.of(99L))).thenReturn(List.of(allow)); + when(similarity.findSimilar(any())).thenReturn( + List.of( + match(1, NameSimilarityField.NAME, "python", "python", 1f, true))); + + assertThat(check.check(context("pyext-labs", "python", "Pythom")).passed()).isTrue(); + } + + private static PublishCheck.Context context(String namespace, String name, String displayName) { + var scan = new ExtensionScan(); + scan.setNamespaceName(namespace); + scan.setExtensionName(name); + scan.setExtensionDisplayName(displayName); + return new PublishCheck.Context(scan, mock(TempFile.class), new UserData()); + } + + private static Match match( + long id, + NameSimilarityField field, + String value, + String probeValue, + float similarity, + boolean exact + ) { + return new Match( + id, + "ns" + id, + "ext" + id, + field, + value, + probeValue, + similarity, + exact, + 0.2f, + LocalDateTime.of(2020, 1, 1, 0, 0), + 100); + } +} diff --git a/webui/CHANGELOG.md b/webui/CHANGELOG.md index 9d3d329c0..6763f39ef 100644 --- a/webui/CHANGELOG.md +++ b/webui/CHANGELOG.md @@ -2,6 +2,13 @@ This change log covers only the frontend library (webui) of Open VSX. +## [next] (unreleased) + +### Added + +- A Name Squatting admin page, for `manage_extensions`, lists extensions in different namespaces whose name or display name resemble each other, grouped under the one published first, to allow the selected pairs or delete either extension (published first is not proof of being the original), and an allowlist of the allowed pairs; `ExtensionRegistryService.admin` gains `getNameSquattingCollisions`, `getNameSquattingAllowlist`, `allowNameSquattingPair` and `removeNameSquattingAllow` +- A Namespaces tab on the Name Squatting page lists namespaces whose names differ by a typo or only in separators, popular targets first with the option to review every pair, to allow the selected pairs; the Allowlist tab lists allowed namespace pairs too. `ExtensionRegistryService.admin` gains `getNameSquattingNamespacePairs`, `getNameSquattingNamespaceAllowlist` and `allowNameSquattingNamespaces` + ## [1.4.0] - 2026-11-09 ### Added diff --git a/webui/src/extension-registry-service.ts b/webui/src/extension-registry-service.ts index 0680cbbf4..c6e166fb8 100644 --- a/webui/src/extension-registry-service.ts +++ b/webui/src/extension-registry-service.ts @@ -43,6 +43,13 @@ import { FileDecisionDeleteResponse, SizeOverride, SizeOverrideList, + NameSquattingAllowlist, + NameSquattingAllowRequest, + NameSquattingCollisions, + NameSquattingNamespaceAllowlist, + NameSquattingNamespaceAllowRequest, + NameSquattingNamespacePairs, + NameSquattingNamespaceSort, LogPageableList, Settings, SiteSettings, @@ -663,6 +670,34 @@ export interface AdminService { createSizeOverride(override: SizeOverride): Promise>; updateSizeOverride(id: number, override: SizeOverride): Promise>; deleteSizeOverride(id: number): Promise>; + /** Looks the name squatting candidates up again, `size` at a time from `offset`; `nextOffset` continues. */ + getNameSquattingCollisions( + signal: AbortSignal, + offset: number, + size: number + ): Promise>; + getNameSquattingAllowlist( + signal: AbortSignal, + page: number, + size: number + ): Promise>; + allowNameSquattingPair(request: NameSquattingAllowRequest): Promise>; + /** Removes an allowed pair of extensions or of namespaces. */ + removeNameSquattingAllow(id: number): Promise>; + /** Namespace pairs from `offset`; the server reuses its lookup for up to a minute. */ + getNameSquattingNamespacePairs( + signal: AbortSignal, + popularOnly: boolean, + sort: NameSquattingNamespaceSort, + offset: number, + size: number + ): Promise>; + getNameSquattingNamespaceAllowlist( + signal: AbortSignal, + page: number, + size: number + ): Promise>; + allowNameSquattingNamespaces(request: NameSquattingNamespaceAllowRequest): Promise>; getLogs(signal: AbortSignal, page?: number, size?: number, period?: string): Promise>; getSettings(signal: AbortSignal): Promise>; updateSettings(settings: Partial): Promise>; @@ -1192,6 +1227,132 @@ export class AdminServiceImpl implements AdminService { }); } + async getNameSquattingCollisions( + signal: AbortSignal, + offset: number, + size: number + ): Promise> { + return sendRequest({ + signal, + credentials: true, + endpoint: createAbsoluteURL( + [this.registry.serverUrl, 'admin', 'name-squatting', 'collisions'], + [ + { key: 'offset', value: offset }, + { key: 'size', value: size } + ] + ) + }); + } + + async getNameSquattingAllowlist( + signal: AbortSignal, + page: number, + size: number + ): Promise> { + return sendRequest({ + signal, + credentials: true, + endpoint: createAbsoluteURL( + [this.registry.serverUrl, 'admin', 'name-squatting', 'allowlist'], + [ + { key: 'page', value: page }, + { key: 'size', value: size } + ] + ) + }); + } + + async allowNameSquattingPair(request: NameSquattingAllowRequest): Promise> { + const csrfToken = await this.registry.getCsrfToken(); + const headers: Record = { + 'Content-Type': 'application/json;charset=UTF-8' + }; + headers[csrfToken.header] = csrfToken.value; + return sendRequest({ + method: 'POST', + payload: request, + credentials: true, + endpoint: createAbsoluteURL([this.registry.serverUrl, 'admin', 'name-squatting', 'allowlist']), + headers + }); + } + + async removeNameSquattingAllow(id: number): Promise> { + const csrfToken = await this.registry.getCsrfToken(); + const headers: Record = { + 'Content-Type': 'application/json;charset=UTF-8' + }; + headers[csrfToken.header] = csrfToken.value; + return sendRequest({ + method: 'DELETE', + credentials: true, + endpoint: createAbsoluteURL([this.registry.serverUrl, 'admin', 'name-squatting', 'allowlist', String(id)]), + headers + }); + } + + async getNameSquattingNamespacePairs( + signal: AbortSignal, + popularOnly: boolean, + sort: NameSquattingNamespaceSort, + offset: number, + size: number + ): Promise> { + return sendRequest({ + signal, + credentials: true, + endpoint: createAbsoluteURL( + [this.registry.serverUrl, 'admin', 'name-squatting', 'namespaces'], + [ + { key: 'popularOnly', value: String(popularOnly) }, + { key: 'sort', value: sort }, + { key: 'offset', value: offset }, + { key: 'size', value: size } + ] + ) + }); + } + + async getNameSquattingNamespaceAllowlist( + signal: AbortSignal, + page: number, + size: number + ): Promise> { + return sendRequest({ + signal, + credentials: true, + endpoint: createAbsoluteURL( + [this.registry.serverUrl, 'admin', 'name-squatting', 'namespaces', 'allowlist'], + [ + { key: 'page', value: page }, + { key: 'size', value: size } + ] + ) + }); + } + + async allowNameSquattingNamespaces(request: NameSquattingNamespaceAllowRequest): Promise> { + const csrfToken = await this.registry.getCsrfToken(); + const headers: Record = { + 'Content-Type': 'application/json;charset=UTF-8' + }; + headers[csrfToken.header] = csrfToken.value; + return sendRequest({ + method: 'POST', + payload: request, + credentials: true, + endpoint: createAbsoluteURL([ + this.registry.serverUrl, + 'admin', + 'name-squatting', + 'namespaces', + 'allowlist' + ]), + headers + }); + } + async getLogs( signal: AbortSignal, page: number = 0, diff --git a/webui/src/extension-registry-types.ts b/webui/src/extension-registry-types.ts index 1ba7d5100..2d5821702 100644 --- a/webui/src/extension-registry-types.ts +++ b/webui/src/extension-registry-types.ts @@ -603,6 +603,161 @@ export interface SizeOverrideList { maxOverrideSize: number; } +/** An extension as the name squatting dashboard shows it. */ +export interface NameSquattingExtension { + namespace: string; + name: string; + /** A display name of one of its active versions. */ + displayName?: string; + downloadCount: number; + /** UTC timestamp of its first publication. */ + publishedDate?: string; + activeVersionCount: number; + active: boolean; +} + +export type NameSquattingField = 'NAME' | 'DISPLAY_NAME'; + +/** How a look-alike's name compares with the extension published first. */ +export interface NameSquattingMatch { + field: NameSquattingField; + /** The value of the extension published first. */ + value: string; + lookalikeValue: string; + /** Trigram similarity, from 0 to 1. */ + similarity: number; + /** Equal ignoring case and surrounding whitespace; a similarity of 1 alone does not imply it. */ + exact: boolean; +} + +export interface NameSquattingLookalike { + extension: NameSquattingExtension; + /** Closest first. */ + matches: NameSquattingMatch[]; + /** Trigram similarity of the two namespace names, from 0 to 1. */ + namespaceSimilarity: number; + /** UTC timestamp of the latest flag of either extension, absent for a display name only shared. */ + flaggedAt?: string; +} + +/** An extension and the later extensions that resemble it. */ +export interface NameSquattingGroup { + anchor: NameSquattingExtension; + lookalikes: NameSquattingLookalike[]; +} + +export interface NameSquattingCollisions { + groups: NameSquattingGroup[]; + /** Pass as `offset` to load the next groups. */ + nextOffset: number; + hasMore: boolean; +} + +export interface NameSquattingAllowRequest { + namespace: string; + extension: string; + otherNamespace: string; + otherExtension: string; + reason?: string; +} + +/** A pair an admin allowed. */ +export interface NameSquattingAllow { + id: number; + other: NameSquattingExtension; + field: NameSquattingField | 'NAMESPACE'; + similarity: number; + /** The allowed extension's value when it was allowed. */ + value: string; + /** The other extension's value when it was allowed. */ + otherValue: string; + /** Whether either value has changed since. */ + renamed: boolean; + reason?: string; + /** Login name of the admin, absent once that user is gone. */ + decidedBy?: string; + decidedAt: string; +} + +/** An allowed extension and the pairs it was allowed in. */ +export interface NameSquattingAllowlistGroup { + extension: NameSquattingExtension; + allows: NameSquattingAllow[]; +} + +export interface NameSquattingAllowlist { + groups: NameSquattingAllowlistGroup[]; + page: number; + hasMore: boolean; +} + +/** A namespace as the name squatting dashboard shows it. */ +export interface NameSquattingNamespace { + name: string; + /** Downloads of its active extensions. */ + downloads: number; + activeExtensions: number; + /** UTC timestamp of its earliest active extension's publication, absent without any. */ + firstPublished?: string; +} + +/** Two namespaces whose names resemble each other, the one with more downloads as target. */ +export interface NameSquattingNamespacePair { + target: NameSquattingNamespace; + lookalike: NameSquattingNamespace; + /** Levenshtein distance of the names, ignoring case. */ + editDistance: number; + /** Trigram similarity of the names, from 0 to 1. */ + similarity: number; + /** Whether the names only differ in characters other than letters and digits. */ + separatorOnly: boolean; + /** Whether a user is a member of both namespaces. */ + sharedMember: boolean; + /** Whether the target counts as popular next to the look-alike. */ + popular: boolean; +} + +/** `downloads`: the most downloaded target first; `newest`: the most recently first published look-alike first. */ +export type NameSquattingNamespaceSort = 'downloads' | 'newest'; + +export interface NameSquattingNamespacePairs { + pairs: NameSquattingNamespacePair[]; + /** Pairs not allowed, popular or not. */ + total: number; + /** Of those, the pairs with a popular target. */ + popularTotal: number; + offset: number; + hasMore: boolean; +} + +export interface NameSquattingNamespaceAllowRequest { + /** The look-alike. */ + namespace: string; + otherNamespace: string; + reason?: string; +} + +/** A pair of namespaces an admin allowed. */ +export interface NameSquattingNamespaceAllow { + id: number; + /** The look-alike's name when it was allowed. */ + namespace: string; + /** The other namespace's name when it was allowed. */ + otherNamespace: string; + similarity: number; + reason?: string; + /** Login name of the admin, absent once that user is gone. */ + decidedBy?: string; + decidedAt: string; +} + +export interface NameSquattingNamespaceAllowlist { + /** The most recently allowed first. */ + allows: NameSquattingNamespaceAllow[]; + page: number; + hasMore: boolean; +} + export interface Log { timestamp: string; user: string; diff --git a/webui/src/pages/admin-dashboard/admin-dashboard-routes.ts b/webui/src/pages/admin-dashboard/admin-dashboard-routes.ts index 5f62dde35..a8a47b6f6 100644 --- a/webui/src/pages/admin-dashboard/admin-dashboard-routes.ts +++ b/webui/src/pages/admin-dashboard/admin-dashboard-routes.ts @@ -18,6 +18,7 @@ export namespace AdminDashboardRoutes { export const EXTENSION_ADMIN = createRoute([ROOT, 'extensions']); export const PUBLISHER_ADMIN = createRoute([ROOT, 'publisher']); export const SCANS_ADMIN = createRoute([ROOT, 'scans']); + export const NAME_SQUATTING = createRoute([ROOT, 'name-squatting']); export const SIZE_OVERRIDES = createRoute([ROOT, 'size-overrides']); export const SETTINGS = createRoute([ROOT, 'settings']); export const LOGS = createRoute([ROOT, 'logs']); diff --git a/webui/src/pages/admin-dashboard/admin-dashboard.tsx b/webui/src/pages/admin-dashboard/admin-dashboard.tsx index 4f5f9990c..e8da9a0df 100644 --- a/webui/src/pages/admin-dashboard/admin-dashboard.tsx +++ b/webui/src/pages/admin-dashboard/admin-dashboard.tsx @@ -21,6 +21,7 @@ import BuildIcon from '@mui/icons-material/Build'; import CategoryIcon from '@mui/icons-material/Category'; import ExtensionSharpIcon from '@mui/icons-material/ExtensionSharp'; import FactCheckIcon from '@mui/icons-material/FactCheck'; +import FindReplaceIcon from '@mui/icons-material/FindReplace'; import InsightsIcon from '@mui/icons-material/Insights'; import ManageSearchIcon from '@mui/icons-material/ManageSearch'; import SearchIcon from '@mui/icons-material/Search'; @@ -61,6 +62,7 @@ const SearchExplainAdmin = lazy(() => import('./search-explain/search-explain').then(m => ({ default: m.SearchExplainAdmin })) ); const StatisticsAdmin = lazy(() => import('./statistics/statistics').then(m => ({ default: m.StatisticsAdmin }))); +const NameSquatting = lazy(() => import('./name-squatting/name-squatting').then(m => ({ default: m.NameSquatting }))); const AccessControl = lazy(() => import('./access-control/access-control').then(m => ({ default: m.AccessControl }))); const navConfig: NavEntry[] = [ @@ -96,6 +98,13 @@ const navConfig: NavEntry[] = [ description: 'View security scan results and manage quarantined extensions', permission: 'manage_scans' }, + { + path: AdminDashboardRoutes.NAME_SQUATTING, + name: 'Name Squatting', + icon: , + description: "Review extensions whose names resemble another namespace's, and allow or delete them", + permission: 'manage_extensions' + }, { path: AdminDashboardRoutes.SIZE_OVERRIDES, name: 'Size overrides', @@ -504,6 +513,14 @@ export const AdminDashboard: FunctionComponent = props => { } /> + + + + } + /> void; + onClose: () => void; +} + +const describePair = ({ anchor, lookalike }: CollisionPair) => + `${extensionId(lookalike)} alongside ${extensionId(anchor)}`; + +/** Mount it per selection, so the reason and any failure do not carry over to the next one. */ +export const AllowDialog: FC = ({ pairs, onAllowed, onClose }) => { + const [reason, setReason] = useState(''); + const { mutateAsync: allowPairs, isPending: allowing, error } = useAllowNameSquattingPairs(); + + const single = pairs.length === 1; + + const handleConfirm = async () => { + const trimmed = reason.trim(); + try { + await allowPairs( + pairs.map(({ anchor, lookalike }) => ({ + namespace: lookalike.namespace, + extension: lookalike.name, + otherNamespace: anchor.namespace, + otherExtension: anchor.name, + reason: trimmed.length > 0 ? trimmed : undefined + })) + ); + onAllowed(); + onClose(); + } catch { + // shown from the mutation's error below + } + }; + + return ( +

+ + {single ? `Allow ${describePair(pairs[0])}?` : `Allow ${pluralize(pairs.length, 'pair')}?`} + + + + {error && ( + + {handleError(error)} + {!single && ' Pairs allowed before the failure stay allowed.'} + + )} + {single ? ( + + This pair will no longer appear on the Collisions tab. If {extensionId(pairs[0].lookalike)}{' '} + later resembles a different extension, it will be flagged again. + + ) : ( + <> + + These {pairs.length} pairs move to the Allowlist and stop showing on the Collisions tab. + Each look-alike is listed under the extension it resembles. + + ({ + first: extensionId(anchor), + second: extensionId(lookalike) + }))} + /> + + )} + setReason(event.target.value)} + error={reason.length > MAX_REASON_LENGTH} + multiline + minRows={2} + fullWidth + autoFocus + /> + + + + + + + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/allow-namespaces-dialog.tsx b/webui/src/pages/admin-dashboard/name-squatting/allow-namespaces-dialog.tsx new file mode 100644 index 000000000..0160ed024 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/allow-namespaces-dialog.tsx @@ -0,0 +1,130 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useState } from 'react'; +import { + Alert, + Button, + CircularProgress, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Stack, + TextField, + Typography +} from '@mui/material'; +import type { NameSquattingNamespacePair } from '../../../extension-registry-types'; +import { handleError } from '../../../utils'; +import { MAX_REASON_LENGTH } from './allow-dialog'; +import { pluralize } from './name-squatting-model'; +import { GroupedPairs } from './name-squatting-parts'; +import { useAllowNameSquattingNamespaces } from './use-name-squatting'; + +export interface AllowNamespacesDialogProps { + /** The selected pairs. */ + pairs: NameSquattingNamespacePair[]; + onAllowed: () => void; + onClose: () => void; +} + +const describePair = ({ target, lookalike }: NameSquattingNamespacePair) => + `${lookalike.name} alongside ${target.name}`; + +/** Mount it per selection, so the reason and any failure do not carry over to the next one. */ +export const AllowNamespacesDialog: FC = ({ pairs, onAllowed, onClose }) => { + const [reason, setReason] = useState(''); + const { mutateAsync: allowNamespaces, isPending: allowing, error } = useAllowNameSquattingNamespaces(); + const single = pairs.length === 1; + const sharedMembers = pairs.filter(pair => pair.sharedMember).length; + + const handleConfirm = async () => { + const trimmed = reason.trim(); + try { + await allowNamespaces( + pairs.map(({ target, lookalike }) => ({ + namespace: lookalike.name, + otherNamespace: target.name, + reason: trimmed.length > 0 ? trimmed : undefined + })) + ); + onAllowed(); + onClose(); + } catch { + // shown from the mutation's error below + } + }; + + return ( + + + {single ? `Allow namespace ${describePair(pairs[0])}?` : `Allow ${pluralize(pairs.length, 'pair')}?`} + + + + {error && ( + + {handleError(error)} + {!single && ' Pairs allowed before the failure stay allowed.'} + + )} + + {single ? 'This pair' : `These ${pairs.length} pairs`} will no longer appear on the Namespaces + tab, with or without the popular filter. Other namespaces that resemble them are still reported. + {!single && ' Each look-alike is listed under its target.'} + + {!single && ( + ({ + first: target.name, + second: lookalike.name + }))} + /> + )} + {sharedMembers > 0 && ( + + {single + ? 'A user is a member of both namespaces, so they are likely the same publisher.' + : `In ${pluralize(sharedMembers, 'pair')}, a user is a member of both namespaces, so they are likely the same publisher.`} + + )} + setReason(event.target.value)} + error={reason.length > MAX_REASON_LENGTH} + multiline + minRows={2} + fullWidth + autoFocus + /> + + + + + + + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/allowlist-tab.tsx b/webui/src/pages/admin-dashboard/name-squatting/allowlist-tab.tsx new file mode 100644 index 000000000..45a285ad7 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/allowlist-tab.tsx @@ -0,0 +1,292 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useMemo, useState } from 'react'; +import { + Alert, + Box, + Button, + Chip, + CircularProgress, + IconButton, + Paper, + Skeleton, + Stack, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + ToggleButton, + ToggleButtonGroup, + Typography +} from '@mui/material'; +import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'; +import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'; +import { useSearchParams } from 'react-router'; +import type { + NameSquattingAllow, + NameSquattingAllowlistGroup, + NameSquattingExtension +} from '../../../extension-registry-types'; +import { Timestamp } from '../../../components/timestamp'; +import { handleError } from '../../../utils'; +import { FilterCheckbox, SearchField } from './name-squatting-controls'; +import { FIELD_LABELS, filterAllowlistGroups, pluralize } from './name-squatting-model'; +import { ColumnWidths, ExtensionIdentity, SimilarityChip, ValuePair } from './name-squatting-parts'; +import { GroupCard, GroupHeader, GroupTable, HeaderEnd, segmentedToggle, Toolbar } from './name-squatting-styles'; +import { NamespaceAllowlist } from './namespace-allowlist'; +import { RemoveAllowsDialog } from './remove-allows-dialog'; +import { extensionId, useNameSquattingAllowlist } from './use-name-squatting'; + +const COLUMN_WIDTHS = ['22%', 'auto', '12rem', '24%', '7rem']; + +const AllowRow: FC<{ allow: NameSquattingAllow; onRemove: () => void }> = ({ allow, onRemove }) => ( + + + + + + + + + {FIELD_LABELS[allow.field]} + + {allow.renamed && } + + + + + {allow.decidedBy ?? 'A former user'} + + + + + + {allow.reason ?? ( + + No reason given + + )} + + + + + +); + +const AllowlistGroup: FC<{ + group: NameSquattingAllowlistGroup; + onRemove: (extension: NameSquattingExtension, allows: NameSquattingAllow[]) => void; +}> = ({ group, onRemove }) => { + const [open, setOpen] = useState(false); + const { extension, allows } = group; + const renamed = allows.some(allow => allow.renamed); + const lastDecidedAt = allows.reduce((last, allow) => (allow.decidedAt > last ? allow.decidedAt : last), ''); + return ( + + + setOpen(!open)} + aria-expanded={open} + aria-label={`${open ? 'Hide' : 'Show'} the allowed pairs of ${extensionId(extension)}`}> + {open ? : } + + + {renamed && } + + + + last + + + + + {open && ( + + + + + + Allowed alongside + Match when allowed (A = other, B = this extension) + Allowed by + Reason + + + + + {allows.map(allow => ( + onRemove(extension, [allow])} /> + ))} + + + + )} + + ); +}; + +const ExtensionAllowlist: FC = () => { + const [query, setQuery] = useState(''); + const [renamedOnly, setRenamedOnly] = useState(false); + const [removeTarget, setRemoveTarget] = useState<{ + extension: NameSquattingExtension; + allows: NameSquattingAllow[]; + }>(); + + const { + data: groups, + error, + isPending, + isFetchNextPageError, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + refetch + } = useNameSquattingAllowlist(); + + const visible = useMemo( + () => filterAllowlistGroups(groups ?? [], { query, renamedOnly }), + [groups, query, renamedOnly] + ); + const pairCount = visible.reduce((count, group) => count + group.allows.length, 0); + + const renderGroups = () => { + if (isPending) { + return error ? null : ( + + {[0, 1].map(index => ( + + ))} + + ); + } + if (visible.length === 0) { + const filtered = (groups?.length ?? 0) > 0; + return ( + + + {filtered ? 'No allowed pairs match these filters' : 'No allowed pairs yet'} + + + When you allow a pair on the Collisions tab, the pair is listed here so you can remove it later. + + + ); + } + return visible.map(group => ( + setRemoveTarget({ extension, allows })} + /> + )); + }; + + return ( + <> + + + + + {error && ( + (isFetchNextPageError ? fetchNextPage() : refetch())}> + Try again + + }> + {handleError(error)} + + )} + {!isPending && visible.length > 0 && ( + + {pluralize(visible.length, 'extension')} · {pluralize(pairCount, 'allowed pair')} + {hasNextPage && ' so far'} + + )} + {renderGroups()} + {hasNextPage && !isFetchNextPageError && ( + + )} + {removeTarget && ( + setRemoveTarget(undefined)} + /> + )} + + ); +}; + +type AllowlistKind = 'extensions' | 'namespaces'; + +/** Allowed pairs of extensions or of namespaces; the kind is kept in the URL, extensions leaving it bare. */ +export const AllowlistTab: FC = () => { + const [searchParams, setSearchParams] = useSearchParams(); + const kind: AllowlistKind = searchParams.get('kind') === 'namespaces' ? 'namespaces' : 'extensions'; + + return ( + <> + + next && + setSearchParams( + previous => { + const params = new URLSearchParams(previous); + if (next === 'namespaces') { + params.set('kind', next); + } else { + params.delete('kind'); + } + return params; + }, + { replace: true } + ) + } + sx={theme => ({ ...segmentedToggle(theme), mb: 2 })}> + Extensions + Namespaces + + {kind === 'extensions' ? : } + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/collision-group.tsx b/webui/src/pages/admin-dashboard/name-squatting/collision-group.tsx new file mode 100644 index 000000000..07948a5ae --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/collision-group.tsx @@ -0,0 +1,229 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useState } from 'react'; +import { + Box, + Chip, + IconButton, + Stack, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Tooltip, + Typography +} from '@mui/material'; +import { styled } from '@mui/material/styles'; +import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown'; +import KeyboardArrowUpIcon from '@mui/icons-material/KeyboardArrowUp'; +import type { + NameSquattingExtension, + NameSquattingGroup, + NameSquattingLookalike +} from '../../../extension-registry-types'; +import { DeleteIconButton } from '../../../components/delete-icon-button'; +import { Timestamp } from '../../../components/timestamp'; +import { formatCompactNumber } from '../../../utils'; +import { FIELD_LABELS, NAMESPACE_HINT_THRESHOLD, pluralize } from './name-squatting-model'; +import type { CollisionPair } from './allow-dialog'; +import { AllowIconButton, SelectCell, SelectCheckbox } from './name-squatting-controls'; +import { ColumnWidths, ExtensionIdentity, SimilarityChip, ValuePair } from './name-squatting-parts'; +import { GroupCard, GroupHeader, GroupTable, HeaderEnd } from './name-squatting-styles'; +import { collisionPairKey, extensionId } from './use-name-squatting'; + +const Facts = styled(Box)(({ theme }) => ({ + display: 'flex', + flexWrap: 'wrap', + gap: theme.spacing(0.5, 2), + color: theme.palette.text.secondary, + fontSize: '0.875rem' +})); + +const MatchRow = styled(Box)(({ theme }) => ({ + display: 'grid', + gridTemplateColumns: '7.5rem 1fr', + gap: theme.spacing(1), + alignItems: 'start', + '& + &': { marginTop: theme.spacing(1) } +})); + +const Hint = styled(Typography)(({ theme }) => ({ + display: 'block', + color: theme.palette.text.secondary, + fontSize: '0.75rem' +})) as typeof Typography; + +const COLUMN_WIDTHS = ['3.25rem', '22%', 'auto', '6.5rem', '11rem', '6.5rem']; + +/** Opens the delete dialog; the dialog's typed confirmation guards the delete itself. */ +const DeleteButton: FC<{ extension: NameSquattingExtension; onClick: () => void; tooltip?: string }> = ({ + extension, + onClick, + tooltip = 'Delete extension' +}) => ( + + + +); + +const LookalikeRow: FC<{ + lookalike: NameSquattingLookalike; + selected: boolean; + onSelect: (selected: boolean) => void; + onAllow: () => void; + onDelete: () => void; +}> = ({ lookalike, selected, onSelect, onAllow, onDelete }) => { + const { extension } = lookalike; + return ( + + + + + + + {lookalike.matches.map(match => ( + + + + {FIELD_LABELS[match.field]} + + + + ))} + {lookalike.namespaceSimilarity >= NAMESPACE_HINT_THRESHOLD && ( + + Namespaces are {Math.round(lookalike.namespaceSimilarity * 100)}% similar too + + )} + + {formatCompactNumber(extension.downloadCount)} + + {extension.publishedDate && } + {pluralize(extension.activeVersionCount, 'version')} + + {lookalike.flaggedAt ? ( + <> + flagged + + ) : ( + 'shares the display name, not flagged' + )} + + + + + + + + + + ); +}; + +export interface CollisionGroupProps { + group: NameSquattingGroup; + /** Keys of the selected pairs, see `collisionPairKey`. */ + selected: ReadonlySet; + onSelect: (keys: string[], selected: boolean) => void; + onAllow: (pairs: CollisionPair[]) => void; + /** `laterCount` is how many extensions of the group were published after the one to delete. */ + onDelete: (extension: NameSquattingExtension, laterCount: number) => void; +} + +/** + * The extension published first and those published later that resemble it, a row each. Published + * first is not proof of being the original, so either side can be deleted. + */ +export const CollisionGroup: FC = ({ group, selected, onSelect, onAllow, onDelete }) => { + const [open, setOpen] = useState(true); + const { anchor, lookalikes } = group; + const keys = lookalikes.map(lookalike => collisionPairKey(anchor, lookalike.extension)); + const selectedCount = keys.filter(key => selected.has(key)).length; + return ( + + + 0 && selectedCount < keys.length} + onChange={event => onSelect(keys, event.target.checked)} + inputProps={{ 'aria-label': `Select every extension published after ${extensionId(anchor)}` }} + // the header's 16px padding less 8px: the same inset as the row checkboxes below + sx={{ ml: -1 }} + /> + setOpen(!open)} + aria-expanded={open} + aria-label={`${open ? 'Collapse' : 'Expand'} ${extensionId(anchor)}`}> + {open ? : } + + + + + {formatCompactNumber(anchor.downloadCount)} downloads + {anchor.publishedDate && ( + + since + + )} + + + + + onAllow(lookalikes.map(lookalike => ({ anchor, lookalike: lookalike.extension }))) + } + /> + onDelete(anchor, lookalikes.length)} + /> + + + {open && ( + + + + + + + Published later + Matched on (A = published first, B = published later) + Downloads + Published + + + + + {lookalikes.map((lookalike, index) => ( + onSelect([keys[index]], checked)} + onAllow={() => onAllow([{ anchor, lookalike: lookalike.extension }])} + onDelete={() => onDelete(lookalike.extension, 0)} + /> + ))} + + + + )} + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/collisions-tab.tsx b/webui/src/pages/admin-dashboard/name-squatting/collisions-tab.tsx new file mode 100644 index 000000000..49c6cfa4f --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/collisions-tab.tsx @@ -0,0 +1,194 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useMemo, useState } from 'react'; +import { Box, Button, CircularProgress, Paper, Skeleton, Typography } from '@mui/material'; +import type { NameSquattingExtension, NameSquattingField } from '../../../extension-registry-types'; +import { AllowDialog, CollisionPair } from './allow-dialog'; +import { CollisionGroup } from './collision-group'; +import { DeleteExtensionDialog } from './delete-extension-dialog'; +import { FilterCheckbox, RefreshControl, SearchField, SelectionBar } from './name-squatting-controls'; +import { FIELD_LABELS, filterCollisionGroups, pluralize } from './name-squatting-model'; +import { LoadError } from './name-squatting-parts'; +import { Toolbar } from './name-squatting-styles'; +import { collisionPairKey, extensionId, useNameSquattingCollisions } from './use-name-squatting'; + +const ALL_FIELDS: NameSquattingField[] = ['NAME', 'DISPLAY_NAME']; + +export const CollisionsTab: FC = () => { + const [fields, setFields] = useState(ALL_FIELDS); + const [exactOnly, setExactOnly] = useState(false); + const [query, setQuery] = useState(''); + const [selected, setSelected] = useState>(new Set()); + const [allowTarget, setAllowTarget] = useState(); + const [deleteTarget, setDeleteTarget] = useState<{ + extension: NameSquattingExtension; + laterCount: number; + }>(); + + const { + data: groups, + dataUpdatedAt, + error, + isPending, + isFetching, + isFetchNextPageError, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + refetch + } = useNameSquattingCollisions(); + + const visible = useMemo( + () => filterCollisionGroups(groups ?? [], { fields: new Set(fields), exactOnly, query }), + [groups, fields, exactOnly, query] + ); + // Only what the filters leave visible can be acted on, whatever was selected before they changed. + const visiblePairs = useMemo( + () => + visible.flatMap(group => + group.lookalikes.map(lookalike => ({ + key: collisionPairKey(group.anchor, lookalike.extension), + anchor: group.anchor, + lookalike: lookalike.extension + })) + ), + [visible] + ); + const selectedPairs = visiblePairs.filter(pair => selected.has(pair.key)); + const lookalikeCount = visiblePairs.length; + const exactCount = visible.reduce( + (count, group) => + count + group.lookalikes.filter(lookalike => lookalike.matches.some(match => match.exact)).length, + 0 + ); + + const toggleField = (field: NameSquattingField, checked: boolean) => + setFields(ALL_FIELDS.filter(candidate => (candidate === field ? checked : fields.includes(candidate)))); + + const select = (keys: string[], checked: boolean) => + setSelected(previous => { + const next = new Set(previous); + keys.forEach(key => (checked ? next.add(key) : next.delete(key))); + return next; + }); + + const renderGroups = () => { + if (isPending) { + return error ? null : ( + + {[0, 1, 2].map(index => ( + + ))} + + ); + } + if (visible.length === 0) { + const filtered = (groups?.length ?? 0) > 0; + return ( + + + {filtered ? 'No similar extensions match these filters' : 'No similar names found'} + + + Pairs you have allowed are not shown here; you can review them on the Allowlist tab. + + + ); + } + return visible.map(group => ( + setDeleteTarget({ extension, laterCount })} + /> + )); + }; + + return ( + <> + + + + Match on + + {ALL_FIELDS.map(field => ( + toggleField(field, checked)} + /> + ))} + + refetch()} + refreshing={isFetching && !isFetchingNextPage} + updatedAt={dataUpdatedAt} + /> + + {error && !isFetchNextPageError && refetch()} />} + {!isPending && visible.length > 0 && ( + + {pluralize(visible.length, 'group')} · {pluralize(lookalikeCount, 'later extension')} · {exactCount}{' '} + with an exact match + {hasNextPage && ' so far'} + + )} + {!isPending && visible.length > 0 && ( + setSelected(new Set(checked ? visiblePairs.map(pair => pair.key) : []))} + onAction={() => setAllowTarget(selectedPairs)} + /> + )} + {renderGroups()} + {error && isFetchNextPageError && fetchNextPage()} />} + {hasNextPage && !isFetchNextPageError && ( + + )} + {allowTarget && ( + setSelected(new Set())} + onClose={() => setAllowTarget(undefined)} + /> + )} + {deleteTarget && ( + setDeleteTarget(undefined)} + /> + )} + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/delete-extension-dialog.tsx b/webui/src/pages/admin-dashboard/name-squatting/delete-extension-dialog.tsx new file mode 100644 index 000000000..ce7a9a761 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/delete-extension-dialog.tsx @@ -0,0 +1,150 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useState } from 'react'; +import { + Alert, + Button, + CircularProgress, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Link, + Stack, + TextField, + Typography +} from '@mui/material'; +import { Link as RouterLink } from 'react-router'; +import type { NameSquattingExtension } from '../../../extension-registry-types'; +import { handleError } from '../../../utils'; +import { AdminDashboardRoutes } from '../admin-dashboard-routes'; +import { useAdminExtension } from '../use-extension-admin'; +import { pluralize } from './name-squatting-model'; +import { extensionId, useDeleteExtension } from './use-name-squatting'; + +export interface DeleteExtensionDialogProps { + extension: NameSquattingExtension; + /** When deleting the extension published first of a group, how many were published after it. */ + laterCount?: number; + onClose: () => void; +} + +/** + * Soft-deletes every active version of an extension on either side of a pair. The versions are read fresh when it opens, + * since the delete endpoint removes only the versions it is given. + */ +export const DeleteExtensionDialog: FC = ({ + extension: target, + laterCount = 0, + onClose +}) => { + const [confirmation, setConfirmation] = useState(''); + const { data: extension, isFetching: loadingVersions } = useAdminExtension({ + namespace: target.namespace, + extension: target.name + }); + const { mutateAsync: deleteExtension, isPending: deleting, error } = useDeleteExtension(); + + const id = extensionId(target); + const targets = (extension?.allTargetPlatformVersions ?? []).flatMap(version => + version.targetPlatforms + .filter(platform => !platform.removed) + .map(({ targetPlatform }) => ({ version: version.version, targetPlatform })) + ); + const versionCount = new Set(targets.map(target => target.version)).size; + const platformCount = new Set(targets.map(target => target.targetPlatform)).size; + const canDelete = confirmation.trim() === id && targets.length > 0 && !loadingVersions && !deleting; + + const handleConfirm = async () => { + try { + await deleteExtension({ + namespace: target.namespace, + extension: target.name, + targetPlatformVersions: targets + }); + onClose(); + } catch { + // shown from the mutation's error below + } + }; + + const describeVersions = () => { + if (loadingVersions) { + return 'Every active version is removed and its files deleted from storage.'; + } + const platforms = platformCount > 1 ? ` (${platformCount} platforms)` : ''; + return versionCount === 1 + ? `Its only version${platforms} is removed and its files deleted from storage.` + : `All ${pluralize(versionCount, 'version')}${platforms} are removed and their files deleted from storage.`; + }; + + return ( + + Delete {id}? + + + {error && {handleError(error)}} + + This cannot be undone. +
    +
  • {describeVersions()}
  • +
  • Users can no longer find, install or update it.
  • +
  • These version numbers stay reserved until an administrator purges the extension.
  • +
+
+ {laterCount > 0 && ( + + {laterCount === 1 + ? `1 extension published after ${id} resembles it. It moves under the next earliest extension it resembles, or leaves this page if ${id} was its only match.` + : `${laterCount} extensions published after ${id} resemble it. Each moves under the next earliest extension it resembles, or leaves this page if ${id} was its only match.`} + + )} + + The publisher can still publish a new version of this extension, which would show up here again. + To stop them publishing,{' '} + + revoke the publisher + + . + + {!loadingVersions && extension && targets.length === 0 && ( + {id} has no active versions left to delete. + )} + setConfirmation(event.target.value)} + autoComplete='off' + spellCheck={false} + fullWidth + autoFocus + /> +
+
+ + + + +
+ ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-diff.ts b/webui/src/pages/admin-dashboard/name-squatting/name-diff.ts new file mode 100644 index 000000000..c695cde9e --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-diff.ts @@ -0,0 +1,63 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +export interface DiffSegment { + text: string; + /** Not part of the longest run of characters both names share. */ + changed: boolean; +} + +/** + * Splits two names into the characters they share, in order, and those that differ, ignoring case + * as the similarity check does. Each name keeps its own spelling in the segments. + */ +export function diffNames(a: string, b: string): [DiffSegment[], DiffSegment[]] { + const lowerA = a.toLowerCase(); + const lowerB = b.toLowerCase(); + // lcs[i][j]: length of the longest common subsequence of lowerA from i and lowerB from j + const lcs = Array.from({ length: a.length + 1 }, () => new Uint16Array(b.length + 1)); + for (let i = a.length - 1; i >= 0; i--) { + for (let j = b.length - 1; j >= 0; j--) { + lcs[i][j] = lowerA[i] === lowerB[j] ? lcs[i + 1][j + 1] + 1 : Math.max(lcs[i + 1][j], lcs[i][j + 1]); + } + } + const keptA = new Array(a.length).fill(false); + const keptB = new Array(b.length).fill(false); + let i = 0; + let j = 0; + while (i < a.length && j < b.length) { + if (lowerA[i] === lowerB[j]) { + keptA[i++] = true; + keptB[j++] = true; + } else if (lcs[i + 1][j] >= lcs[i][j + 1]) { + i++; + } else { + j++; + } + } + return [toSegments(a, keptA), toSegments(b, keptB)]; +} + +function toSegments(text: string, kept: boolean[]): DiffSegment[] { + const segments: DiffSegment[] = []; + for (let index = 0; index < text.length; index++) { + const changed = !kept[index]; + const last = segments[segments.length - 1]; + if (last?.changed === changed) { + last.text += text[index]; + } else { + segments.push({ text: text[index], changed }); + } + } + return segments; +} diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-squatting-controls.tsx b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-controls.tsx new file mode 100644 index 000000000..4f56e9d0a --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-controls.tsx @@ -0,0 +1,224 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useEffect, useState } from 'react'; +import { + Box, + Button, + Checkbox, + CheckboxProps, + CircularProgress, + FormControlLabel, + IconButton, + IconButtonProps, + InputAdornment, + TableCell, + TextField, + Tooltip, + Typography +} from '@mui/material'; +import { styled, Theme } from '@mui/material/styles'; +import CheckIcon from '@mui/icons-material/Check'; +import RefreshIcon from '@mui/icons-material/Refresh'; +import SearchIcon from '@mui/icons-material/Search'; +import { toLocalTime, toRelativeTime } from '../../../utils'; +import { pluralize } from './name-squatting-model'; + +/** Search box that leads a toolbar, focused in the secondary color like the Extension Scans filters. */ +export const SearchField: FC<{ + value: string; + onChange: (value: string) => void; + placeholder: string; + label: string; +}> = ({ value, onChange, placeholder, label }) => ( + onChange(event.target.value)} + inputProps={{ 'aria-label': label }} + InputProps={{ + startAdornment: ( + + + + ) + }} + sx={{ + flex: '1 1 18rem', + maxWidth: '26rem', + '& .MuiOutlinedInput-root.Mui-focused fieldset': { borderColor: 'secondary.main' } + }} + /> +); + +/** + * How long ago the list was looked up, counted in seconds under a minute: the lists refresh every minute, + * so the shared formatter's "now" would be all it ever said. Ticks on its own, since the list only + * re-renders when it refreshes. + */ +const UpdatedAgo: FC<{ updatedAt: number }> = ({ updatedAt }) => { + const [now, setNow] = useState(Date.now); + useEffect(() => { + const timer = setInterval(() => setNow(Date.now()), 1000); + return () => clearInterval(timer); + }, []); + const iso = new Date(updatedAt).toISOString(); + const seconds = Math.max(1, Math.floor((now - updatedAt) / 1000)); + return ( + + Updated {seconds < 60 ? `${pluralize(seconds, 'second')} ago` : toRelativeTime(iso)} + + ); +}; + +/** + * When the list was last looked up, and a button to look it up again now. The list also refreshes itself, + * so the spinner shows for those refreshes too. + */ +export const RefreshControl: FC<{ + onClick: () => void; + refreshing: boolean; + /** `dataUpdatedAt` of the query, 0 before its first answer. */ + updatedAt: number; +}> = ({ onClick, refreshing, updatedAt }) => ( + + {updatedAt > 0 && } + + {/* a disabled button fires no events, so the span keeps the tooltip working while it refreshes */} + + + {refreshing ? : } + + + + +); + +/** A checkbox in the secondary color, plain grey when unchecked so a checked one stands out. */ +export const SelectCheckbox: FC = ({ sx, ...props }) => ( + theme.palette.checkboxUnchecked }, ...(Array.isArray(sx) ? sx : [sx])]} + /> +); + +/** + * The checkbox leading a row. Its 8px inset matches the select-all and group checkboxes, so they line up; + * no top padding centers it on the row's first line of text. + */ +export const SelectCell: FC<{ checked: boolean; onChange: (checked: boolean) => void; label: string }> = ({ + checked, + onChange, + label +}) => ( + + onChange(event.target.checked)} + inputProps={{ 'aria-label': label }} + /> + +); + +// The theme's outlined error button and DeleteIconButton, in the color Extension Scans allows in. +const allowColors = (theme: Theme) => ({ + backgroundColor: theme.palette.surface2, + border: `1px solid ${theme.palette.divider}`, + color: theme.palette.allowed, + transition: 'background-color 0.15s', + '&:hover': { + backgroundColor: theme.palette.allowed, + borderColor: theme.palette.allowed, + color: theme.palette.common.white + } +}); + +// Circular twin of DeleteIconButton, so the two sit side by side in a row. +const AllowIconRoot = styled(IconButton)(({ theme }) => ({ + width: '1.875rem', + height: '1.875rem', + ...allowColors(theme) +})); + +/** Allows the pair of one row, or every pair of a group. */ +export const AllowIconButton: FC = ({ tooltip = 'Allow pair', ...props }) => ( + + + + + +); + +/** An on/off filter, as the Extension Scans toolbars show them. */ +export const FilterCheckbox: FC<{ + label: string; + checked: boolean; + onChange: (checked: boolean) => void; + disabled?: boolean; +}> = ({ label, checked, onChange, disabled }) => ( + onChange(event.target.checked)} /> + } + label={{label}} + sx={{ mr: 0 }} + /> +); + +const Bar = styled(Box)(({ theme }) => ({ + display: 'flex', + flexWrap: 'wrap', + alignItems: 'center', + gap: theme.spacing(1, 2), + padding: theme.spacing(0.5, 2, 0.5, 1), + marginBottom: theme.spacing(2), + border: `1px solid ${theme.palette.divider}`, + borderRadius: theme.shape.borderRadius +})); + +/** Select all, how many pairs are selected, and the button that allows them. */ +export const SelectionBar: FC<{ + selected: number; + total: number; + onSelectAll: (selected: boolean) => void; + onAction: () => void; +}> = ({ selected, total, onSelectAll, onAction }) => ( + + 0 && selected === total} + indeterminate={selected > 0 && selected < total} + onChange={event => onSelectAll(event.target.checked)} + /> + } + label={Select all} + sx={{ ml: 0, mr: 0 }} + /> + + {selected > 0 ? `${pluralize(selected, 'pair')} selected` : 'Select pairs to allow them together'} + + + +); diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-squatting-model.ts b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-model.ts new file mode 100644 index 000000000..42e77c5c2 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-model.ts @@ -0,0 +1,101 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import type { + NameSquattingAllow, + NameSquattingAllowlistGroup, + NameSquattingExtension, + NameSquattingField, + NameSquattingGroup +} from '../../../extension-registry-types'; +import { extensionId } from './use-name-squatting'; + +export const FIELD_LABELS: Record = { + NAME: 'Extension name', + DISPLAY_NAME: 'Display name', + NAMESPACE: 'Namespace' +}; + +/** + * Namespace similarity only corroborates a name match, so it is mentioned from here up and is + * otherwise noise: unrelated namespaces still share a trigram or two. + */ +export const NAMESPACE_HINT_THRESHOLD = 0.5; + +/** Trigram similarity can reach 1 for names that are not equal (punctuation is ignored), so 100% is not "Exact". */ +export const formatSimilarity = (similarity: number, exact: boolean): string => + exact ? 'Exact' : `${Math.round(similarity * 100)}%`; + +export const similarityColor = (similarity: number, exact: boolean): 'error' | 'warning' | 'default' => { + if (exact) { + return 'error'; + } + return similarity >= 0.85 ? 'warning' : 'default'; +}; + +export const pluralize = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`; + +export interface CollisionFilter { + fields: ReadonlySet; + exactOnly: boolean; + query: string; +} + +const matchesQuery = (query: string, extensions: NameSquattingExtension[]): boolean => { + const needle = query.trim().toLowerCase(); + return ( + needle.length === 0 || + extensions.some(extension => + `${extensionId(extension)} ${extension.displayName ?? ''}`.toLowerCase().includes(needle) + ) + ); +}; + +/** + * Narrows the loaded groups to the matches on the chosen fields. A look-alike left with no match is + * dropped, and so is a group left with no look-alike; the query keeps a group when its anchor or any + * remaining look-alike contains it. + */ +export function filterCollisionGroups(groups: NameSquattingGroup[], filter: CollisionFilter): NameSquattingGroup[] { + return groups.flatMap(group => { + const lookalikes = group.lookalikes.flatMap(lookalike => { + const matches = lookalike.matches.filter( + match => filter.fields.has(match.field) && (!filter.exactOnly || match.exact) + ); + return matches.length > 0 ? [{ ...lookalike, matches }] : []; + }); + if ( + lookalikes.length === 0 || + !matchesQuery(filter.query, [group.anchor, ...lookalikes.map(lookalike => lookalike.extension)]) + ) { + return []; + } + return [{ anchor: group.anchor, lookalikes }]; + }); +} + +export interface AllowlistFilter { + renamedOnly: boolean; + query: string; +} + +export function filterAllowlistGroups( + groups: NameSquattingAllowlistGroup[], + filter: AllowlistFilter +): NameSquattingAllowlistGroup[] { + return groups.filter( + group => + (!filter.renamedOnly || group.allows.some(allow => allow.renamed)) && + matchesQuery(filter.query, [group.extension, ...group.allows.map(allow => allow.other)]) + ); +} diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-squatting-parts.tsx b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-parts.tsx new file mode 100644 index 000000000..9f8e9b6e5 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-parts.tsx @@ -0,0 +1,219 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC } from 'react'; +import { Alert, Box, Button, Chip, Link } from '@mui/material'; +import { alpha, styled } from '@mui/material/styles'; +import OpenInNewIcon from '@mui/icons-material/OpenInNew'; +import { Link as RouterLink } from 'react-router'; +import type { NameSquattingExtension } from '../../../extension-registry-types'; +import { NamespaceDetailRoutes } from '../../namespace-detail/namespace-detail-routes'; +import type { ErrorResponse } from '../../../server-request'; +import { createRoute, handleError } from '../../../utils'; +import { ExtensionDetailRoutes } from '../../extension-detail/extension-detail-routes'; +import { AdminDashboardRoutes } from '../admin-dashboard-routes'; +import { diffNames, DiffSegment } from './name-diff'; +import { formatSimilarity, similarityColor } from './name-squatting-model'; +import { extensionId } from './use-name-squatting'; + +const NewTab = () => ( + +); + +const monoLink = { + fontFamily: 'monospace', + fontSize: '0.8125rem', + color: 'text.secondary' +} as const; + +/** + * Display name and identifier. Throughout the page, the arrow marks the public page (a new tab) and the + * monospace identifier opens the admin page. + */ +export const ExtensionIdentity: FC<{ extension: NameSquattingExtension }> = ({ extension }) => ( + + + {extension.displayName ?? extension.name} + + + + {extensionId(extension)} + + +); + +/** A namespace's name, opening the admin page, and the arrow to its public page, as for extensions. */ +export const NamespaceIdentity: FC<{ name: string }> = ({ name }) => ( + + + {name} + + + + + +); + +/** Column widths for a `GroupTable`, in column order. */ +export const ColumnWidths: FC<{ widths: string[] }> = ({ widths }) => ( + + {widths.map((width, index) => ( + + ))} + +); + +export const SimilarityChip: FC<{ similarity: number; exact: boolean }> = ({ similarity, exact }) => ( + +); + +const Changed = styled('mark')(({ theme }) => ({ + backgroundColor: alpha(theme.palette.warning.main, 0.3), + color: 'inherit', + borderRadius: '0.125rem' +})); + +const Segments: FC<{ segments: DiffSegment[] }> = ({ segments }) => ( + <> + {segments.map((segment, index) => + segment.changed ? {segment.text} : {segment.text} + )} + +); + +const PairGrid = styled(Box)(({ theme }) => ({ + display: 'grid', + gridTemplateColumns: 'auto 1fr', + columnGap: theme.spacing(1), + fontSize: '0.875rem', + wordBreak: 'break-word' +})); + +const PairKey = styled('span')(({ theme }) => ({ + color: theme.palette.text.secondary, + fontWeight: 600 +})); + +/** + * The two values one above the other, the characters they do not share highlighted. A is the + * extension published first (or the other extension of an allowed pair), B the one published later. + */ +export const ValuePair: FC<{ first: string; second: string }> = ({ first, second }) => { + const [segmentsA, segmentsB] = diffNames(first, second); + return ( + + A + + + + B + + + + + ); +}; + +// Not capped: the dialog scrolls its content itself and keeps its buttons in view. +const PairGroups = styled('ul')(({ theme }) => ({ + listStyle: 'none', + margin: 0, + padding: theme.spacing(1.5, 2), + border: `1px solid ${theme.palette.divider}`, + borderRadius: theme.shape.borderRadius, + fontFamily: 'monospace', + fontSize: '0.875rem', + '& > li + li': { marginTop: theme.spacing(1.5) } +})); + +const Seconds = styled('ul')(({ theme }) => ({ + listStyle: 'none', + margin: theme.spacing(0.5, 0, 0, 0.5), + padding: theme.spacing(0, 0, 0, 1.5), + borderLeft: `2px solid ${theme.palette.divider}` +})); + +/** Pairs grouped under their first value, in the order those first appear. */ +const groupPairs = (pairs: { first: string; second: string }[]) => { + const groups = new Map(); + pairs.forEach(({ first, second }) => groups.set(first, [...(groups.get(first) ?? []), second])); + return [...groups].map(([first, seconds]) => ({ first, seconds })); +}; + +/** Selected pairs, each look-alike under the name it resembles, which is named once however many do. */ +export const GroupedPairs: FC<{ pairs: { first: string; second: string }[]; label: string }> = ({ pairs, label }) => ( + + {groupPairs(pairs).map(group => ( +
  • + + {group.first} + + + {group.seconds.map(second => ( +
  • {second}
  • + ))} + + + ))} +
    +); + +/** The server answers 503 when a lookup ran past its statement timeout and was stopped. */ +const isTimeout = (error: unknown): boolean => (error as Partial | null)?.status === 503; + +/** A failed lookup, with a retry; a 503 is the statement timeout, which a retry may well get past. */ +export const LoadError: FC<{ error: unknown; onRetry: () => void }> = ({ error, onRetry }) => ( + + Try again + + }> + {isTimeout(error) ? ( + <> + The check took too long and was stopped. Nothing was changed. Try again; if this keeps + happening, raise ovsx.scanning.name-similarity.statement-timeout in the server + configuration. + + ) : ( + handleError(error) + )} + +); diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-squatting-styles.ts b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-styles.ts new file mode 100644 index 000000000..5ff1e6951 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-squatting-styles.ts @@ -0,0 +1,70 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { Box, Paper, Table } from '@mui/material'; +import { styled, Theme } from '@mui/material/styles'; + +export const GroupCard = styled(Paper)(({ theme }) => ({ + marginBottom: theme.spacing(2), + overflow: 'hidden' +})); + +export const GroupHeader = styled(Box)(({ theme }) => ({ + display: 'flex', + flexWrap: 'wrap', + alignItems: 'center', + gap: theme.spacing(1, 2), + padding: theme.spacing(1.5, 2), + backgroundColor: theme.palette.action.hover +})); + +export const HeaderEnd = styled(Box)(({ theme }) => ({ + display: 'flex', + alignItems: 'center', + gap: theme.spacing(1), + marginLeft: 'auto' +})); + +// Each group is its own table; a fixed layout makes the columns line up from one group to the next. +export const GroupTable = styled(Table)({ + tableLayout: 'fixed', + minWidth: '60rem', + '& td': { + verticalAlign: 'top', + overflowWrap: 'anywhere' + } +}); + +export const Toolbar = styled(Box)(({ theme }) => ({ + display: 'flex', + flexWrap: 'wrap', + alignItems: 'center', + gap: theme.spacing(1.5, 2), + marginBottom: theme.spacing(2) +})); + +/** `sx` of a one-of-a-few ToggleButtonGroup: the selected button filled in the secondary color, as on Extension Scans. */ +export const segmentedToggle = (theme: Theme) => ({ + height: '2rem', + '& .MuiToggleButton-root': { + padding: theme.spacing(0, 1.5), + fontSize: '0.8125rem', + textTransform: 'none', + whiteSpace: 'nowrap', + '&.Mui-selected': { + backgroundColor: theme.palette.secondary.main, + color: theme.palette.secondary.contrastText, + '&:hover': { backgroundColor: theme.palette.secondary.dark } + } + } +}); diff --git a/webui/src/pages/admin-dashboard/name-squatting/name-squatting.tsx b/webui/src/pages/admin-dashboard/name-squatting/name-squatting.tsx new file mode 100644 index 000000000..2a895d2b0 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/name-squatting.tsx @@ -0,0 +1,77 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC } from 'react'; +import { Box, Tab, Tabs, Typography } from '@mui/material'; +import { styled } from '@mui/material/styles'; +import { useSearchParams } from 'react-router'; +import { AllowlistTab } from './allowlist-tab'; +import { CollisionsTab } from './collisions-tab'; +import { NamespacesTab } from './namespaces-tab'; + +type NameSquattingTab = 'collisions' | 'namespaces' | 'allowlist'; + +const TABS: NameSquattingTab[] = ['collisions', 'namespaces', 'allowlist']; + +const DESCRIPTIONS: Record = { + collisions: + 'Active extensions in different namespaces whose name or display name match or closely resemble each other, ' + + 'grouped under the one published first. Published first is not proof of being the original: someone may ' + + 'publish an extension here before its author does. The most recently flagged come first, followed by display ' + + 'names shared across namespaces.', + namespaces: + 'Namespaces whose names differ by a typo or only in separators, the one with more downloads as target. ' + + 'Popular targets shows the pairs whose target is far more downloaded than the look-alike; All pairs adds ' + + 'the quieter ones. A namespace created in the last minute may not show yet.', + allowlist: 'Pairs admins decided are not squatting. Removing an allow reports the pair again while the names match.' +}; + +// Same gutters as the Extension Scans page. +const Page = styled(Box)(({ theme }) => ({ + padding: theme.spacing(0, 2, 3) +})); + +/** + * Extensions in different namespaces whose names match or resemble each other, namespaces whose names + * resemble each other, and the pairs admins allowed. The tab is kept in the URL so a link can open it. + */ +export const NameSquatting: FC = () => { + const [searchParams, setSearchParams] = useSearchParams(); + const tab = TABS.find(candidate => candidate === searchParams.get('tab')) ?? 'collisions'; + + return ( + + + Name Squatting + + + {DESCRIPTIONS[tab]} + + + setSearchParams(next === 'collisions' ? {} : { tab: next }, { replace: true }) + } + sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}> + + + + + + {tab === 'collisions' && } + {tab === 'namespaces' && } + {tab === 'allowlist' && } + + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/namespace-allowlist.tsx b/webui/src/pages/admin-dashboard/name-squatting/namespace-allowlist.tsx new file mode 100644 index 000000000..000c6ff9b --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/namespace-allowlist.tsx @@ -0,0 +1,238 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useMemo, useState } from 'react'; +import { + Alert, + Box, + Button, + CircularProgress, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Paper, + Skeleton, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + Typography +} from '@mui/material'; +import type { NameSquattingNamespaceAllow } from '../../../extension-registry-types'; +import { Timestamp } from '../../../components/timestamp'; +import { handleError } from '../../../utils'; +import { SearchField } from './name-squatting-controls'; +import { pluralize } from './name-squatting-model'; +import { ColumnWidths, NamespaceIdentity, SimilarityChip, ValuePair } from './name-squatting-parts'; +import { GroupCard, GroupTable, Toolbar } from './name-squatting-styles'; +import { useNameSquattingNamespaceAllowlist, useRemoveNameSquattingAllows } from './use-name-squatting'; + +const COLUMN_WIDTHS = ['auto', '12rem', '24%', '7rem']; + +const RemoveNamespaceAllowDialog: FC<{ allow: NameSquattingNamespaceAllow; onClose: () => void }> = ({ + allow, + onClose +}) => { + const { mutateAsync: removeAllows, isPending: removing, error } = useRemoveNameSquattingAllows(); + + const handleConfirm = async () => { + try { + await removeAllows([allow.id]); + onClose(); + } catch { + // shown from the mutation's error below + } + }; + + return ( + + {`Remove the allow for namespaces ${allow.namespace} and ${allow.otherNamespace}?`} + + {error && ( + + {handleError(error)} + + )} + + If the two names still resemble each other, the pair will appear on the Namespaces tab again. + + + + + + + + ); +}; + +const AllowRow: FC<{ allow: NameSquattingNamespaceAllow; onRemove: () => void }> = ({ allow, onRemove }) => ( + + + + + + + + + + {allow.decidedBy ?? 'A former user'} + + + + + + {allow.reason ?? ( + + No reason given + + )} + + + + + +); + +/** The allowed pairs of namespaces, one row each, under the names they had when allowed. */ +export const NamespaceAllowlist: FC = () => { + const [query, setQuery] = useState(''); + const [removeTarget, setRemoveTarget] = useState(); + + const { + data: allows, + error, + isPending, + isFetchNextPageError, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + refetch + } = useNameSquattingNamespaceAllowlist(); + + const visible = useMemo(() => { + const needle = query.trim().toLowerCase(); + return (allows ?? []).filter( + allow => + needle.length === 0 || + allow.namespace.toLowerCase().includes(needle) || + allow.otherNamespace.toLowerCase().includes(needle) + ); + }, [allows, query]); + + const renderAllows = () => { + if (isPending) { + return error ? null : ( + + + + ); + } + if (visible.length === 0) { + return ( + + + {(allows?.length ?? 0) > 0 + ? 'No allowed namespaces match this filter' + : 'No allowed namespaces yet'} + + + When you allow a pair on the Namespaces tab, the pair is listed here so you can remove it later. + + + ); + } + return ( + + + + + + + Names when allowed (A = target, B = look-alike) + Allowed by + Reason + + + + + {visible.map(allow => ( + setRemoveTarget(allow)} /> + ))} + + + + + ); + }; + + return ( + <> + + + + {error && ( + (isFetchNextPageError ? fetchNextPage() : refetch())}> + Try again + + }> + {handleError(error)} + + )} + {!isPending && visible.length > 0 && ( + + {pluralize(visible.length, 'allowed pair')} + {hasNextPage && ' so far'} + + )} + {renderAllows()} + {hasNextPage && !isFetchNextPageError && ( + + )} + {removeTarget && ( + setRemoveTarget(undefined)} /> + )} + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/namespaces-tab.tsx b/webui/src/pages/admin-dashboard/name-squatting/namespaces-tab.tsx new file mode 100644 index 000000000..de996320a --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/namespaces-tab.tsx @@ -0,0 +1,299 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC, useState } from 'react'; +import { + Box, + Button, + Chip, + CircularProgress, + Paper, + Skeleton, + Stack, + TableBody, + TableCell, + TableContainer, + TableHead, + TableRow, + ToggleButton, + ToggleButtonGroup, + Tooltip, + Typography +} from '@mui/material'; +import { useSearchParams } from 'react-router'; +import type { + NameSquattingNamespace, + NameSquattingNamespacePair, + NameSquattingNamespaceSort +} from '../../../extension-registry-types'; +import { Timestamp } from '../../../components/timestamp'; +import { formatCompactNumber } from '../../../utils'; +import { AllowNamespacesDialog } from './allow-namespaces-dialog'; +import { AllowIconButton, RefreshControl, SelectCell, SelectionBar } from './name-squatting-controls'; +import { pluralize } from './name-squatting-model'; +import { ColumnWidths, LoadError, NamespaceIdentity, SimilarityChip, ValuePair } from './name-squatting-parts'; +import { GroupCard, GroupTable, segmentedToggle, Toolbar } from './name-squatting-styles'; +import { namespacePairKey, useNameSquattingNamespacePairs } from './use-name-squatting'; + +const COLUMN_WIDTHS = ['3.25rem', '24%', '24%', 'auto', '4rem']; + +const SORT_LABELS: Record = { + downloads: 'Most downloaded target first', + newest: 'Newest look-alike first' +}; + +/** Kept in the URL, so a link opens the same view; the defaults leave the URL bare. */ +const TARGETS_PARAM = 'targets'; +const SORT_PARAM = 'sort'; + +const NamespaceCell: FC<{ namespace: NameSquattingNamespace }> = ({ namespace }) => ( + + + + {formatCompactNumber(namespace.downloads)} downloads · {pluralize(namespace.activeExtensions, 'extension')} + + + {namespace.firstPublished ? ( + <> + first published + + ) : ( + 'Nothing published' + )} + + +); + +const PairRow: FC<{ + pair: NameSquattingNamespacePair; + showPopular: boolean; + selected: boolean; + onSelect: (selected: boolean) => void; + onAllow: () => void; +}> = ({ pair, showPopular, selected, onSelect, onAllow }) => ( + + + + + + + + + + + + + {pair.sharedMember && ( + + + + )} + {showPopular && pair.popular && } + + + + + + + +); + +export const NamespacesTab: FC = () => { + const [searchParams, setSearchParams] = useSearchParams(); + const popularOnly = searchParams.get(TARGETS_PARAM) !== 'all'; + const sort: NameSquattingNamespaceSort = searchParams.get(SORT_PARAM) === 'newest' ? 'newest' : 'downloads'; + const [selected, setSelected] = useState>(new Set()); + const [allowTarget, setAllowTarget] = useState(); + + const { + data, + dataUpdatedAt, + error, + isPending, + isFetching, + isFetchNextPageError, + hasNextPage, + isFetchingNextPage, + fetchNextPage, + refetch + } = useNameSquattingNamespacePairs({ popularOnly, sort }); + + const setParam = (key: string, value: string | undefined) => + setSearchParams( + previous => { + const next = new URLSearchParams(previous); + if (value === undefined) { + next.delete(key); + } else { + next.set(key, value); + } + return next; + }, + { replace: true } + ); + + const pairs = data?.pairs ?? []; + const selectedPairs = pairs.filter(pair => selected.has(namespacePairKey(pair))); + + const select = (key: string, checked: boolean) => + setSelected(previous => { + const next = new Set(previous); + if (checked) { + next.add(key); + } else { + next.delete(key); + } + return next; + }); + + const renderPairs = () => { + if (isPending) { + return error ? null : ( + + {[0, 1, 2].map(index => ( + + ))} + + ); + } + if (!data || data.pairs.length === 0) { + return ( + + + {popularOnly && (data?.total ?? 0) > 0 + ? 'No pairs with a popular target' + : 'No similar namespace names found'} + + + {popularOnly && (data?.total ?? 0) > 0 + ? `Switch to "All pairs" to see the other ${pluralize(data?.total ?? 0, 'pair')}.` + : 'Pairs you have allowed are not shown here; you can review them on the Allowlist tab.'} + + + ); + } + return ( + + + + + + + + Target (more downloads) + Look-alike + How the names compare (A = target, B = look-alike) + + + + + {data.pairs.map(pair => ( + select(namespacePairKey(pair), checked)} + onAllow={() => setAllowTarget([pair])} + /> + ))} + + + + + ); + }; + + const shownTotal = popularOnly ? data?.popularTotal : data?.total; + + return ( + <> + + + next && setParam(TARGETS_PARAM, next === 'all' ? 'all' : undefined) + } + sx={segmentedToggle}> + Popular targets + All pairs + + + next && setParam(SORT_PARAM, next === 'newest' ? 'newest' : undefined) + } + sx={segmentedToggle}> + {Object.entries(SORT_LABELS).map(([value, label]) => ( + + {label} + + ))} + + refetch()} + refreshing={isFetching && !isFetchingNextPage} + updatedAt={dataUpdatedAt} + /> + + {error && !isFetchNextPageError && refetch()} />} + {data && data.pairs.length > 0 && ( + + Showing {data.pairs.length} of {pluralize(shownTotal ?? 0, 'pair')} + {popularOnly && ` with a popular target · ${data.total} in all`} + + )} + {pairs.length > 0 && ( + setSelected(new Set(checked ? pairs.map(namespacePairKey) : []))} + onAction={() => setAllowTarget(selectedPairs)} + /> + )} + {renderPairs()} + {error && isFetchNextPageError && fetchNextPage()} />} + {hasNextPage && !isFetchNextPageError && ( + + )} + {allowTarget && ( + setSelected(new Set())} + onClose={() => setAllowTarget(undefined)} + /> + )} + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/remove-allows-dialog.tsx b/webui/src/pages/admin-dashboard/name-squatting/remove-allows-dialog.tsx new file mode 100644 index 000000000..10c5290b0 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/remove-allows-dialog.tsx @@ -0,0 +1,90 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { FC } from 'react'; +import { + Alert, + Button, + CircularProgress, + Dialog, + DialogActions, + DialogContent, + DialogTitle, + Stack, + Typography +} from '@mui/material'; +import type { NameSquattingAllow, NameSquattingExtension } from '../../../extension-registry-types'; +import { handleError } from '../../../utils'; +import { pluralize } from './name-squatting-model'; +import { extensionId, useRemoveNameSquattingAllows } from './use-name-squatting'; + +export interface RemoveAllowsDialogProps { + /** The allowed extension the pairs are listed under. */ + extension: NameSquattingExtension; + allows: NameSquattingAllow[]; + onClose: () => void; +} + +export const RemoveAllowsDialog: FC = ({ extension, allows, onClose }) => { + const { mutateAsync: removeAllows, isPending: removing, error } = useRemoveNameSquattingAllows(); + + const id = extensionId(extension); + const single = allows.length === 1; + + const handleConfirm = async () => { + try { + await removeAllows(allows.map(allow => allow.id)); + onClose(); + } catch { + // shown from the mutation's error below + } + }; + + return ( + + + {single + ? `Remove the allow for ${id} and ${extensionId(allows[0].other)}?` + : `Remove all ${pluralize(allows.length, 'allowed pair')} for ${id}?`} + + + + {error && ( + + {handleError(error)} + {!single && ' Allows removed before the failure stay removed.'} + + )} + + {single + ? 'If the two names still match, the pair will appear on the Collisions tab again.' + : 'Any pair whose names still match will appear on the Collisions tab again.'} + + + + + + + + + ); +}; diff --git a/webui/src/pages/admin-dashboard/name-squatting/use-name-squatting.ts b/webui/src/pages/admin-dashboard/name-squatting/use-name-squatting.ts new file mode 100644 index 000000000..ac7112146 --- /dev/null +++ b/webui/src/pages/admin-dashboard/name-squatting/use-name-squatting.ts @@ -0,0 +1,252 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { useContext } from 'react'; +import { InfiniteData, useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'; +import { MainContext } from '../../../context'; +import type { + NameSquattingAllowlist, + NameSquattingAllowlistGroup, + NameSquattingAllowRequest, + NameSquattingCollisions, + NameSquattingExtension, + NameSquattingGroup, + NameSquattingNamespaceAllowlist, + NameSquattingNamespaceAllowRequest, + NameSquattingNamespacePair, + NameSquattingNamespacePairs, + NameSquattingNamespaceSort, + TargetPlatformVersion +} from '../../../extension-registry-types'; + +/** Candidates the server looks up per batch; each costs it a few trigram probes. */ +export const COLLISIONS_BATCH_SIZE = 25; +export const ALLOWLIST_PAGE_SIZE = 25; +export const NAMESPACE_PAIRS_PAGE_SIZE = 25; + +/** + * How often the live lists look the names up again while the page is visible. The server keeps its + * namespace pairs for a minute, so polling faster would only read the same copy. + */ +export const REFRESH_INTERVAL_MS = 60_000; + +export const nameSquattingKeys = { + all: ['admin', 'name-squatting'] as const, + collisions: () => [...nameSquattingKeys.all, 'collisions'] as const, + allowlist: () => [...nameSquattingKeys.all, 'allowlist'] as const, + namespaces: (view: NamespacePairsView) => + [...nameSquattingKeys.all, 'namespaces', view.popularOnly, view.sort] as const, + namespaceAllowlist: () => [...nameSquattingKeys.all, 'namespaces', 'allowlist'] as const +}; + +export interface NamespacePairsView { + popularOnly: boolean; + sort: NameSquattingNamespaceSort; +} + +export const extensionId = (extension: Pick): string => + `${extension.namespace}.${extension.name}`; + +/** Joins the batches into one list; an anchor resembled in two batches is shown as one group. */ +export const mergeCollisionPages = (data: InfiniteData): NameSquattingGroup[] => { + const groups = new Map(); + for (const group of data.pages.flatMap(page => page.groups)) { + const key = extensionId(group.anchor); + const existing = groups.get(key); + if (!existing) { + groups.set(key, { anchor: group.anchor, lookalikes: [...group.lookalikes] }); + continue; + } + const seen = new Set(existing.lookalikes.map(lookalike => extensionId(lookalike.extension))); + existing.lookalikes.push(...group.lookalikes.filter(lookalike => !seen.has(extensionId(lookalike.extension)))); + } + return [...groups.values()]; +}; + +/** Joins the pages into one list; an allowed extension split across two pages is shown once. */ +export const mergeAllowlistPages = ( + data: InfiniteData +): NameSquattingAllowlistGroup[] => { + const groups = new Map(); + for (const group of data.pages.flatMap(page => page.groups)) { + const key = extensionId(group.extension); + const existing = groups.get(key); + if (!existing) { + groups.set(key, { extension: group.extension, allows: [...group.allows] }); + continue; + } + const seen = new Set(existing.allows.map(allow => allow.id)); + existing.allows.push(...group.allows.filter(allow => !seen.has(allow.id))); + } + return [...groups.values()]; +}; + +/** The key a selection holds a pair under: the extension published first and the look-alike. */ +export const collisionPairKey = (anchor: NameSquattingExtension, lookalike: NameSquattingExtension): string => + `${extensionId(anchor)}/${extensionId(lookalike)}`; + +export const namespacePairKey = (pair: NameSquattingNamespacePair): string => + `${pair.target.name}/${pair.lookalike.name}`; + +export interface NamespacePairList { + pairs: NameSquattingNamespacePair[]; + total: number; + popularTotal: number; +} + +/** + * Joins the pages into one list, the totals from the latest. The server looks the pairs up again once + * its cached copy expires, which can shift a pair onto the next page; it is shown once. + */ +export const mergeNamespacePairPages = (data: InfiniteData): NamespacePairList => { + const pairs = new Map(); + for (const pair of data.pages.flatMap(page => page.pairs)) { + const key = namespacePairKey(pair); + if (!pairs.has(key)) { + pairs.set(key, pair); + } + } + const last = data.pages[data.pages.length - 1] as NameSquattingNamespacePairs | undefined; + return { pairs: [...pairs.values()], total: last?.total ?? 0, popularTotal: last?.popularTotal ?? 0 }; +}; + +/** + * The look-alikes, looked up live a batch at a time. Never retried: a lookup that hit the server's + * statement timeout would only be run again against the same database, and the page offers a retry. + */ +export const useNameSquattingCollisions = () => { + const { service } = useContext(MainContext); + return useInfiniteQuery({ + queryKey: nameSquattingKeys.collisions(), + queryFn: ({ signal, pageParam }) => + service.admin.getNameSquattingCollisions(signal, pageParam, COLLISIONS_BATCH_SIZE), + initialPageParam: 0, + getNextPageParam: lastPage => (lastPage.hasMore ? lastPage.nextOffset : undefined), + select: mergeCollisionPages, + retry: false, + refetchInterval: REFRESH_INTERVAL_MS + }); +}; + +export const useNameSquattingAllowlist = () => { + const { service } = useContext(MainContext); + return useInfiniteQuery({ + queryKey: nameSquattingKeys.allowlist(), + queryFn: ({ signal, pageParam }) => + service.admin.getNameSquattingAllowlist(signal, pageParam, ALLOWLIST_PAGE_SIZE), + initialPageParam: 0, + getNextPageParam: lastPage => (lastPage.hasMore ? lastPage.page + 1 : undefined), + select: mergeAllowlistPages + }); +}; + +/** Never retried, for the same reason as the collisions: a 503 means the lookup ran out of time. */ +export const useNameSquattingNamespacePairs = (view: NamespacePairsView) => { + const { service } = useContext(MainContext); + return useInfiniteQuery({ + queryKey: nameSquattingKeys.namespaces(view), + queryFn: ({ signal, pageParam }) => + service.admin.getNameSquattingNamespacePairs( + signal, + view.popularOnly, + view.sort, + pageParam, + NAMESPACE_PAIRS_PAGE_SIZE + ), + initialPageParam: 0, + getNextPageParam: lastPage => (lastPage.hasMore ? lastPage.offset + lastPage.pairs.length : undefined), + select: mergeNamespacePairPages, + retry: false, + refetchInterval: REFRESH_INTERVAL_MS + }); +}; + +export const useNameSquattingNamespaceAllowlist = () => { + const { service } = useContext(MainContext); + return useInfiniteQuery({ + queryKey: nameSquattingKeys.namespaceAllowlist(), + queryFn: ({ signal, pageParam }) => + service.admin.getNameSquattingNamespaceAllowlist(signal, pageParam, ALLOWLIST_PAGE_SIZE), + initialPageParam: 0, + getNextPageParam: (lastPage: NameSquattingNamespaceAllowlist) => + lastPage.hasMore ? lastPage.page + 1 : undefined, + // An allow removed meanwhile shifts the next page back by one, repeating its first entry. + select: data => [...new Map(data.pages.flatMap(page => page.allows).map(allow => [allow.id, allow])).values()] + }); +}; + +/** + * Allows pairs of namespaces one after another. Both views of the Namespaces tab and the allowlist change, + * so every name squatting query is refreshed, however far it got. + */ +export const useAllowNameSquattingNamespaces = () => { + const { service } = useContext(MainContext); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (requests: NameSquattingNamespaceAllowRequest[]) => { + for (const request of requests) { + await service.admin.allowNameSquattingNamespaces(request); + } + }, + onSettled: () => queryClient.invalidateQueries({ queryKey: nameSquattingKeys.all }) + }); +}; + +/** + * Allows pairs one after another. Settling rather than succeeding refreshes both lists, so pairs + * allowed before a failure leave the Collisions tab too. + */ +export const useAllowNameSquattingPairs = () => { + const { service } = useContext(MainContext); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (requests: NameSquattingAllowRequest[]) => { + for (const request of requests) { + await service.admin.allowNameSquattingPair(request); + } + }, + onSettled: () => queryClient.invalidateQueries({ queryKey: nameSquattingKeys.all }) + }); +}; + +/** Removes allows one after another; like allowing, refreshes both lists however far it got. */ +export const useRemoveNameSquattingAllows = () => { + const { service } = useContext(MainContext); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: async (ids: number[]) => { + for (const id of ids) { + await service.admin.removeNameSquattingAllow(id); + } + }, + onSettled: () => queryClient.invalidateQueries({ queryKey: nameSquattingKeys.all }) + }); +}; + +/** Soft-deletes the named versions of an extension, as the admin Extensions page does. */ +export const useDeleteExtension = () => { + const { service } = useContext(MainContext); + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (req: { + namespace: string; + extension: string; + targetPlatformVersions: Pick[]; + }) => service.admin.deleteExtensions(req), + onSuccess: (_result, req) => + Promise.all([ + queryClient.invalidateQueries({ queryKey: nameSquattingKeys.collisions() }), + queryClient.invalidateQueries({ queryKey: ['admin', 'extension', req.namespace, req.extension] }) + ]) + }); +}; diff --git a/webui/test/unit/admin-name-squatting-request.spec.ts b/webui/test/unit/admin-name-squatting-request.spec.ts new file mode 100644 index 000000000..d49014d9e --- /dev/null +++ b/webui/test/unit/admin-name-squatting-request.spec.ts @@ -0,0 +1,105 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { jsonResponse, stubFetch } from './support/fetch'; +import { ExtensionRegistryService } from '../../src/extension-registry-service'; + +// Every mutator fetches a CSRF token first, so assertions look at the last call. +const csrfToken = () => jsonResponse({ header: 'X-XSRF-TOKEN', value: 'token' }); + +describe('admin name squatting requests', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('asks for the collisions batch at the offset it was given', async () => { + const fetchMock = stubFetch(jsonResponse({ groups: [], nextOffset: 0, hasMore: false })); + const service = new ExtensionRegistryService('https://registry.test'); + + await service.admin.getNameSquattingCollisions(new AbortController().signal, 50, 25); + + expect(String(fetchMock.mock.calls[0][0])).toBe( + 'https://registry.test/admin/name-squatting/collisions?offset=50&size=25' + ); + }); + + it('asks for the allowlist page it was given', async () => { + const fetchMock = stubFetch(jsonResponse({ groups: [], page: 2, hasMore: false })); + const service = new ExtensionRegistryService('https://registry.test'); + + await service.admin.getNameSquattingAllowlist(new AbortController().signal, 2, 25); + + expect(String(fetchMock.mock.calls[0][0])).toBe( + 'https://registry.test/admin/name-squatting/allowlist?page=2&size=25' + ); + }); + + it('posts an allowed pair to the allowlist', async () => { + const fetchMock = stubFetch(csrfToken(), jsonResponse({ success: 'ok' })); + const service = new ExtensionRegistryService('https://registry.test'); + const request = { namespace: 'b', extension: 'x', otherNamespace: 'a', otherExtension: 'x' }; + + await service.admin.allowNameSquattingPair(request); + + const [url, init] = fetchMock.mock.calls.at(-1)!; + expect(String(url)).toBe('https://registry.test/admin/name-squatting/allowlist'); + expect(init.method).toBe('POST'); + expect(JSON.parse(init.body)).toEqual(request); + }); + + // Removing the wrong id silently reports somebody else's pair again. + it('deletes the allow its id names', async () => { + const fetchMock = stubFetch(csrfToken(), jsonResponse({ success: 'ok' })); + const service = new ExtensionRegistryService('https://registry.test'); + + await service.admin.removeNameSquattingAllow(42); + + const [url, init] = fetchMock.mock.calls.at(-1)!; + expect(String(url)).toBe('https://registry.test/admin/name-squatting/allowlist/42'); + expect(init.method).toBe('DELETE'); + }); + + it('asks for the namespace pairs of the view and page it was given', async () => { + const fetchMock = stubFetch(jsonResponse({ pairs: [], total: 0, popularTotal: 0, offset: 25, hasMore: false })); + const service = new ExtensionRegistryService('https://registry.test'); + + await service.admin.getNameSquattingNamespacePairs(new AbortController().signal, false, 'newest', 25, 25); + + expect(String(fetchMock.mock.calls[0][0])).toBe( + 'https://registry.test/admin/name-squatting/namespaces?popularOnly=false&sort=newest&offset=25&size=25' + ); + }); + + it('asks for the namespace allowlist page it was given', async () => { + const fetchMock = stubFetch(jsonResponse({ allows: [], page: 1, hasMore: false })); + const service = new ExtensionRegistryService('https://registry.test'); + + await service.admin.getNameSquattingNamespaceAllowlist(new AbortController().signal, 1, 25); + + expect(String(fetchMock.mock.calls[0][0])).toBe( + 'https://registry.test/admin/name-squatting/namespaces/allowlist?page=1&size=25' + ); + }); + + it('posts an allowed namespace pair to the namespace allowlist', async () => { + const fetchMock = stubFetch(csrfToken(), jsonResponse({ success: 'ok' })); + const service = new ExtensionRegistryService('https://registry.test'); + const request = { namespace: 'redhaat', otherNamespace: 'redhat', reason: 'Same organization' }; + + await service.admin.allowNameSquattingNamespaces(request); + + const [url, init] = fetchMock.mock.calls.at(-1)!; + expect(String(url)).toBe('https://registry.test/admin/name-squatting/namespaces/allowlist'); + expect(init.method).toBe('POST'); + expect(JSON.parse(init.body)).toEqual(request); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/allowlist-tab.spec.tsx b/webui/test/unit/pages/admin-dashboard/name-squatting/allowlist-tab.spec.tsx new file mode 100644 index 000000000..ff1485c10 --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/allowlist-tab.spec.tsx @@ -0,0 +1,159 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it, vi } from 'vitest'; +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ExtensionRegistryService } from '../../../../../src/extension-registry-service'; +import type { NameSquattingAllow, NameSquattingExtension } from '../../../../../src/extension-registry-types'; +import { AllowlistTab } from '../../../../../src/pages/admin-dashboard/name-squatting/allowlist-tab'; +import { renderWithProviders } from '../../../support/test-providers'; + +const ext = (namespace: string, name: string): NameSquattingExtension => ({ + namespace, + name, + displayName: name, + downloadCount: 0, + activeVersionCount: 1, + active: true +}); + +const allow = (id: number, other: string, renamed = false): NameSquattingAllow => ({ + id, + other: ext(other, 'snippets'), + field: 'DISPLAY_NAME', + similarity: 0.7, + value: 'React Snippets', + otherValue: 'React Snippets Pro', + renamed, + reason: id === 1 ? 'Generic snippet pack names' : undefined, + decidedBy: 'a.rivera', + decidedAt: '2026-10-01T00:00:00Z' +}); + +const mountTab = (admin: Record, route = '/') => { + renderWithProviders(, { + route, + mainContext: { service: { admin } as unknown as ExtensionRegistryService } + }); + return admin; +}; + +const allowlist = { + groups: [ + { extension: ext('snippets-co', 'react-snippets'), allows: [allow(1, 'rsnip'), allow(2, 'es7-tools')] }, + { extension: ext('prettier-dev', 'prettier-eslint'), allows: [allow(3, 'esbenp', true)] } + ], + page: 0, + hasMore: false +}; + +describe('AllowlistTab', () => { + it('lists the pairs of an allowed extension once it is expanded', async () => { + const user = userEvent.setup(); + mountTab({ getNameSquattingAllowlist: vi.fn().mockResolvedValue(allowlist) }); + + await user.click(await screen.findByRole('button', { name: /show the allowed pairs of snippets-co/i })); + + expect(screen.getByText('rsnip.snippets')).toBeInTheDocument(); + expect(screen.getByText('Generic snippet pack names')).toBeInTheDocument(); + expect(screen.getByText('No reason given')).toBeInTheDocument(); + }); + + it('narrows to the extensions with a pair renamed since it was allowed', async () => { + const user = userEvent.setup(); + mountTab({ getNameSquattingAllowlist: vi.fn().mockResolvedValue(allowlist) }); + await screen.findByText('snippets-co.react-snippets'); + + await user.click(screen.getByLabelText('Names changed since allowed')); + + expect(screen.queryByText('snippets-co.react-snippets')).not.toBeInTheDocument(); + expect(screen.getByText('prettier-dev.prettier-eslint')).toBeInTheDocument(); + }); + + it('removes every allow of an extension with "Remove all"', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingAllowlist: vi.fn().mockResolvedValue(allowlist), + removeNameSquattingAllow: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Remove all' })); + await user.click(screen.getByRole('button', { name: 'Remove 2 allows' })); + + await waitFor(() => expect(admin.removeNameSquattingAllow).toHaveBeenCalledTimes(2)); + expect(admin.removeNameSquattingAllow).toHaveBeenCalledWith(1); + expect(admin.removeNameSquattingAllow).toHaveBeenCalledWith(2); + }); + + // Pairs removed before a failure are gone on the server, so the list has to be refetched anyway. + it('reports a failed removal in the dialog and refreshes the list', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingAllowlist: vi.fn().mockResolvedValue(allowlist), + removeNameSquattingAllow: vi + .fn() + .mockResolvedValueOnce({ success: 'ok' }) + .mockRejectedValueOnce({ error: 'Allowed pair not found' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Remove all' })); + await user.click(screen.getByRole('button', { name: 'Remove 2 allows' })); + + expect(await screen.findByText(/allowed pair not found/i)).toBeInTheDocument(); + await waitFor(() => expect(admin.getNameSquattingAllowlist).toHaveBeenCalledTimes(2)); + }); + + it('lists the allowed namespace pairs once namespaces are picked, and removes the one asked', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingAllowlist: vi.fn().mockResolvedValue(allowlist), + getNameSquattingNamespaceAllowlist: vi.fn().mockResolvedValue({ + allows: [ + { + id: 7, + namespace: 'redhaat', + otherNamespace: 'redhat', + similarity: 0.5, + reason: 'Same organization', + decidedBy: 'a.rivera', + decidedAt: '2026-10-01T00:00:00Z' + } + ], + page: 0, + hasMore: false + }), + removeNameSquattingAllow: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + await screen.findByText('snippets-co.react-snippets'); + + await user.click(screen.getByRole('button', { name: 'Namespaces' })); + expect(await screen.findByText('Same organization')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Remove' })); + await user.click(screen.getByRole('button', { name: 'Remove allow' })); + + await waitFor(() => expect(admin.removeNameSquattingAllow).toHaveBeenCalledWith(7)); + await waitFor(() => expect(admin.getNameSquattingNamespaceAllowlist).toHaveBeenCalledTimes(2)); + }); + + it('opens the namespace allowlist its link names', async () => { + mountTab( + { + getNameSquattingNamespaceAllowlist: vi.fn().mockResolvedValue({ allows: [], page: 0, hasMore: false }) + }, + '/?tab=allowlist&kind=namespaces' + ); + + expect(await screen.findByText('No allowed namespaces yet')).toBeInTheDocument(); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/collisions-tab.spec.tsx b/webui/test/unit/pages/admin-dashboard/name-squatting/collisions-tab.spec.tsx new file mode 100644 index 000000000..8a2e551ae --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/collisions-tab.spec.tsx @@ -0,0 +1,276 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it, vi } from 'vitest'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ExtensionRegistryService } from '../../../../../src/extension-registry-service'; +import type { + NameSquattingCollisions, + NameSquattingExtension, + NameSquattingLookalike +} from '../../../../../src/extension-registry-types'; +import { CollisionsTab } from '../../../../../src/pages/admin-dashboard/name-squatting/collisions-tab'; +import { renderWithProviders } from '../../../support/test-providers'; + +const ext = (namespace: string, name: string, displayName = name): NameSquattingExtension => ({ + namespace, + name, + displayName, + downloadCount: 1200, + publishedDate: '2024-01-01T00:00:00Z', + activeVersionCount: 2, + active: true +}); + +const lookalike = (namespace: string, name: string, exact: boolean): NameSquattingLookalike => ({ + extension: ext(namespace, name, 'Python'), + matches: [{ field: 'DISPLAY_NAME', value: 'Python', lookalikeValue: 'Python', similarity: 1, exact }], + namespaceSimilarity: 0, + flaggedAt: '2026-11-01T00:00:00Z' +}); + +const anchor = ext('ms-python', 'python', 'Python'); + +const page = (lookalikes: NameSquattingLookalike[], hasMore = false): NameSquattingCollisions => ({ + groups: [{ anchor, lookalikes }], + nextOffset: 25, + hasMore +}); + +// not named render*, so the testing-library naming rule does not treat the stub it returns as a render result +const mountTab = (admin: Record) => { + renderWithProviders(, { + mainContext: { service: { admin } as unknown as ExtensionRegistryService } + }); + return admin; +}; + +describe('CollisionsTab', () => { + it('lists the extensions published later under the one published first', async () => { + mountTab({ + getNameSquattingCollisions: vi.fn().mockResolvedValue(page([lookalike('pyth0n', 'python', true)])) + }); + + expect(await screen.findByText('pyth0n.python')).toBeInTheDocument(); + expect(screen.getByText('ms-python.python')).toBeInTheDocument(); + expect(screen.getByText('Exact')).toBeInTheDocument(); + }); + + it('shows when the names were looked up, and looks them up again on request', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi.fn().mockResolvedValue(page([lookalike('pyth0n', 'python', true)])) + }); + + expect(await screen.findByText(/^Updated /)).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Check again' })); + + await waitFor(() => expect(admin.getNameSquattingCollisions).toHaveBeenCalledTimes(2)); + }); + + it('explains a lookup stopped by the statement timeout', async () => { + mountTab({ + getNameSquattingCollisions: vi.fn().mockRejectedValue({ error: 'timed out', status: 503 }) + }); + + expect(await screen.findByText(/the check took too long and was stopped/i)).toBeInTheDocument(); + }); + + it('says nothing was found rather than nothing matched when the server found nothing', async () => { + mountTab({ + getNameSquattingCollisions: vi.fn().mockResolvedValue({ groups: [], nextOffset: 0, hasMore: false }) + }); + + expect(await screen.findByText('No similar names found')).toBeInTheDocument(); + }); + + it('hides look-alikes without an exact match when only exact ones are asked for', async () => { + const user = userEvent.setup(); + mountTab({ + getNameSquattingCollisions: vi + .fn() + .mockResolvedValue(page([lookalike('pyth0n', 'python', true), lookalike('labs', 'pythom', false)])) + }); + await screen.findByText('labs.pythom'); + + await user.click(screen.getByLabelText('Exact matches only')); + + expect(screen.queryByText('labs.pythom')).not.toBeInTheDocument(); + expect(screen.getByText('pyth0n.python')).toBeInTheDocument(); + }); + + it('loads the next batch from the offset the server returned', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi + .fn() + .mockResolvedValueOnce(page([lookalike('pyth0n', 'python', true)], true)) + .mockResolvedValueOnce(page([lookalike('labs', 'pythom', false)])) + }); + + await user.click(await screen.findByRole('button', { name: 'Load more groups' })); + + expect(await screen.findByText('labs.pythom')).toBeInTheDocument(); + expect(admin.getNameSquattingCollisions).toHaveBeenLastCalledWith(expect.anything(), 25, 25); + // the anchor of both batches stays one group + expect(screen.getAllByText('ms-python.python')).toHaveLength(1); + }); + + // The server stores the look-alike as the allowed side; swapping them would list the pair under + // the extension published first on the Allowlist tab. + it('allows the look-alike alongside the extension it resembles, with the reason given', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi.fn().mockResolvedValue(page([lookalike('pyth0n', 'python', true)])), + allowNameSquattingPair: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Allow pyth0n.python' })); + await user.type(screen.getByLabelText(/reason/i), ' same publisher '); + await user.click(screen.getByRole('button', { name: 'Allow pair' })); + + await waitFor(() => + expect(admin.allowNameSquattingPair).toHaveBeenCalledWith({ + namespace: 'pyth0n', + extension: 'python', + otherNamespace: 'ms-python', + otherExtension: 'python', + reason: 'same publisher' + }) + ); + await waitFor(() => expect(admin.getNameSquattingCollisions).toHaveBeenCalledTimes(2)); + }); + + it('allows every look-alike of a group from its header', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi + .fn() + .mockResolvedValue(page([lookalike('pyth0n', 'python', true), lookalike('labs', 'pythom', false)])), + allowNameSquattingPair: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click( + await screen.findByRole('button', { name: 'Allow every extension published after ms-python.python' }) + ); + // the extension both resemble is named once, its look-alikes under it + const list = within(screen.getByRole('list', { name: 'Pairs to allow' })); + expect(list.getAllByText('ms-python.python')).toHaveLength(1); + expect(list.getByText('labs.pythom')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Allow 2 pairs' })); + + await waitFor(() => expect(admin.allowNameSquattingPair).toHaveBeenCalledTimes(2)); + expect(admin.allowNameSquattingPair).toHaveBeenCalledWith(expect.objectContaining({ namespace: 'labs' })); + }); + + // A selection made before a filter changed must not allow pairs the admin can no longer see. + it('allows only the selected pairs the filters still show', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi + .fn() + .mockResolvedValue(page([lookalike('pyth0n', 'python', true), lookalike('labs', 'pythom', false)])), + allowNameSquattingPair: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('checkbox', { name: 'Select all' })); + await user.click(screen.getByLabelText('Exact matches only')); + expect(screen.getByText('1 pair selected')).toBeInTheDocument(); + await user.click(screen.getByRole('button', { name: 'Allow selected' })); + await user.click(screen.getByRole('button', { name: 'Allow pair' })); + + await waitFor(() => expect(admin.allowNameSquattingPair).toHaveBeenCalledTimes(1)); + expect(admin.allowNameSquattingPair).toHaveBeenCalledWith(expect.objectContaining({ namespace: 'pyth0n' })); + }); + + // The delete endpoint removes only the versions it is named; a removed one would fail the request. + it('deletes every active version of the later extension once its id is typed', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi.fn().mockResolvedValue(page([lookalike('pyth0n', 'python', true)])), + getExtension: vi.fn().mockResolvedValue({ + namespace: 'pyth0n', + name: 'python', + allTargetPlatformVersions: [ + { + version: '1.0.1', + targetPlatforms: [ + { targetPlatform: 'linux-x64', removed: false }, + { targetPlatform: 'win32-x64', removed: true } + ] + }, + { version: '1.0.0', targetPlatforms: [{ targetPlatform: 'universal', removed: false }] } + ] + }), + deleteExtensions: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Delete pyth0n.python' })); + const dialog = await screen.findByRole('dialog'); + const confirm = within(dialog).getByRole('button', { name: 'Delete extension' }); + await within(dialog).findByText(/all 2 versions \(2 platforms\)/i); + expect(confirm).toBeDisabled(); + expect(within(dialog).queryByText(/published after/i)).not.toBeInTheDocument(); + + await user.type(within(dialog).getByLabelText(/to confirm/i), 'pyth0n.python'); + await user.click(confirm); + + await waitFor(() => + expect(admin.deleteExtensions).toHaveBeenCalledWith({ + namespace: 'pyth0n', + extension: 'python', + targetPlatformVersions: [ + { version: '1.0.1', targetPlatform: 'linux-x64' }, + { version: '1.0.0', targetPlatform: 'universal' } + ] + }) + ); + }); + + // Someone may publish an extension here before its author does, so the first published is not trusted. + it('deletes the extension published first, warning that the later ones regroup', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingCollisions: vi + .fn() + .mockResolvedValue(page([lookalike('pyth0n', 'python', true), lookalike('labs', 'pythom', false)])), + getExtension: vi.fn().mockResolvedValue({ + namespace: 'ms-python', + name: 'python', + allTargetPlatformVersions: [ + { version: '2.0.0', targetPlatforms: [{ targetPlatform: 'universal', removed: false }] } + ] + }), + deleteExtensions: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Delete ms-python.python' })); + const dialog = await screen.findByRole('dialog'); + expect( + within(dialog).getByText(/2 extensions published after ms-python\.python resemble it/i) + ).toBeInTheDocument(); + await within(dialog).findByText(/its only version is removed/i); + + await user.type(within(dialog).getByLabelText(/to confirm/i), 'ms-python.python'); + await user.click(within(dialog).getByRole('button', { name: 'Delete extension' })); + + await waitFor(() => + expect(admin.deleteExtensions).toHaveBeenCalledWith({ + namespace: 'ms-python', + extension: 'python', + targetPlatformVersions: [{ version: '2.0.0', targetPlatform: 'universal' }] + }) + ); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/name-diff.spec.ts b/webui/test/unit/pages/admin-dashboard/name-squatting/name-diff.spec.ts new file mode 100644 index 000000000..b958af797 --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/name-diff.spec.ts @@ -0,0 +1,46 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it } from 'vitest'; +import { diffNames } from '../../../../../src/pages/admin-dashboard/name-squatting/name-diff'; + +const changed = (segments: { text: string; changed: boolean }[]) => + segments.filter(segment => segment.changed).map(segment => segment.text); + +describe('diffNames', () => { + it('marks a swapped character on both sides', () => { + const [a, b] = diffNames('python', 'pyth0n'); + + expect(changed(a)).toEqual(['o']); + expect(changed(b)).toEqual(['0']); + }); + + it('marks only the added characters of the longer name', () => { + const [a, b] = diffNames('ESLint', 'ESLint Pro'); + + expect(changed(a)).toEqual([]); + expect(changed(b)).toEqual([' Pro']); + }); + + // The similarity check ignores case, so a case-only difference is not one worth highlighting. + it('ignores case but keeps each name spelled as given', () => { + const [a, b] = diffNames('Go', 'go'); + + expect(a).toEqual([{ text: 'Go', changed: false }]); + expect(b).toEqual([{ text: 'go', changed: false }]); + }); + + it('handles an empty name', () => { + expect(diffNames('', 'abc')).toEqual([[], [{ text: 'abc', changed: true }]]); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting-model.spec.ts b/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting-model.spec.ts new file mode 100644 index 000000000..44ed23b8c --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting-model.spec.ts @@ -0,0 +1,192 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it } from 'vitest'; +import type { + NameSquattingAllowlistGroup, + NameSquattingExtension, + NameSquattingGroup +} from '../../../../../src/extension-registry-types'; +import { + filterAllowlistGroups, + filterCollisionGroups, + formatSimilarity +} from '../../../../../src/pages/admin-dashboard/name-squatting/name-squatting-model'; +import { + mergeAllowlistPages, + mergeCollisionPages, + mergeNamespacePairPages +} from '../../../../../src/pages/admin-dashboard/name-squatting/use-name-squatting'; + +const ext = (namespace: string, name: string, displayName = name): NameSquattingExtension => ({ + namespace, + name, + displayName, + downloadCount: 0, + activeVersionCount: 1, + active: true +}); + +const group: NameSquattingGroup = { + anchor: ext('ms-python', 'python', 'Python'), + lookalikes: [ + { + extension: ext('pyth0n', 'python', 'Python'), + matches: [ + { field: 'DISPLAY_NAME', value: 'Python', lookalikeValue: 'Python', similarity: 1, exact: true }, + { field: 'NAME', value: 'python', lookalikeValue: 'python', similarity: 1, exact: true } + ], + namespaceSimilarity: 0.2 + }, + { + extension: ext('labs', 'pythom', 'Pythom'), + matches: [{ field: 'NAME', value: 'python', lookalikeValue: 'pythom', similarity: 0.56, exact: false }], + namespaceSimilarity: 0 + } + ] +}; + +const bothFields = new Set(['NAME', 'DISPLAY_NAME'] as const); + +describe('filterCollisionGroups', () => { + it('keeps only the matches on the chosen fields and drops look-alikes left with none', () => { + const [filtered] = filterCollisionGroups([group], { + fields: new Set(['DISPLAY_NAME'] as const), + exactOnly: false, + query: '' + }); + + expect(filtered.lookalikes.map(lookalike => lookalike.extension.namespace)).toEqual(['pyth0n']); + expect(filtered.lookalikes[0].matches.map(match => match.field)).toEqual(['DISPLAY_NAME']); + }); + + it('drops a group none of whose look-alikes is an exact match when only exact ones are asked for', () => { + const fuzzyOnly = { ...group, lookalikes: [group.lookalikes[1]] }; + + expect(filterCollisionGroups([fuzzyOnly], { fields: bothFields, exactOnly: true, query: '' })).toEqual([]); + }); + + it('keeps a whole group when the query names its anchor', () => { + const [filtered] = filterCollisionGroups([group], { fields: bothFields, exactOnly: false, query: 'MS-PY' }); + + expect(filtered.lookalikes).toHaveLength(2); + }); + + it('matches the query against display names too', () => { + expect(filterCollisionGroups([group], { fields: bothFields, exactOnly: false, query: 'pythom' })).toHaveLength( + 1 + ); + expect(filterCollisionGroups([group], { fields: bothFields, exactOnly: false, query: 'rust' })).toEqual([]); + }); +}); + +describe('filterAllowlistGroups', () => { + const allowGroup = (renamed: boolean): NameSquattingAllowlistGroup => ({ + extension: ext(renamed ? 'renamed' : 'kept', 'x'), + allows: [ + { + id: renamed ? 1 : 2, + other: ext('a', 'x'), + field: 'NAME', + similarity: 1, + value: 'x', + otherValue: 'x', + renamed, + decidedAt: '2026-11-01T00:00:00Z' + } + ] + }); + + it('keeps only the groups with a pair renamed since it was allowed', () => { + const filtered = filterAllowlistGroups([allowGroup(false), allowGroup(true)], { + renamedOnly: true, + query: '' + }); + + expect(filtered.map(g => g.extension.namespace)).toEqual(['renamed']); + }); +}); + +describe('formatSimilarity', () => { + // Trigram similarity ignores punctuation, so it can reach 1 for names that are not equal. + it('calls only an exact match exact', () => { + expect(formatSimilarity(1, true)).toBe('Exact'); + expect(formatSimilarity(1, false)).toBe('100%'); + expect(formatSimilarity(0.564, false)).toBe('56%'); + }); +}); + +describe('merging pages', () => { + // Batches are cut by candidate, so one anchor can head a group in two of them. + it('shows an anchor resembled in two batches as one group, each look-alike once', () => { + const [first, second] = group.lookalikes; + const merged = mergeCollisionPages({ + pageParams: [0, 25], + pages: [ + { groups: [{ anchor: group.anchor, lookalikes: [first] }], nextOffset: 25, hasMore: true }, + { groups: [{ anchor: group.anchor, lookalikes: [first, second] }], nextOffset: 50, hasMore: false } + ] + }); + + expect(merged).toHaveLength(1); + expect(merged[0].lookalikes.map(lookalike => lookalike.extension.namespace)).toEqual(['pyth0n', 'labs']); + }); + + it('shows an allowed extension split across two pages once', () => { + const allow = (id: number) => ({ + id, + other: ext('a', `x${id}`), + field: 'NAME' as const, + similarity: 0.8, + value: 'x', + otherValue: 'x', + renamed: false, + decidedAt: '2026-11-01T00:00:00Z' + }); + const extension = ext('b', 'x'); + const merged = mergeAllowlistPages({ + pageParams: [0, 1], + pages: [ + { groups: [{ extension, allows: [allow(1)] }], page: 0, hasMore: true }, + { groups: [{ extension, allows: [allow(1), allow(2)] }], page: 1, hasMore: false } + ] + }); + + expect(merged).toHaveLength(1); + expect(merged[0].allows.map(a => a.id)).toEqual([1, 2]); + }); + + // The server looks the pairs up again once its copy expires, which can push a pair onto the next page. + it('shows a namespace pair repeated on the next page once, with the latest totals', () => { + const namespace = (name: string) => ({ name, downloads: 0, activeExtensions: 1 }); + const pair = (lookalike: string) => ({ + target: namespace('redhat'), + lookalike: namespace(lookalike), + editDistance: 1, + similarity: 0.5, + separatorOnly: false, + sharedMember: false, + popular: true + }); + const merged = mergeNamespacePairPages({ + pageParams: [0, 1], + pages: [ + { pairs: [pair('redhaat')], total: 2, popularTotal: 2, offset: 0, hasMore: true }, + { pairs: [pair('redhaat'), pair('red-hat')], total: 3, popularTotal: 2, offset: 1, hasMore: false } + ] + }); + + expect(merged.pairs.map(p => p.lookalike.name)).toEqual(['redhaat', 'red-hat']); + expect(merged.total).toBe(3); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting.spec.tsx b/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting.spec.tsx new file mode 100644 index 000000000..a7dbdea36 --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/name-squatting.spec.tsx @@ -0,0 +1,54 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it, vi } from 'vitest'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ExtensionRegistryService } from '../../../../../src/extension-registry-service'; +import { NameSquatting } from '../../../../../src/pages/admin-dashboard/name-squatting/name-squatting'; +import { renderWithProviders } from '../../../support/test-providers'; + +const service = () => + ({ + admin: { + getNameSquattingCollisions: vi.fn().mockResolvedValue({ groups: [], nextOffset: 0, hasMore: false }), + getNameSquattingAllowlist: vi.fn().mockResolvedValue({ groups: [], page: 0, hasMore: false }), + getNameSquattingNamespacePairs: vi + .fn() + .mockResolvedValue({ pairs: [], total: 0, popularTotal: 0, offset: 0, hasMore: false }) + } + }) as unknown as ExtensionRegistryService; + +describe('NameSquatting', () => { + it('opens the tab its link names', async () => { + renderWithProviders(, { route: '/?tab=allowlist', mainContext: { service: service() } }); + + expect(await screen.findByText('No allowed pairs yet')).toBeInTheDocument(); + }); + + it('opens the namespaces tab its link names', async () => { + renderWithProviders(, { route: '/?tab=namespaces', mainContext: { service: service() } }); + + expect(await screen.findByText('No similar namespace names found')).toBeInTheDocument(); + }); + + it('switches between the collisions and the allowlist', async () => { + const user = userEvent.setup(); + renderWithProviders(, { mainContext: { service: service() } }); + expect(await screen.findByText('No similar names found')).toBeInTheDocument(); + + await user.click(screen.getByRole('tab', { name: 'Allowlist' })); + + expect(await screen.findByText('No allowed pairs yet')).toBeInTheDocument(); + }); +}); diff --git a/webui/test/unit/pages/admin-dashboard/name-squatting/namespaces-tab.spec.tsx b/webui/test/unit/pages/admin-dashboard/name-squatting/namespaces-tab.spec.tsx new file mode 100644 index 000000000..6ba8a41d9 --- /dev/null +++ b/webui/test/unit/pages/admin-dashboard/name-squatting/namespaces-tab.spec.tsx @@ -0,0 +1,200 @@ +/****************************************************************************** + * Copyright (c) 2026 Contributors to the Eclipse Foundation. + * + * See the NOTICE file(s) distributed with this work for additional + * information regarding copyright ownership. + * + * This program and the accompanying materials are made available under the + * terms of the Eclipse Public License 2.0 which is available at + * https://www.eclipse.org/legal/epl-2.0. + * + * SPDX-License-Identifier: EPL-2.0 + *****************************************************************************/ + +import { describe, expect, it, vi } from 'vitest'; +import { screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { ExtensionRegistryService } from '../../../../../src/extension-registry-service'; +import type { + NameSquattingNamespace, + NameSquattingNamespacePair, + NameSquattingNamespacePairs +} from '../../../../../src/extension-registry-types'; +import { NamespacesTab } from '../../../../../src/pages/admin-dashboard/name-squatting/namespaces-tab'; +import { renderWithProviders } from '../../../support/test-providers'; + +const namespace = (name: string, downloads: number): NameSquattingNamespace => ({ + name, + downloads, + activeExtensions: 1, + firstPublished: '2024-01-01T00:00:00Z' +}); + +const pair = (lookalike: string, overrides: Partial = {}): NameSquattingNamespacePair => ({ + target: namespace('redhat', 50_000), + lookalike: namespace(lookalike, 10), + editDistance: 1, + similarity: 0.5, + separatorOnly: false, + sharedMember: false, + popular: true, + ...overrides +}); + +const page = ( + pairs: NameSquattingNamespacePair[], + { offset = 0, hasMore = false, total = pairs.length, popularTotal = pairs.length } = {} +): NameSquattingNamespacePairs => ({ pairs, total, popularTotal, offset, hasMore }); + +// not named render*, so the testing-library naming rule does not treat the stub it returns as a render result +const mountTab = (admin: Record, route = '/?tab=namespaces') => { + renderWithProviders(, { + route, + mainContext: { service: { admin } as unknown as ExtensionRegistryService } + }); + return admin; +}; + +describe('NamespacesTab', () => { + it('lists each pair with its target and look-alike, counting what the popular filter hides', async () => { + const admin = mountTab({ + getNameSquattingNamespacePairs: vi + .fn() + .mockResolvedValue(page([pair('redhaat', { sharedMember: true })], { total: 7, popularTotal: 1 })) + }); + + await screen.findByText('redhaat'); + const [, target, lookalike, comparison] = within(screen.getAllByRole('row')[1]).getAllByRole('cell'); + expect(within(target).getByText('redhat')).toBeInTheDocument(); + expect(within(lookalike).getByText('redhaat')).toBeInTheDocument(); + expect(within(comparison).getByText('1 edit')).toBeInTheDocument(); + expect(within(comparison).getByText('Shared member')).toBeInTheDocument(); + expect(screen.getByText(/showing 1 of 1 pair with a popular target · 7 in all/i)).toBeInTheDocument(); + expect(admin.getNameSquattingNamespacePairs).toHaveBeenCalledWith(expect.anything(), true, 'downloads', 0, 25); + }); + + // Showing all pairs is how quiet, long-term squatting on niche namespaces gets reviewed. + it('asks for every pair once all pairs are shown', async () => { + const user = userEvent.setup(); + const admin = mountTab({ getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([pair('redhaat')])) }); + await screen.findByText('redhaat'); + + await user.click(screen.getByRole('button', { name: 'All pairs' })); + + await waitFor(() => + expect(admin.getNameSquattingNamespacePairs).toHaveBeenLastCalledWith( + expect.anything(), + false, + 'downloads', + 0, + 25 + ) + ); + }); + + it('asks for the newest look-alikes first when sorted that way', async () => { + const user = userEvent.setup(); + const admin = mountTab({ getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([pair('redhaat')])) }); + await screen.findByText('redhaat'); + + await user.click(screen.getByRole('button', { name: 'Newest look-alike first' })); + + await waitFor(() => + expect(admin.getNameSquattingNamespacePairs).toHaveBeenLastCalledWith( + expect.anything(), + true, + 'newest', + 0, + 25 + ) + ); + }); + + it('opens the view its link names', async () => { + const admin = mountTab( + { getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([pair('redhaat')])) }, + '/?tab=namespaces&targets=all&sort=newest' + ); + + await screen.findByText('redhaat'); + expect(admin.getNameSquattingNamespacePairs).toHaveBeenCalledWith(expect.anything(), false, 'newest', 0, 25); + expect(screen.getByRole('button', { name: 'All pairs' })).toHaveAttribute('aria-pressed', 'true'); + expect(screen.getByRole('button', { name: 'Newest look-alike first' })).toHaveAttribute('aria-pressed', 'true'); + }); + + it('points to the full list when no pair has a popular target', async () => { + mountTab({ + getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([], { total: 3, popularTotal: 0 })) + }); + + expect(await screen.findByText('No pairs with a popular target')).toBeInTheDocument(); + expect(screen.getByText(/to see the other 3 pairs/i)).toBeInTheDocument(); + }); + + it('loads the next page from the offset after the pairs it has', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingNamespacePairs: vi + .fn() + .mockResolvedValueOnce(page([pair('redhaat'), pair('red-hat')], { hasMore: true, total: 3 })) + .mockResolvedValueOnce(page([pair('redhet')], { offset: 2, total: 3 })) + }); + + await user.click(await screen.findByRole('button', { name: 'Load more pairs' })); + + expect(await screen.findByText('redhet')).toBeInTheDocument(); + expect(admin.getNameSquattingNamespacePairs).toHaveBeenLastCalledWith( + expect.anything(), + true, + 'downloads', + 2, + 25 + ); + }); + + it('explains a lookup stopped by the statement timeout', async () => { + mountTab({ getNameSquattingNamespacePairs: vi.fn().mockRejectedValue({ error: 'timed out', status: 503 }) }); + + expect(await screen.findByText(/the check took too long and was stopped/i)).toBeInTheDocument(); + }); + + // The server stores the look-alike first; the allowlist reads the pair that way round. + it('allows the look-alike alongside the target, with the reason given, and refreshes the pairs', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([pair('redhaat')])), + allowNameSquattingNamespaces: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('button', { name: 'Allow redhaat' })); + await user.type(screen.getByLabelText(/reason/i), ' same organization '); + await user.click(screen.getByRole('button', { name: 'Allow pair' })); + + await waitFor(() => + expect(admin.allowNameSquattingNamespaces).toHaveBeenCalledWith({ + namespace: 'redhaat', + otherNamespace: 'redhat', + reason: 'same organization' + }) + ); + await waitFor(() => expect(admin.getNameSquattingNamespacePairs).toHaveBeenCalledTimes(2)); + }); + + it('allows every selected pair', async () => { + const user = userEvent.setup(); + const admin = mountTab({ + getNameSquattingNamespacePairs: vi.fn().mockResolvedValue(page([pair('redhaat'), pair('redhet')])), + allowNameSquattingNamespaces: vi.fn().mockResolvedValue({ success: 'ok' }) + }); + + await user.click(await screen.findByRole('checkbox', { name: 'Select redhaat and redhat' })); + await user.click(screen.getByRole('checkbox', { name: 'Select redhet and redhat' })); + await user.click(screen.getByRole('button', { name: 'Allow selected' })); + await user.click(screen.getByRole('button', { name: 'Allow 2 pairs' })); + + await waitFor(() => expect(admin.allowNameSquattingNamespaces).toHaveBeenCalledTimes(2)); + expect(admin.allowNameSquattingNamespaces).toHaveBeenCalledWith( + expect.objectContaining({ namespace: 'redhet' }) + ); + }); +});