codeant-ai-for-open-source[bot] commented on code in PR #36495: URL: https://github.com/apache/superset/pull/36495#discussion_r2624938837
########## docs/plugins/remark-localize-badges.mjs: ########## @@ -0,0 +1,224 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * Remark plugin to localize badge images from shields.io and similar services. + * + * This plugin downloads badge SVGs at build time and serves them locally, + * avoiding external dependencies and caching issues with dynamic badges. + * + * Inspired by Apache Commons' fixshields.py approach. + */ + +import { visit } from 'unist-util-visit'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as crypto from 'crypto'; + +// Badge domains to localize (always localize all URLs from these domains) +const BADGE_DOMAINS = [ + 'img.shields.io', + 'badge.fury.io', + 'codecov.io', + 'badgen.net', + 'nodei.co', +]; + +// Patterns for badge URLs on other domains (e.g., GitHub Actions badges) +const BADGE_PATH_PATTERNS = [ + /github\.com\/.*\/actions\/workflows\/.*\/badge\.svg/, + /github\.com\/.*\/badge\.svg/, +]; + +// Cache for downloaded badges (persists across files in a single build) +const badgeCache = new Map(); + +// Track if we've already ensured the badges directory exists +let badgesDirCreated = false; + +/** + * Generate a stable filename for a badge URL + */ +function getBadgeFilename(url) { + const hash = crypto.createHash('md5').update(url).digest('hex').slice(0, 12); + // Extract a readable name from the URL + const urlPath = new URL(url).pathname; + const readablePart = urlPath + .replace(/^\//, '') + .replace(/[^a-zA-Z0-9-]/g, '_') + .slice(0, 40); + return `${readablePart}_${hash}.svg`; +} + +/** + * Check if a URL is a badge we should localize + */ +function isBadgeUrl(url) { + if (!url) return false; + try { + const parsed = new URL(url); + // Check if it's from a known badge domain + if (BADGE_DOMAINS.some((domain) => parsed.hostname.includes(domain))) { + return true; + } + // Check if it matches a badge path pattern + return BADGE_PATH_PATTERNS.some((pattern) => pattern.test(url)); + } catch { + return false; + } +} + +/** + * Download a badge and return the local path + */ +async function downloadBadge(url, staticDir) { + // Check cache first + if (badgeCache.has(url)) { + return badgeCache.get(url); + } + + const badgesDir = path.join(staticDir, 'badges'); + + // Ensure badges directory exists + if (!badgesDirCreated) { + fs.mkdirSync(badgesDir, { recursive: true }); + badgesDirCreated = true; + } + + const filename = getBadgeFilename(url); + const localPath = path.join(badgesDir, filename); + const webPath = `/badges/${filename}`; + + // Check if already downloaded in a previous build + if (fs.existsSync(localPath)) { + badgeCache.set(url, webPath); + return webPath; + } + + console.log(`[remark-localize-badges] Downloading: ${url}`); + + try { + const response = await fetch(url, { + headers: { + // Some services need a user agent + 'User-Agent': 'Mozilla/5.0 (compatible; DocusaurusBuild/1.0)', + Accept: 'image/svg+xml,image/*,*/*', + }, + // Follow redirects + redirect: 'follow', + }); + + if (!response.ok) { + throw new Error(`HTTP ${response.status}: ${response.statusText}`); + } + + const contentType = response.headers.get('content-type') || ''; + const content = await response.text(); + + // Validate it's actually an SVG or image + if ( + !contentType.includes('svg') && + !contentType.includes('image') && Review Comment: **Suggestion:** The current validation treats any `image/*` response as acceptable and then saves it as UTF-8 text, which will silently corrupt non-SVG badges (e.g., PNGs) instead of failing the build as intended; restricting acceptance to actual SVG content avoids generating broken badge files. [logic error] **Severity Level:** Minor ⚠️ ```suggestion // Validate it's actually an SVG document if ( !contentType.includes('svg') && ``` <details> <summary><b>Why it matters? ⭐ </b></summary> The PR currently allows any "image/*" content-type and then uses response.text() + utf8 write. That will corrupt binary images (PNG, GIF) silently. The suggestion to restrict acceptance to true SVG content is correct: badges are expected to be SVG and we should fail rather than save a corrupted file. This is a real logic/runtime problem, not cosmetic. </details> <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** docs/plugins/remark-localize-badges.mjs **Line:** 134:137 **Comment:** *Logic Error: The current validation treats any `image/*` response as acceptable and then saves it as UTF-8 text, which will silently corrupt non-SVG badges (e.g., PNGs) instead of failing the build as intended; restricting acceptance to actual SVG content avoids generating broken badge files. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. ``` </details> ########## docs/plugins/remark-localize-badges.mjs: ########## @@ -0,0 +1,224 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +/** + * Remark plugin to localize badge images from shields.io and similar services. + * + * This plugin downloads badge SVGs at build time and serves them locally, + * avoiding external dependencies and caching issues with dynamic badges. + * + * Inspired by Apache Commons' fixshields.py approach. + */ + +import { visit } from 'unist-util-visit'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as crypto from 'crypto'; + +// Badge domains to localize (always localize all URLs from these domains) +const BADGE_DOMAINS = [ + 'img.shields.io', + 'badge.fury.io', + 'codecov.io', + 'badgen.net', + 'nodei.co', +]; + +// Patterns for badge URLs on other domains (e.g., GitHub Actions badges) +const BADGE_PATH_PATTERNS = [ + /github\.com\/.*\/actions\/workflows\/.*\/badge\.svg/, + /github\.com\/.*\/badge\.svg/, +]; + +// Cache for downloaded badges (persists across files in a single build) +const badgeCache = new Map(); + +// Track if we've already ensured the badges directory exists +let badgesDirCreated = false; + +/** + * Generate a stable filename for a badge URL + */ +function getBadgeFilename(url) { + const hash = crypto.createHash('md5').update(url).digest('hex').slice(0, 12); + // Extract a readable name from the URL + const urlPath = new URL(url).pathname; + const readablePart = urlPath + .replace(/^\//, '') + .replace(/[^a-zA-Z0-9-]/g, '_') + .slice(0, 40); + return `${readablePart}_${hash}.svg`; +} + +/** + * Check if a URL is a badge we should localize + */ +function isBadgeUrl(url) { + if (!url) return false; + try { + const parsed = new URL(url); + // Check if it's from a known badge domain + if (BADGE_DOMAINS.some((domain) => parsed.hostname.includes(domain))) { Review Comment: **Suggestion:** The domain allowlist check uses `hostname.includes(domain)`, so a host like `img.shields.io.attacker.com` will pass as allowed even though it is not actually the intended badge provider, which weakens the protection against fetching badges from unexpected domains; tightening this to exact domains or proper subdomains fixes the issue. [security] **Severity Level:** Critical 🚨 ```suggestion // Check if it's from a known badge domain (exact match or subdomain) if ( BADGE_DOMAINS.some( (domain) => parsed.hostname === domain || parsed.hostname.endsWith(`.${domain}`), ) ) { ``` <details> <summary><b>Why it matters? ⭐ </b></summary> Using hostname.includes(domain) will match attacker-controlled hosts like img.shields.io.attacker.com. Tightening the check to exact match or valid subdomain (hostname === domain || hostname.endsWith(`.${domain}`)) fixes a genuine security/host validation issue. This is a simple, correct, and low-risk improvement. </details> <details> <summary><b>Prompt for AI Agent 🤖 </b></summary> ```mdx This is a comment left during a code review. **Path:** docs/plugins/remark-localize-badges.mjs **Line:** 76:77 **Comment:** *Security: The domain allowlist check uses `hostname.includes(domain)`, so a host like `img.shields.io.attacker.com` will pass as allowed even though it is not actually the intended badge provider, which weakens the protection against fetching badges from unexpected domains; tightening this to exact domains or proper subdomains fixes the issue. Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise. ``` </details> -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
