diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index ddd9dc6..18e4516 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -3,7 +3,9 @@ {"id":"ifcurl-p60","title":"Viewer: no element click-to-identify — can't get GlobalId or properties","description":"There is no way to click on a mesh in the viewer and see which IFC element it represents. Reviewers can see geometry but cannot reference specific elements — they can't discover a GlobalId to put in a selector URL, can't see the element name/type/Psets, and can't say 'this specific wall' in a BCF or Forgejo comment. This breaks the collaboration workflow at its foundation: every useful feedback comment needs to identify specific elements. Need: click or hover on a surface to highlight it and show a properties panel (name, type, GlobalId, key Psets). The GlobalId should be copyable into the selector field or URL. The ThatOpen components library provides the tools for this (OBC.IfcRelationsIndexer, element property queries).","status":"closed","priority":1,"issue_type":"feature","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-04-24T11:02:33Z","created_by":"Bruno Postle","updated_at":"2026-04-24T11:47:23Z","started_at":"2026-04-24T11:14:57Z","closed_at":"2026-04-24T11:47:23Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0} {"id":"ifcurl-4l7","title":"viewer.html: scale= URLs don't load in orthographic mode","description":"applyCameraParam() reads the camera= and fov= parameters from the URL and applies them, but never reads scale= or switches the camera to orthographic (parallel) projection. URLs like ?camera=...\u0026scale=50 will load in perspective mode instead of orthographic. The OBC OrthoPerspectiveCamera can switch modes, but the code path to set parallel projection and apply the scale value is missing from applyCameraParam.","status":"closed","priority":1,"issue_type":"bug","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-04-24T09:04:51Z","created_by":"Bruno Postle","updated_at":"2026-04-24T10:56:29Z","started_at":"2026-04-24T10:50:19Z","closed_at":"2026-04-24T10:56:29Z","close_reason":"Closed","dependency_count":0,"dependent_count":0,"comment_count":0} {"id":"ifcurl-362","title":"Add missing server-config files: gitconfig-ifcmerge and gitattributes","description":"forgejo/README.md documents deploying two files that don't exist in the repo: forgejo/server-config/gitconfig-ifcmerge and forgejo/server-config/gitattributes. Both are required for the ifcmerge git merge driver to work in bare Forgejo repos. The README even includes 'sudo cp forgejo/server-config/gitattributes /etc/gitattributes' and 'sudo git config --system include.path .../gitconfig-ifcmerge', but the files themselves are absent. Anyone following the deployment instructions will hit a 'file not found' error. Need to create both files with the content described in the README.","status":"closed","priority":1,"issue_type":"bug","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-04-24T09:04:31Z","created_by":"Bruno Postle","updated_at":"2026-04-24T10:51:47Z","started_at":"2026-04-24T10:50:15Z","closed_at":"2026-04-24T10:51:47Z","close_reason":"Files already exist: forgejo/server-config/gitconfig-ifcmerge and gitattributes are both present and correct. Missed in initial review.","dependency_count":0,"dependent_count":0,"comment_count":0} -{"id":"ifcurl-2yd","title":"Security review: OpenCDE CDE routes (OAuth2 proxy + document picker)","description":"Perform a security review of the CDE-related code added in foundation_api.py and the select-documents additions to documents_api.py. Areas to examine:\\n- OAuth2 proxy: does proxying client_secret server-side introduce SSRF or credential leak risks? Are Forgejo error responses safely forwarded without leaking internal detail?\\n- Picker HTML: is callback_url validated before embedding? Could a crafted callback_url cause open redirect to an attacker-controlled host? Is the JSON embedding in \u003cscript\u003e safe against XSS (\u003c/script\u003e injection test exists but review the escaping logic)?\\n- document_id encoding: can a malformed document_id returned from the picker cause decode_document_id to crash or expose unexpected data?\\n- Rate limiting: do the new /foundation/ and /select-documents endpoints inherit the rate-limit middleware?\\n- Auth forwarding: the document picker UI calls Forgejo API with credentials:include (session cookie). Could a malicious callback_url cause the picker to exfiltrate the session cookie?\\n- Input validation: are all Pydantic models tight enough to reject unexpected fields?\\nProduce a prioritised list of findings with recommended fixes.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-07T11:21:23Z","created_by":"Bruno Postle","updated_at":"2026-06-07T11:28:58Z","started_at":"2026-06-07T11:28:58Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"id":"ifcurl-e9g","title":"Security review: viewer.js and viewer HTML","description":"Perform a security review of the browser-side viewer code. Files to cover: forgejo/custom/public/assets/viewer.js and forgejo/custom/public/assets/viewer.html (or equivalent). Areas to examine: ifc:// URL parsing and handling of untrusted URL components before passing to API calls or displaying in the UI, postMessage or cross-origin communication patterns, innerHTML or other unsafe DOM sinks fed from URL parameters or API responses, camera/selector parameter injection into API URLs, BCF file parsing (Zip content, XML parsing) for injection or path traversal, any eval() or dynamic script execution, handling of Forgejo API responses in the metadata/query panels, content security policy considerations, handling of the ifc:// protocol in OS-registered handler (ifcurl-open/register). Produce a prioritised list of findings with recommended fixes.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-07T11:51:09Z","created_by":"Bruno Postle","updated_at":"2026-06-07T11:51:34Z","started_at":"2026-06-07T11:51:34Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"id":"ifcurl-b99","title":"Security review: Python API service (service.py, bcf_api.py, documents_api.py)","description":"Perform a security review of the core Python API service code. Files to cover: ifcurl/service.py (rate limiting, SSRF protection, caching, all endpoints), ifcurl/bcf_api.py (BCF 3.0 REST routes, Forgejo proxy, GUID encoding), ifcurl/documents_api.py (OpenCDE Documents API, select-documents picker), ifcurl/foundation_api.py (OAuth2 proxy routes). Areas to examine: SSRF protection gaps (is _ssrf_check applied consistently to all endpoints that fetch remote content?), sandbox escape paths (does sandboxed rendering fully isolate arbitrary IFC input?), injection risks in Forgejo API proxying (header forwarding, response handling), authentication bypass in BCF routes, document_id encoding/decoding robustness, input validation on all Pydantic models, any path traversal in file or cache operations, tier-4 cache poisoning via mutable/immutable ref misclassification. Produce a prioritised list of findings with recommended fixes.","status":"in_progress","priority":2,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-07T11:51:06Z","created_by":"Bruno Postle","updated_at":"2026-06-07T11:51:32Z","started_at":"2026-06-07T11:51:32Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"id":"ifcurl-2yd","title":"Security review: OpenCDE CDE routes (OAuth2 proxy + document picker)","description":"Perform a security review of the CDE-related code added in foundation_api.py and the select-documents additions to documents_api.py. Areas to examine:\\n- OAuth2 proxy: does proxying client_secret server-side introduce SSRF or credential leak risks? Are Forgejo error responses safely forwarded without leaking internal detail?\\n- Picker HTML: is callback_url validated before embedding? Could a crafted callback_url cause open redirect to an attacker-controlled host? Is the JSON embedding in \u003cscript\u003e safe against XSS (\u003c/script\u003e injection test exists but review the escaping logic)?\\n- document_id encoding: can a malformed document_id returned from the picker cause decode_document_id to crash or expose unexpected data?\\n- Rate limiting: do the new /foundation/ and /select-documents endpoints inherit the rate-limit middleware?\\n- Auth forwarding: the document picker UI calls Forgejo API with credentials:include (session cookie). Could a malicious callback_url cause the picker to exfiltrate the session cookie?\\n- Input validation: are all Pydantic models tight enough to reject unexpected fields?\\nProduce a prioritised list of findings with recommended fixes.","status":"closed","priority":2,"issue_type":"task","assignee":"Bruno Postle","owner":"bruno@postle.net","created_at":"2026-06-07T11:21:23Z","created_by":"Bruno Postle","updated_at":"2026-06-07T11:48:36Z","started_at":"2026-06-07T11:28:58Z","closed_at":"2026-06-07T11:48:36Z","close_reason":"One confirmed HIGH finding: DOM XSS in renderBreadcrumb via unescaped single quote in onclick — fixed by replacing innerHTML construction with DOM API calls. Three other candidates (callback_url XSS, X-Forwarded-Host injection, Forgejo error disclosure) were false positives.","dependency_count":0,"dependent_count":0,"comment_count":0} {"id":"ifcurl-dy9","title":"Manual test plan: OpenCDE Foundation API OAuth2 and document picker","description":"Step-by-step manual test procedure for the OpenCDE CDE functionality added in commits 48169ff and e2d3d12. Tests to cover:\\n1. Forgejo OAuth2 app registration: go to http://localhost:3000/-/admin/applications, create an app named 'ifcurl', set redirect URI, note client_id/secret, set IFCURL_OAUTH2_CLIENT_ID and IFCURL_OAUTH2_CLIENT_SECRET in ifcurl-api.service environment and restart.\\n2. GET /foundation/versions: confirm foundation 1.1, bcf 3.0, documents 1.0 all appear.\\n3. GET /foundation/1.1/oauth2/auth_url: returns {url, expires_in}; URL contains client_id and response_type=code.\\n4. GET /foundation/1.1/oauth2/auth_url?redirect_uri=...: redirect_uri is appended.\\n5. GET /foundation/1.1/oauth2/auth_url with no env vars set: returns 503.\\n6. POST /foundation/1.1/oauth2/token with a valid code (obtain via browser auth flow): returns access_token and refresh_token.\\n7. POST /foundation/1.1/oauth2/token_refresh with valid refresh_token: returns new access_token.\\n8. POST /documents/1.0/select-documents: returns select_documents_url pointing to /ui endpoint.\\n9. GET the select_documents_url in a browser: page loads, repo dropdown populates from Forgejo API.\\n10. Browse into a repo containing an IFC file, click it: browser redirects to callback_url with document_ids[] param containing a base64url-encoded owner/repo/path string that round-trips through decode_document_id.\\n11. POST /documents/1.0/document-versions with the returned document_id: returns version list with download URLs.","status":"open","priority":2,"issue_type":"task","owner":"bruno@postle.net","created_at":"2026-06-07T11:21:19Z","created_by":"Bruno Postle","updated_at":"2026-06-07T11:21:19Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"id":"ifcurl-m0y","title":"Phase 4: Bonsai integration — open ifc:// URLs natively","description":"Bonsai (the Blender-based IFC authoring tool) should be able to receive and handle ifc:// URLs natively, delegating all git fetch/cache/reconstruction work to the ifcurl Python library.\n\n## What Bonsai needs to implement\n\n**1. ifcurl library integration**\nBonsai calls ifcurl.resolve(url) → local IFC file path, and ifcurl.parse(url) → view state (camera position/direction/up, selector expression, visibility mode, clipping planes). The ifcurl library handles all transport, caching, and file reconstruction — Bonsai sees only a local path.\n\nIf the ifcurl library is not installed, all ifc:// features degrade gracefully: menu entries are hidden or disabled, CLI URL arguments are ignored with a logged warning, and BCF export omits ifc:// fields silently. No errors or broken UI.\n\n**2. 'Open ifc:// URL…' operator and menu entry**\nA Blender operator that accepts an ifc:// URL string, resolves it via ifcurl, opens the resulting IFC file, and applies the view state (camera, selector, visibility). Exposed as a menu entry (File \u003e Open ifc:// URL…) so users can paste a URL directly. This is also the entry point used when launched from ifcurl-open. Hidden when ifcurl is not installed.\n\n**3. CLI / launch argument handling**\nWhen Bonsai is launched with an ifc:// URL as a CLI argument (forwarded by ifcurl-open), the add-on detects it and invokes the same operator. ifcurl-open always launches a new Bonsai instance — there is no mechanism to send a URL to an already-running instance. Silently ignored if ifcurl is not installed.\n\n**4. 'Copy view URL' action**\nSerialise the current Bonsai camera position, active selector/filter, and visibility state into an ifc:// URL pointing to the current file's git repo and ref. Requires the file to have been opened from a git-tracked location. Hidden when ifcurl is not installed.\n\n**5. BCF viewpoint embedding**\nWhen Bonsai exports a BCF file, viewpoints that reference a git-tracked IFC file should include an ifc:// URL in the viewpoint metadata alongside the standard BCF camera fields. Omitted silently when ifcurl is not installed.\n\n**6. Federation: IFCDOCUMENTREFERENCE resolution**\nWhen Bonsai encounters an IFCDOCUMENTREFERENCE whose Location is an ifc:// URL, call ifcurl.resolve() to fetch and open the referenced model. This is the long-term federation goal. Falls back to ignoring the reference when ifcurl is not installed.\n\n## Out of scope here\n- The ifcurl Python library API itself (ifcurl.resolve, ifcurl.parse) — that is Phase 1 work\n- OS handler registration (ifcurl-coh) and dispatcher (ifcurl-7db)","status":"open","priority":2,"issue_type":"feature","owner":"bruno@postle.net","created_at":"2026-06-07T07:20:36Z","created_by":"Bruno Postle","updated_at":"2026-06-07T07:39:58Z","dependency_count":0,"dependent_count":0,"comment_count":0} {"id":"ifcurl-8x4","title":"Deploy and test BCF export","description":"The BCF export was rewritten as pure client-side (commit 7c25e06). The query panel row-click highlight was also added (ifcurl-yhp). Deploy the updated JS assets to Forgejo and run the browser test checklist items 13 and 14 to verify BCF export and round-trip import still work correctly. Also test that clicking a row in the query panel highlights the corresponding element in the 3D view.","status":"open","priority":2,"issue_type":"task","owner":"bruno@postle.net","created_at":"2026-06-07T06:32:36Z","created_by":"Bruno Postle","updated_at":"2026-06-07T07:47:27Z","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/forgejo/custom/public/assets/viewer.html b/forgejo/custom/public/assets/viewer.html index 0e00c47..fac41e1 100644 --- a/forgejo/custom/public/assets/viewer.html +++ b/forgejo/custom/public/assets/viewer.html @@ -170,7 +170,8 @@ (function() { try { var snap = sessionStorage.getItem("viewerSnapshot"); - if (!snap || !new URLSearchParams(location.search).get("url")) return; + if (!snap || !snap.startsWith("data:image/jpeg;base64,")) return; + if (!new URLSearchParams(location.search).get("url")) return; var el = document.createElement("div"); el.id = "snapshot-overlay"; el.style.backgroundImage = "url(" + snap + ")"; diff --git a/forgejo/custom/public/assets/viewer.js b/forgejo/custom/public/assets/viewer.js index dac0f83..230067d 100644 --- a/forgejo/custom/public/assets/viewer.js +++ b/forgejo/custom/public/assets/viewer.js @@ -760,12 +760,20 @@ async function applyQuery(srcUrl, queryPath) { queryTbody.innerHTML = ""; for (const [guid, value] of entries) { const tr = document.createElement("tr"); + tr.style.cursor = "pointer"; const tdGuid = document.createElement("td"); tdGuid.textContent = guid; const tdVal = document.createElement("td"); tdVal.textContent = value; tr.appendChild(tdGuid); tr.appendChild(tdVal); + tr.addEventListener("click", async () => { + if (!components || !loadedModel) return; + const localIds = (await loadedModel.getLocalIdsByGuids([guid])).filter(id => id !== null); + if (!localIds.length) return; + const items = { [loadedModel.modelId]: new Set(localIds) }; + await applyFragmentStyle(components, items, new THREE.Color(0xff8800), 1); + }); queryTbody.appendChild(tr); } queryPanel.style.display = ""; @@ -1088,13 +1096,15 @@ async function populateMetaPanel(components) { // --- Render --- const html = []; + const hesc = s => String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,"""); + if (types.length) { html.push("

Types

"); for (const { name, count } of types) { html.push( `
` + - `${name}` + - `${count}` + + `${hesc(name)}` + + `${hesc(count)}` + `
` ); } @@ -1109,8 +1119,8 @@ async function populateMetaPanel(components) { ); for (const name of storeyNames) { html.push( - `
` + - `${name}` + + `
` + + `${hesc(name)}` + `
` ); } diff --git a/ifcurl/bcf_api.py b/ifcurl/bcf_api.py index 5e70c36..118c59d 100644 --- a/ifcurl/bcf_api.py +++ b/ifcurl/bcf_api.py @@ -47,6 +47,7 @@ from fastapi.responses import JSONResponse, Response from ifcurl.bcf import bcf_viewpoint_to_ifc_url, ifc_url_to_bcf_viewpoint from ifcurl.url import IfcUrl +from ifcurl.auth import get_token_for_host # --------------------------------------------------------------------------- # Config @@ -356,16 +357,27 @@ def get_viewpoint(owner: str, repo: str, tguid: str, vpguid: str, request: Reque @router.get("/projects/{owner}/{repo}/topics/{tguid}/viewpoints/{vpguid}/snapshot") def get_snapshot(owner: str, repo: str, tguid: str, vpguid: str, request: Request) -> Response: + from ifcurl.service import _ssrf_check auth = _auth(request) issue = _find_issue(owner, repo, tguid, auth) comment = _find_comment(owner, repo, vpguid, auth) ifc_url_str = _first_ifc_url(comment.get("body")) if not ifc_url_str: raise HTTPException(status_code=404, detail="No ifc:// URL in viewpoint comment") - headers = {} - if auth: - headers["Authorization"] = auth - r = httpx.get(f"{_PREVIEW_URL}/preview", params={"url": ifc_url_str}, headers=headers, timeout=120) + # Validate the stored ifc:// URL against SSRF rules before fetching. + # The caller's bearer token must NOT be forwarded to the preview service — + # it would then be sent to the git host named in the comment, which may be + # attacker-controlled. Use the server-side token for the ifc:// host instead. + try: + ifc_url = IfcUrl.parse(ifc_url_str) + except ValueError as exc: + raise HTTPException(status_code=422, detail=f"Invalid ifc:// URL in viewpoint: {exc}") from exc + _ssrf_check(ifc_url) + server_token = get_token_for_host(ifc_url.host) if ifc_url.host else None + params: dict = {"url": ifc_url_str} + if server_token: + params["token"] = server_token + r = httpx.get(f"{_PREVIEW_URL}/preview", params=params, timeout=120) if r.status_code != 200: raise HTTPException(status_code=r.status_code, detail="Preview service error") return Response(content=r.content, media_type="image/png") diff --git a/ifcurl/service.py b/ifcurl/service.py index 61861d4..61ab08e 100644 --- a/ifcurl/service.py +++ b/ifcurl/service.py @@ -41,6 +41,7 @@ import hashlib import ipaddress import json import os +import socket import threading import time from collections import OrderedDict @@ -263,18 +264,34 @@ def configure_allowed_hosts(hosts: set[str] | None) -> None: def _is_private_ip(host: str) -> bool: - """Return True if *host* is a literal private/loopback/link-local IP.""" + """Return True if *host* resolves to a private/loopback/link-local address. + + Accepts both literal IP strings and hostnames. For hostnames, all resolved + addresses are checked — if any resolve to a private address the function + returns True, blocking DNS-rebinding / internal-hostname SSRF attacks. + """ bare = host.split(":")[0].strip("[]") # strip port and IPv6 brackets try: + # Fast path: host is already a literal IP address. addr = ipaddress.ip_address(bare) - return ( - addr.is_loopback - or addr.is_link_local - or addr.is_private - or addr.is_reserved - ) + return addr.is_loopback or addr.is_link_local or addr.is_private or addr.is_reserved except ValueError: - return False + pass + # Slow path: resolve the hostname and check all returned addresses. + try: + results = socket.getaddrinfo(bare, None, proto=socket.IPPROTO_TCP) + except OSError: + # Resolution failed — treat as private to fail safe. + return True + for _family, _type, _proto, _canonname, sockaddr in results: + ip_str = sockaddr[0] + try: + addr = ipaddress.ip_address(ip_str) + if addr.is_loopback or addr.is_link_local or addr.is_private or addr.is_reserved: + return True + except ValueError: + return True + return False def _ssrf_check(ifc_url: IfcUrl) -> None: