Repository navigation
Single page viewer #10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
4fd50e9
Single-page SYSMOD viewer (web/): no Flask server needed
claude ef07fc3
web: ports of interfaces, SYSMOD version, cover view; 256 elements pe…
claude 1e7cfd9
web/serve.py: honour ALLOWED_SYSML_SERVER_ORIGINS like the Flask serv…
claude 2f73c6b
web: relay only to ALLOWED_SYSML_SERVER_ORIGINS; no end-anchored regexes
claude d0e6db0
web: SonarCloud findings of PR #10 (reliability, security, maintainab…
claude c371c24
web: remaining SonarCloud and CodeQL findings of PR #10
claude 2f4834c
web/serve.py: mark the plain-HTTP local server as reviewed for SonarC…
claude 1c7595f
web/serve.py: correct syntax of the SonarCloud suppression comment (N…
claude 23aaebb
web/serve.py: plain NOSONAR marker for the local HTTP server
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| """Tests of web/serve.py: the rules of the relay and real HTTP requests against a fake SysML v2 API server. | ||
| Standard library only: python -m unittest tests/test_web_serve.py (pytest runs it too)""" | ||
| import json | ||
| import sys | ||
| import threading | ||
| import unittest | ||
| import urllib.error | ||
| import urllib.parse | ||
| import urllib.request | ||
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | ||
| from pathlib import Path | ||
|
|
||
| sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "web")) | ||
| import serve # noqa: E402 | ||
|
|
||
|
|
||
| class FakeSysml(BaseHTTPRequestHandler): | ||
| """A tiny SysML v2 API server: echoes what it received, pages elements with a Link header.""" | ||
| def log_message(self, *a): | ||
| pass | ||
|
|
||
| def send(self, code, body, headers=None): | ||
| b = json.dumps(body).encode() | ||
| self.send_response(code) | ||
| self.send_header("Content-Type", "application/json") | ||
| for k, v in (headers or {}).items(): | ||
| self.send_header(k, v) | ||
| self.end_headers() | ||
| self.wfile.write(b) | ||
|
|
||
| def do_GET(self): | ||
|
|
||
| u = urllib.parse.urlsplit(self.path) | ||
| if u.path == "/projects": | ||
| return self.send(200, [{"@id": "p-1", "name": "P", "auth": self.headers.get("Authorization", ""), "query": u.query}]) | ||
| if u.path == "/projects/p-1/commits/c/elements": | ||
| return self.send(200, [{"@id": "e-1"}], {"Link": f"<http://127.0.0.1:{self.server.server_address[1]}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\""}) | ||
| if u.path == "/projects/redirect": | ||
| self.send_response(302); self.send_header("Location", "https://example.org/"); self.end_headers(); return | ||
| if u.path == "/projects/html": | ||
| b = b"<html>oops</html>" | ||
| self.send_response(200); self.send_header("Content-Type", "text/html"); self.end_headers(); self.wfile.write(b); return | ||
| if u.path == "/projects/secret": | ||
| return self.send(401, {"error": "unauthorized"}) | ||
| return self.send(404, {"error": "not found"}) | ||
|
|
||
|
|
||
| def start(handler): | ||
| srv = ThreadingHTTPServer(("127.0.0.1", 0), handler) | ||
| threading.Thread(target=srv.serve_forever, daemon=True).start() | ||
| return srv | ||
|
|
||
|
|
||
| ALLOWED = "https://h.org,http://sysml2.intercax.com:9000" | ||
|
|
||
|
|
||
| class Rules(unittest.TestCase): | ||
| def setUp(self): | ||
| import os | ||
| os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = ALLOWED | ||
|
|
||
| def tearDown(self): | ||
| import os | ||
| os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) | ||
| def ok(self, url, expected=None): | ||
| target, error = serve.check_url(url) | ||
| self.assertEqual(error, "", url) | ||
| if expected: | ||
| self.assertEqual(target, expected) | ||
|
|
||
| def refused(self, url, reason): | ||
| self.assertEqual(serve.check_url(url), (None, reason), url) | ||
|
|
||
| def test_allowed(self): | ||
| self.ok("https://h.org/projects") | ||
| self.ok("http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000", "http://sysml2.intercax.com:9000/projects?page%5Bsize%5D=1000") | ||
| self.ok("https://h.org/projects?page[size]=10", "https://h.org/projects?page%5Bsize%5D=10") | ||
| self.ok("https://h.org/api/v1/projects/p/commits/c/elements?page%5Bafter%5D=x") | ||
| self.ok("https://h.org/projects/p/branches/b") | ||
| self.ok("https://H.org/projects", "https://h.org/projects") | ||
|
|
||
| def test_allowed_origins(self): | ||
| import os | ||
| self.refused("https://other.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") | ||
| self.refused("http://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") | ||
| self.refused("http://sysml2.intercax.com:9001/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") | ||
| os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS") | ||
| self.ok("http://localhost:9000/projects") # the default, as for the Flask server | ||
| self.refused("https://h.org/projects", "server not allowed (ALLOWED_SYSML_SERVER_ORIGINS)") | ||
|
|
||
| def test_refused(self): | ||
| self.refused("", "invalid address") | ||
| self.refused("file:///etc/passwd", "only http and https") | ||
| self.refused("https://h.org@evil.org/projects", "invalid address") | ||
| self.refused("https://u:p@h.org/projects", "invalid address") | ||
| self.refused("https://h.org/projects#x", "invalid address") | ||
| self.refused("https://h.org/admin", "not a read endpoint of the SysML v2 API") | ||
| self.refused("https://h.org/projects/p/query-results", "not a read endpoint of the SysML v2 API") | ||
| self.refused("https://h.org/projects/../admin", "invalid path") | ||
| self.refused("https://h.org/projects/%2e%2e", "invalid path") | ||
| self.refused("https://h.org//projects", "invalid path") | ||
| self.refused("https://h.org/projects?x=1", "query not allowed") | ||
| self.refused("https://h.org/projects?page%5Bsize%5D=1&page%5Bsize%5D=2", "query not allowed") | ||
| self.refused("https://h.org/projects?page%5Bsize%5D=x", "query not allowed") | ||
|
|
||
|
|
||
| class Relay(unittest.TestCase): | ||
| @classmethod | ||
| def setUpClass(cls): | ||
| import os | ||
| cls.up = start(FakeSysml) | ||
| os.environ["ALLOWED_SYSML_SERVER_ORIGINS"] = f"http://127.0.0.1:{cls.up.server_address[1]}" | ||
| cls.viewer = start(serve.Handler) | ||
| cls.U = f"http://127.0.0.1:{cls.up.server_address[1]}" | ||
| cls.R = f"http://127.0.0.1:{cls.viewer.server_address[1]}" | ||
|
|
||
| @classmethod | ||
| def tearDownClass(cls): | ||
| import os | ||
| os.environ.pop("ALLOWED_SYSML_SERVER_ORIGINS", None) | ||
| cls.up.shutdown(); cls.viewer.shutdown() | ||
|
|
||
| def get(self, path, headers=None): | ||
| req = urllib.request.Request(self.R + path, headers=headers or {}) | ||
| try: | ||
| with urllib.request.urlopen(req, timeout=10) as r: | ||
| return r.status, r.headers, r.read() | ||
| except urllib.error.HTTPError as e: | ||
| return e.code, e.headers, e.read() | ||
|
|
||
| def relay(self, url, headers=None): | ||
| return self.get("/relay?url=" + urllib.parse.quote(url, safe=""), headers) | ||
|
|
||
| def test_page_and_config(self): | ||
| status, _, body = self.get("/") | ||
| self.assertEqual(status, 200) | ||
| self.assertIn(b'id="sysmod-viewer"', body) | ||
| status, _, body = self.get("/viewer-config.json") | ||
| self.assertEqual(json.loads(body)["relay"]["servers"], [self.U]) | ||
| self.assertEqual(self.get("/serve.py")[0], 404) | ||
|
|
||
| def test_relayed_with_token_and_paging(self): | ||
| status, _, body = self.relay(self.U + "/projects?page%5Bsize%5D=1000", {"X-Relay-Authorization": "Bearer t"}) | ||
| data = json.loads(body)[0] | ||
| self.assertEqual((status, data["auth"], data["query"]), (200, "Bearer t", "page%5Bsize%5D=1000")) | ||
| status, headers, _ = self.relay(self.U + "/projects/p-1/commits/c/elements") | ||
| self.assertEqual(headers["Link"], f"<{self.U}/projects/p-1/commits/c/elements?page%5Bafter%5D=e-1>; rel=\"next\"") | ||
| self.assertIsNone(headers.get("Access-Control-Allow-Origin")) | ||
|
|
||
| def test_errors(self): | ||
| self.assertEqual(self.relay(self.U + "/projects/secret")[0], 401) | ||
| self.assertEqual(self.relay(self.U + "/projects/nothing")[0], 404) | ||
| self.assertEqual(self.relay(self.U + "/projects/redirect")[0], 502) | ||
| self.assertIn(b"did not answer with JSON", self.relay(self.U + "/projects/html")[2]) | ||
| self.assertEqual(self.relay(self.U + "/admin")[0], 400) | ||
| self.assertEqual(self.relay("http://127.0.0.1:1/projects")[0], 400) # not on the list | ||
| self.assertEqual(self.relay("https://example.org/projects")[0], 400) | ||
| self.assertEqual(self.relay(self.U + "/projects", {"Sec-Fetch-Site": "cross-site"})[0], 403) | ||
| status, headers, _ = self.relay(self.U + "/admin") | ||
| self.assertEqual(headers["X-Relay-Error"], "1") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| <!doctype html> | ||
| <html lang="en"> | ||
| <head> | ||
| <meta charset="utf-8"> | ||
| <meta name="viewport" content="width=device-width, initial-scale=1"> | ||
| <meta name="color-scheme" content="light dark"> | ||
| <title>SYSMOD Viewer</title> | ||
| <meta name="description" content="View a SYSMOD project of a SysML v2 model: Atlas, problem statement, stakeholders, needs, requirements, use cases and system context diagrams."> | ||
| <link rel="stylesheet" href="sysmod-viewer.css"> | ||
| </head> | ||
| <body> | ||
| <main> | ||
| <header> | ||
| <p class="stereo m-0">tool</p> | ||
| <h1>SYSMOD Viewer</h1> | ||
| <p class="lead"> | ||
| Shows a <a href="https://sysmod.org">SYSMOD</a> project of a SysML v2 model the way the method structures it: the SYSMOD Atlas, the problem statement, | ||
| the system idea and its objectives, stakeholders, needs, system requirements, system use cases and the system context of every architecture. | ||
| It reads the model with the SysML v2 API (OMG Systems Modeling API). A single page, no server of its own: everything runs in your browser. | ||
| </p> | ||
| </header> | ||
|
|
||
| <div id="sysmod-viewer" class="mt-10" data-config='{"core":"./sysmod-viewer-core.js","api":"./sysmod-viewer-api.js"}'> | ||
| <noscript><p class="ui text-muted">The SYSMOD viewer needs JavaScript.</p></noscript> | ||
|
|
||
| <section class="sv-source" aria-labelledby="sv-source-h" hidden data-js-only> | ||
| <h2 id="sv-source-h" class="display display-md mb-4">Open a model</h2> | ||
| <div class="sv-tabs ui" role="tablist" aria-label="Source of the model"> | ||
| <button type="button" role="tab" id="sv-tab-server" aria-controls="sv-panel-server" aria-selected="true" data-src-tab="server">SysML v2 API server</button> | ||
| <button type="button" role="tab" id="sv-tab-files" aria-controls="sv-panel-files" aria-selected="false" data-src-tab="files">JSON file</button> | ||
| </div> | ||
|
|
||
| <div class="sv-panel" role="tabpanel" id="sv-panel-server" aria-labelledby="sv-tab-server" data-src-panel="server"> | ||
| <p class="m-0 mb-4 max-w-[46rem]" data-relay-note> | ||
| The address of a SysML v2 API server, e.g. the API services of the SysML v2 Pilot Implementation or Open-MBEE Flexo. | ||
| Opened directly, the page can only read servers that allow requests from it (CORS); run <code>python web/serve.py</code> to reach any server through its local relay. | ||
| </p> | ||
| <div class="sv-form"> | ||
| <label class="ui font-semibold" for="sv-url">Server address</label> | ||
| <input id="sv-url" class="sv-input" type="url" inputmode="url" placeholder="http://localhost:9000" autocomplete="url" spellcheck="false" data-url> | ||
| <label class="ui font-semibold" for="sv-token">Token <span class="font-normal text-muted">(optional)</span></label> | ||
| <input id="sv-token" class="sv-input" type="password" placeholder="Bearer …" autocomplete="off" spellcheck="false" data-token> | ||
| <span></span> | ||
| <p class="m-0"> | ||
| <button type="button" class="btn" data-connect>Connect</button> | ||
| <output class="ui text-muted ml-3 sv-status" data-status-server aria-live="polite"></output> | ||
| </p> | ||
| </div> | ||
| <div class="sv-form mt-4" data-proj-row hidden> | ||
| <label class="ui font-semibold" for="sv-proj-filter">Find project</label> | ||
| <input id="sv-proj-filter" class="sv-input" type="search" placeholder="Name or id" data-proj-filter> | ||
| <label class="ui font-semibold" for="sv-proj">Project</label> | ||
| <select id="sv-proj" class="sv-input" data-proj></select> | ||
| <label class="ui font-semibold" for="sv-commit">Commit</label> | ||
| <select id="sv-commit" class="sv-input" data-commit></select> | ||
| <span></span> | ||
| <p class="m-0"><button type="button" class="btn" data-load>Load the model</button></p> | ||
| </div> | ||
| <div class="mt-4" data-err-server></div> | ||
| </div> | ||
|
|
||
| <div class="sv-panel" role="tabpanel" id="sv-panel-files" aria-labelledby="sv-tab-files" data-src-panel="files" hidden> | ||
| <p class="m-0 mb-4 max-w-[46rem]"> | ||
| A <strong>.json file</strong> with the elements of a commit, as <code>GET …/commits/{commit}/elements</code> of the SysML v2 API returns them. | ||
| To view <code>.sysml</code> files, use <a href="https://mbse4u.com/tools/sysmod-viewer/">mbse4u.com/tools/sysmod-viewer</a>, which reads them with a SysML v2 engine in the browser. | ||
| </p> | ||
| <p class="m-0"> | ||
| <label class="btn sv-file-btn" for="sv-files">Choose a file</label> | ||
| <input id="sv-files" class="sr-only" type="file" accept=".json" multiple data-files> | ||
| <output class="ui text-muted ml-3 sv-status" data-status-files aria-live="polite"></output> | ||
| </p> | ||
| <div class="mt-4" data-err-files></div> | ||
| </div> | ||
|
|
||
| <div class="sv-form mt-6" data-pick hidden> | ||
| <label class="ui font-semibold" for="sv-pick">SYSMOD project</label> | ||
| <select id="sv-pick" class="sv-input" data-pick-select></select> | ||
| </div> | ||
| </section> | ||
|
|
||
| <div class="sv-out mt-10" data-out aria-live="polite"></div> | ||
| </div> | ||
|
|
||
| <section class="prose mt-16" aria-labelledby="sv-good-to-know"> | ||
| <h2 id="sv-good-to-know">Good to know</h2> | ||
| <ul> | ||
| <li><strong>Run it:</strong> <code>python web/serve.py</code>, then open <code>http://localhost:8080/</code>. The script needs only Python 3, no packages. Browsers do not run the page from a <code>file://</code> address.</li> | ||
| <li><strong>CORS and http:</strong> a page can only read servers that allow requests from it. <code>serve.py</code> also relays the requests (read-only) to the servers in <code>ALLOWED_SYSML_SERVER_ORIGINS</code> (default <code>http://localhost:9000</code>), including plain <code>http://</code> ones and servers without CORS.</li> | ||
| <li><strong>Token:</strong> optional, passed on as header <code>Authorization</code>; it stays in the page and is never stored. The page address records server, project and commit (not the token).</li> | ||
| <li><strong>SYSMOD v5:</strong> the project is an <code>occurrence def</code> with <code>#project</code> or a specialization of <code>SYSMOD::Project</code>; the SYSMOD library must be in the same project.</li> | ||
| <li><strong>Read-only.</strong> Editing, the AI suggestions and the creation wizard are in the Flask server of this repository (<code>sysmod_api_server.py</code>).</li> | ||
| </ul> | ||
| </section> | ||
| </main> | ||
| <script type="module"> | ||
| // Settings of the server that delivers this page: web/serve.py provides viewer-config.json with its relay. | ||
| const root = document.getElementById('sysmod-viewer'); | ||
| try { | ||
| const r = await fetch('viewer-config.json', { cache: 'no-store' }); | ||
| if (r.ok) { | ||
| const extra = await r.json(); | ||
| root.dataset.config = JSON.stringify({ ...JSON.parse(root.dataset.config), ...extra }); | ||
| if (extra.relay) document.querySelector('[data-relay-note]').append(` Running with serve.py: these servers are reached through its relay: ${extra.relay.servers.join(', ')} (ALLOWED_SYSML_SERVER_ORIGINS).`); | ||
| } | ||
| } catch { /* served without serve.py: no relay */ } | ||
| await import('./sysmod-viewer.js'); | ||
| </script> | ||
| </body> | ||
| </html> |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.