diff --git a/.github/workflows/build_container_image.yml b/.github/workflows/build_container_image.yml index df85909..942bca5 100644 --- a/.github/workflows/build_container_image.yml +++ b/.github/workflows/build_container_image.yml @@ -19,12 +19,12 @@ jobs: run: | if [ "${{ github.ref }}" == "refs/heads/develop" ]; then echo start building api-explorer-ii containers develop branch with latest tag - docker build . --file Dockerfiles/Dockerfile_backend --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ steps.extract_branch.outputs.branch }} --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest + docker build . --file Dockerfiles/Dockerfile_backend --build-arg GIT_COMMIT=$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ steps.extract_branch.outputs.branch }} --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:latest docker build . --file Dockerfiles/Dockerfile_frontend --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}-nginx:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}-nginx:${{ steps.extract_branch.outputs.branch }} --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}-nginx:latest echo building api-explorer-ii containers develop branch with latest tag done else echo start building api-explorer-ii containers non-develop branch without latest tag - docker build . --file Dockerfiles/Dockerfile_backend --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ steps.extract_branch.outputs.branch }} + docker build . --file Dockerfiles/Dockerfile_backend --build-arg GIT_COMMIT=$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}:${{ steps.extract_branch.outputs.branch }} docker build . --file Dockerfiles/Dockerfile_frontend --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}-nginx:$GITHUB_SHA --tag docker.io/${{ env.DOCKER_HUB_ORGANIZATION }}/${{ env.DOCKER_HUB_REPOSITORY }}-nginx:${{ steps.extract_branch.outputs.branch }} echo building api-explorer-ii containers non-develop branch without latest tag done fi diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..cc7dae4 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,21 @@ +name: tests + +on: + pull_request: + push: + branches: + - develop + +jobs: + tests: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: lts/* + cache: npm + - name: Install the dependencies from package-lock.json + run: npm ci + - name: Run all the tests, including the OBP-API contract and the v5.1.0 version floor + run: npx vitest --run diff --git a/.gitignore b/.gitignore index 5ac716c..7e37b93 100644 --- a/.gitignore +++ b/.gitignore @@ -70,3 +70,6 @@ shared-constants.js # Documentation untracked_docs/ + +# Zed editor settings, which open_dev_env writes for each project +.zed/ diff --git a/.zed/settings.json b/.zed/settings.json deleted file mode 100644 index 2e21165..0000000 --- a/.zed/settings.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "theme": { - "mode": "dark", - "dark": "API-Explorer-II-Green", - "light": "API-Explorer-II-Green" - }, - "ui_font_size": 14, - "buffer_font_size": 14, - "terminal": { - "font_size": 13, - "line_height": "comfortable" - }, - "project_panel": { - "button": true, - "default_width": 300, - "dock": "left" - }, - "tab_bar": { - "show": true - }, - "status_bar": { - "show": true - }, - "toolbar": { - "breadcrumbs": true, - "quick_actions": true - }, - "workspace": { - "save_on_focus_change": true - }, - "git": { - "enabled": true, - "autoFetch": true - }, - "format_on_save": "on", - "show_whitespaces": "selection", - "soft_wrap": "prefer_line" -} diff --git a/.zed/tasks.json b/.zed/tasks.json deleted file mode 100644 index e1a2dc8..0000000 --- a/.zed/tasks.json +++ /dev/null @@ -1,8 +0,0 @@ -[ - { - "label": "🟢 Open Terminal Here", - "command": "gnome-terminal", - "args": ["--title=\"🟢 API-Explorer\"", "--working-directory=${workspaceFolder}"], - "reveal": "never" - } -] diff --git a/.zed/theme.json b/.zed/theme.json deleted file mode 100644 index 41abbc2..0000000 --- a/.zed/theme.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "name": "API-Explorer-II-Green", - "author": "Portal/Opey Development Setup", - "themes": [ - { - "name": "API-Explorer-II-Green", - "appearance": "dark", - "style": { - "background": "#1e1e1e", - "foreground": "#d4d4d4", - "cursor": "#28A745", - "selection": "#28A74533", - "selected_line_background": "#28A74511", - "line_number": "#858585", - "active_line_number": "#28A745", - "find_highlight": "#28A745", - "border": "#28A74566", - "panel_background": "#252526", - "panel_focused_border": "#28A745", - "tab_bar_background": "#2d2d30", - "tab_active_background": "#28A74588", - "status_bar_background": "#28A74566", - "title_bar_background": "#28A74544", - "toolbar_background": "#37373d" - } - } - ] -} diff --git a/Dockerfiles/Dockerfile_backend b/Dockerfiles/Dockerfile_backend index 596184c..1c940cf 100644 --- a/Dockerfiles/Dockerfile_backend +++ b/Dockerfiles/Dockerfile_backend @@ -12,6 +12,10 @@ RUN npm run build-server # CMD npm run -d start FROM node:lts-slim +# The commit the image is built from (the image has no .git), reported in Telemetry and on the status page +ARG GIT_COMMIT=unknown +ENV GIT_COMMIT=$GIT_COMMIT + COPY --from=builder /home/node/app/dist-server /home/node/app RUN mkdir /home/node/node_modules COPY --from=builder /home/node/app/node_modules /home/node/node_modules diff --git a/obp-api-contract/contract.json b/obp-api-contract/contract.json new file mode 100644 index 0000000..876bc4f --- /dev/null +++ b/obp-api-contract/contract.json @@ -0,0 +1,660 @@ +{ + "about": "Every OBP-API call API Explorer II makes from its own code: verb, path (OBP placeholders in capitals), the source file and the text that makes the call (needles), the version constants the path is built from (version_from), and the response fields the code reads. Not listed: the calls whose path the user picks while browsing the docs (Try It in Preview.vue and the generic /api/get, /api/create, /api/update and /api/delete proxy in server/routes/obp.ts, including the public docs cache), and the gRPC services page. not_calls lists the lines that name an OBP-API path without being one of the calls. server/test/obpApiContract.test.ts checks this list against the source and against snapshot.json, which obp-api-contract/snapshot.py writes from an OBP-API's resource docs.", + "version_policy": "Each call writes the OBP-API version it needs in its own path. One configured version cannot serve them all, because an endpoint exists only in the versions OBP-API documents it for. The contract test checks every call against the endpoint documented for the version it names and fails on any version below v5.1.0. To move a call to a newer version, change its path and run snapshot.py again.", + "calls": [ + { + "verb": "GET", + "path": "/obp/v5.1.0/ui/suggested-session-timeout", + "source": "src/components/AutoLogout.vue", + "needles": [ + "fetch(`${obpApiHost}/obp/${DEFAULT_OBP_API_VERSION}/ui/suggested-session-timeout`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + } + ], + "reads": [ + "timeout_in_seconds" + ], + "note": "Sent by the browser straight to VITE_OBP_API_HOST, without a token and past the Explorer server, so it also needs CORS. Without the field the Explorer logs out after 301 seconds." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/USER_ID/entitlements", + "source": "src/obp/index.ts", + "needles": [ + "export async function getUserEntitlements()", + "`/obp/${OBP_API_VERSION}/users/${userId}/entitlements`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [ + "list[].role_name", + "list[].bank_id" + ], + "note": "Read by Preview.vue to show which of an endpoint's roles the user holds." + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/users/USER_ID/entitlements", + "source": "src/obp/index.ts", + "needles": [ + "export async function createEntitlement(", + "`/obp/${OBP_API_VERSION}/users/${userId}/entitlements`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "Preview.vue reads only the code and message of an error answer." + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/my/api-collections", + "source": "src/obp/index.ts", + "needles": [ + "const url = `/obp/${OBP_API_VERSION}/my/api-collections`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "Creates the Favourites collection; Content.vue does not read the answer." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/my/api-collections", + "source": "src/obp/index.ts", + "needles": [ + "get(`/obp/${OBP_API_VERSION}/my/api-collections`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [ + "api_collections", + "api_collections[].api_collection_name" + ], + "note": "main.ts checks the list is not empty; SearchNav.vue reads each collection's name." + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "source": "src/obp/index.ts", + "needles": [ + "`/obp/${OBP_API_VERSION}/my/api-collections/${default_collection_name}/api-collection-endpoints`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "Adds an endpoint to Favourites; the answer is not read." + }, + { + "verb": "DELETE", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints/OPERATION_ID", + "source": "src/obp/index.ts", + "needles": [ + "`/obp/${OBP_API_VERSION}/my/api-collections/${default_collection_name}/api-collection-endpoints/${operation_id}`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "Sent through /api/delete. Content.vue shows any non-empty answer as an error." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "source": "src/obp/index.ts", + "needles": [ + "`/obp/${OBP_API_VERSION}/my/api-collections/${collectionName}/api-collection-endpoints`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [ + "api_collection_endpoints[].operation_id" + ], + "note": "Read by main.ts and SearchNav.vue." + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/api-collections/API_COLLECTION_ID/api-collection-endpoints", + "source": "src/obp/index.ts", + "needles": [ + "`obp/${V6_0_0}/api-collections/${collectionId}/api-collection-endpoints`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V6_0_0 = 'v6.0.0'" + } + ], + "reads": [ + "api_collection_endpoints[].operation_id" + ], + "note": "Read by CollectionView.vue." + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/banks", + "source": "src/obp/index.ts", + "needles": [ + "get(`obp/${V6_0_0}/banks`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V6_0_0 = 'v6.0.0'" + } + ], + "reads": [ + "banks[].bank_id", + "banks[].full_name" + ], + "note": "Read by Menu.vue for the bank selector." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/api/versions", + "source": "src/obp/api-version.ts", + "needles": [ + "get(`obp/${API_VERSIONS_LIST_API_VERSION}/api/versions`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const API_VERSIONS_LIST_API_VERSION = 'v7.0.0'" + } + ], + "reads": [ + "scanned_api_versions[].is_active", + "scanned_api_versions[].api_standard", + "scanned_api_versions[].api_short_version", + "scanned_api_versions[].fully_qualified_version" + ], + "note": "main.ts builds the version menu from is_active and fully_qualified_version; resource-docs.ts loads the docs of each active api_standard + api_short_version." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "source": "src/obp/resource-docs.ts", + "needles": [ + "`/obp/${RESOURCE_DOCS_API_VERSION}/resource-docs/${apiStandardAndVersion}/obp`", + "`/obp/${RESOURCE_DOCS_API_VERSION}/resource-docs/${apiStandardAndVersion}/obp?content=dynamic`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const RESOURCE_DOCS_API_VERSION = 'v7.0.0'" + } + ], + "reads": [ + "resource_docs", + "resource_docs[].operation_id", + "resource_docs[].summary", + "resource_docs[].description", + "resource_docs[].tags", + "resource_docs[].request_verb", + "resource_docs[].request_url", + "resource_docs[].specified_url", + "resource_docs[].example_request_body", + "resource_docs[].success_response_body", + "resource_docs[].error_response_bodies", + "resource_docs[].connector_methods", + "resource_docs[].roles[].role", + "resource_docs[].roles[].requires_bank_id", + "resource_docs[].implemented_by.version", + "resource_docs[].implemented_by.function" + ], + "undocumented_fields": [ + "resource_docs", + "resource_docs[].operation_id", + "resource_docs[].summary", + "resource_docs[].description", + "resource_docs[].tags", + "resource_docs[].request_verb", + "resource_docs[].request_url", + "resource_docs[].specified_url", + "resource_docs[].example_request_body", + "resource_docs[].success_response_body", + "resource_docs[].error_response_bodies", + "resource_docs[].connector_methods", + "resource_docs[].roles[].role", + "resource_docs[].roles[].requires_bank_id", + "resource_docs[].implemented_by.version", + "resource_docs[].implemented_by.function" + ], + "note": "API_VERSION is each active version from api/versions (OBPv7.0.0, UKv3.1, ...). The fields are read by Preview.vue, Content.vue, SearchNav.vue, CollectionView.vue and resource-docs.ts. OBP-API documents no typed response for its resource docs, so every field the Explorer reads is listed in undocumented_fields; the test fails here once OBP-API documents one of them." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/domain-apis", + "source": "src/obp/domain-apis.ts", + "needles": [ + "get(`/obp/${RESOURCE_DOCS_API_VERSION}/domain-apis`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const RESOURCE_DOCS_API_VERSION = 'v7.0.0'" + } + ], + "reads": [ + "domain_apis[].bank_id", + "domain_apis[].base_path", + "domain_apis[].title", + "domain_apis[].description", + "domain_apis[].url", + "domain_apis[].version", + "domain_apis[].openapi_url" + ], + "note": "Content.vue shows title, description, url, version and openapi_url." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/banks/BANK_ID/domain-apis/resource-docs", + "source": "src/obp/domain-apis.ts", + "needles": [ + "`/obp/${RESOURCE_DOCS_API_VERSION}/banks/${encodeURIComponent(api.bank_id)}/domain-apis/resource-docs?base_path=${api.base_path}`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const RESOURCE_DOCS_API_VERSION = 'v7.0.0'" + } + ], + "reads": [ + "resource_docs", + "resource_docs[].operation_id", + "resource_docs[].summary", + "resource_docs[].description", + "resource_docs[].tags", + "resource_docs[].request_verb", + "resource_docs[].request_url", + "resource_docs[].specified_url", + "resource_docs[].example_request_body", + "resource_docs[].success_response_body", + "resource_docs[].error_response_bodies", + "resource_docs[].connector_methods", + "resource_docs[].roles[].role", + "resource_docs[].roles[].requires_bank_id", + "resource_docs[].implemented_by.version", + "resource_docs[].implemented_by.function" + ], + "undocumented_fields": [ + "resource_docs", + "resource_docs[].operation_id", + "resource_docs[].summary", + "resource_docs[].description", + "resource_docs[].tags", + "resource_docs[].request_verb", + "resource_docs[].request_url", + "resource_docs[].specified_url", + "resource_docs[].example_request_body", + "resource_docs[].success_response_body", + "resource_docs[].error_response_bodies", + "resource_docs[].connector_methods", + "resource_docs[].roles[].role", + "resource_docs[].roles[].requires_bank_id", + "resource_docs[].implemented_by.version", + "resource_docs[].implemented_by.function" + ], + "note": "Shown like any other version's resource docs. OBP-API documents no typed response for its resource docs, so every field the Explorer reads is listed in undocumented_fields; the test fails here once OBP-API documents one of them." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/api/glossary", + "source": "src/obp/glossary.ts", + "needles": [ + "get(`obp/${GLOSSARY_API_VERSION}/api/glossary`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const GLOSSARY_API_VERSION = 'v5.1.0'" + } + ], + "reads": [ + "glossary_items[].title", + "glossary_items[].description.html" + ], + "note": "Read by GlossaryView.vue, GlossarySearchNav.vue, HelpView.vue and MessageDocsListView.vue." + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/system/connectors", + "source": "src/obp/message-docs.ts", + "needles": [ + "get(`obp/${V6_0_0}/system/connectors`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V6_0_0 = 'v6.0.0'" + } + ], + "reads": [ + "connectors[].connector_name" + ], + "note": "Falls back to a fixed connector list when the call fails." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/message-docs/CONNECTOR", + "source": "src/obp/message-docs.ts", + "needles": [ + "get(`obp/${OBP_API_VERSION}/message-docs/${item}`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "src/obp/index.ts", + "needle": "export const OBP_API_VERSION = DEFAULT_OBP_API_VERSION" + } + ], + "reads": [ + "message_docs[].adapter_implementation.group", + "message_docs[].process", + "message_docs[].description", + "message_docs[].outbound_topic", + "message_docs[].inbound_topic", + "message_docs[].example_outbound_message", + "message_docs[].example_inbound_message", + "message_docs[].requiredFieldInfo", + "message_docs[].dependent_endpoints[].name", + "message_docs[].dependent_endpoints[].version" + ], + "note": "Grouped in message-docs.ts and shown by MessageDocsView.vue." + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/message-docs/CONNECTOR/json-schema", + "source": "src/obp/message-docs.ts", + "needles": [ + "get(`obp/${V6_0_0}/message-docs/${item}/json-schema`)" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V6_0_0 = 'v6.0.0'" + } + ], + "reads": [ + "definitions", + "properties.messages.items[].process", + "properties.messages.items[].description", + "properties.messages.items[].adapter_implementation.group", + "properties.messages.items[].outbound_schema", + "properties.messages.items[].inbound_schema", + "properties.messages.items[].message_format" + ], + "undocumented_fields": [ + "definitions", + "properties.messages.items[].process", + "properties.messages.items[].description", + "properties.messages.items[].adapter_implementation.group", + "properties.messages.items[].outbound_schema", + "properties.messages.items[].inbound_schema", + "properties.messages.items[].message_format" + ], + "note": "The answer is a JSON Schema document; OBP-API documents no typed response for it." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "source": "server/routes/status.ts", + "needles": [ + "`/obp/${RESOURCE_DOCS_API_VERSION}/resource-docs/${version}/obp`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const RESOURCE_DOCS_API_VERSION = 'v7.0.0'" + } + ], + "reads": [], + "note": "Status check: API_VERSION is the server's own version (DEFAULT_OBP_API_VERSION); only an error code is looked at." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/message-docs/CONNECTOR", + "source": "server/routes/status.ts", + "needles": [ + "`/obp/${MESSAGE_DOCS_API_VERSION}/message-docs/${connector}`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const MESSAGE_DOCS_API_VERSION = 'v5.1.0'" + } + ], + "reads": [], + "note": "Status check for each of four fixed connectors; only an error code is looked at." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/api/versions", + "source": "server/routes/status.ts", + "needles": [ + "`/obp/${API_VERSIONS_LIST_API_VERSION}/api/versions`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const API_VERSIONS_LIST_API_VERSION = 'v7.0.0'" + } + ], + "reads": [], + "note": "Status check; only an error code is looked at." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/current", + "source": "server/routes/status.ts", + "needles": [ + "`/obp/${version}/users/current`", + "const version = obpClientService.getOBPVersion()" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "server/services/OBPClientService.ts", + "needle": "version: DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "Status check for a logged-in visitor; only an error code is looked at." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/well-known", + "source": "server/routes/status.ts", + "needles": [ + "/obp/${V5_1_0}/well-known" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V5_1_0 = 'v5.1.0'" + } + ], + "reads": [ + "well_known_uris", + "well_known_uris[].provider", + "well_known_uris[].url" + ], + "undocumented_fields": [ + "well_known_uris", + "well_known_uris[].provider", + "well_known_uris[].url" + ], + "note": "OIDC debug page. OBP-API answers with WellKnownUrisJsonV510 (well_known_uris: provider, url; see code/api/v5_1_0/Http4s510.scala getOAuth2ServerWellKnown) but its resource doc shows jwks_uris only, in v5.1.0, v6.0.0 and v7.0.0." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/current", + "source": "server/routes/user.ts", + "needles": [ + "`/obp/${version}/users/current`", + "const version = DEFAULT_OBP_API_VERSION" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + } + ], + "reads": [ + "user_id" + ], + "note": "GET /api/user/current answers with the OBP user_id, or the token's sub when this call fails." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/well-known", + "source": "server/services/OAuth2ProviderManager.ts", + "needles": [ + "/obp/${V5_1_0}/well-known" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const V5_1_0 = 'v5.1.0'" + } + ], + "reads": [ + "well_known_uris", + "well_known_uris[].provider", + "well_known_uris[].url" + ], + "undocumented_fields": [ + "well_known_uris", + "well_known_uris[].provider", + "well_known_uris[].url" + ], + "note": "The login providers the Explorer offers. OBP-API answers with WellKnownUrisJsonV510 (well_known_uris: provider, url; see code/api/v5_1_0/Http4s510.scala getOAuth2ServerWellKnown) but its resource doc shows jwks_uris only, in v5.1.0, v6.0.0 and v7.0.0." + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/root", + "source": "server/services/ObpReachability.ts", + "needles": [ + "`/obp/${version}/root`" + ], + "version_from": [ + { + "source": "src/shared-constants.ts", + "needle": "export const DEFAULT_OBP_API_VERSION = 'v5.1.0'" + }, + { + "source": "server/services/OBPClientService.ts", + "needle": "version: DEFAULT_OBP_API_VERSION" + } + ], + "reads": [], + "note": "GET /api/ready; status.ts passes obpClientService.getOBPVersion(). Only an error code is looked at." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/banks/SYS/my/roles/ROLE_NAME", + "source": "server/utils/obpRoleCheck.ts", + "needles": [ + "`${obpApiHost}/obp/v7.0.0/banks/SYS/my/roles/${encodeURIComponent(role)}`" + ], + "reads": [ + "allowed_for_auth_modes" + ], + "note": "Guards the Explorer's own monitoring routes with an OBP Role." + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/consumers/current/identity", + "source": "server/services/OIDCServiceHealth.ts", + "needles": [ + "/obp/v7.0.0/consumers/current/identity" + ], + "reads": [ + "consumer_id", + "consumer_name" + ], + "note": "Names the Consumer of the provider health check's client_credentials token." + } + ], + "not_calls": [ + { + "source": "src/components/Preview.vue", + "needle": "operation.specified_url.replace(/\\/obp\\/v\\d+\\.\\d+\\.\\d+\\//, `/obp/${versionWithoutPrefix}/`)", + "reason": "Try It: the path is the chosen endpoint's documented path in the chosen version." + }, + { + "source": "server/app.ts", + "needle": "'ERROR: Check that OBP API is running and returns providers from /obp/v5.1.0/well-known'", + "reason": "Log message about the well-known call in OAuth2ProviderManager.ts." + }, + { + "source": "server/routes/user.ts", + "needle": "console.log('User: Fetching OBP user from /obp/' + version + '/users/current')", + "reason": "Log message about the users/current call made on the next lines." + } + ] +} diff --git a/obp-api-contract/snapshot.json b/obp-api-contract/snapshot.json new file mode 100644 index 0000000..28ca78f --- /dev/null +++ b/obp-api-contract/snapshot.json @@ -0,0 +1,466 @@ +{ + "about": "Written by obp-api-contract/snapshot.py; do not edit by hand.", + "obp_api": { + "https://k8s.openbankproject.com": { + "version": "v7.0.0", + "git_commit": "474d4bcc554f1d8e9516e12d85be121d92410aa5" + } + }, + "taken_at": "2026-11-12T23:23:32Z", + "endpoints": [ + { + "verb": "GET", + "path": "/obp/v5.1.0/ui/suggested-session-timeout", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv5.1.0-suggestedSessionTimeout", + "documented_path": "/obp/v5.1.0/ui/suggested-session-timeout", + "fields": [ + "timeout_in_seconds" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/USER_ID/entitlements", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-getEntitlements", + "documented_path": "/obp/v5.1.0/users/USER_ID/entitlements", + "fields": [ + "list", + "list[]", + "list[].bank_id", + "list[].entitlement_id", + "list[].role_name", + "list[].user_id" + ] + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/users/USER_ID/entitlements", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv2.0.0-addEntitlement", + "documented_path": "/obp/v5.1.0/users/USER_ID/entitlements", + "fields": [ + "bank_id", + "entitlement_id", + "role_name" + ] + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/my/api-collections", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-createMyApiCollection", + "documented_path": "/obp/v5.1.0/my/api-collections", + "fields": [ + "api_collection_id", + "api_collection_name", + "description", + "is_sharable", + "user_id" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/my/api-collections", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-getMyApiCollections", + "documented_path": "/obp/v5.1.0/my/api-collections", + "fields": [ + "api_collections", + "api_collections[]", + "api_collections[].api_collection_id", + "api_collections[].api_collection_name", + "api_collections[].description", + "api_collections[].is_sharable", + "api_collections[].user_id" + ] + }, + { + "verb": "POST", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-createMyApiCollectionEndpoint", + "documented_path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "fields": [ + "api_collection_endpoint_id", + "api_collection_id", + "operation_id" + ] + }, + { + "verb": "DELETE", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints/OPERATION_ID", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-deleteMyApiCollectionEndpoint", + "documented_path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints/OPERATION_ID", + "fields": [ + "value" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-getMyApiCollectionEndpoints", + "documented_path": "/obp/v5.1.0/my/api-collections/API_COLLECTION_NAME/api-collection-endpoints", + "fields": [ + "api_collection_endpoints", + "api_collection_endpoints[]", + "api_collection_endpoints[].api_collection_endpoint_id", + "api_collection_endpoints[].api_collection_id", + "api_collection_endpoints[].operation_id" + ] + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/api-collections/API_COLLECTION_ID/api-collection-endpoints", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv4.0.0-getApiCollectionEndpoints", + "documented_path": "/obp/v6.0.0/api-collections/API_COLLECTION_ID/api-collection-endpoints", + "fields": [ + "api_collection_endpoints", + "api_collection_endpoints[]", + "api_collection_endpoints[].api_collection_endpoint_id", + "api_collection_endpoints[].api_collection_id", + "api_collection_endpoints[].operation_id" + ] + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/banks", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv6.0.0-getBanks", + "documented_path": "/obp/v6.0.0/banks", + "fields": [ + "banks", + "banks[]", + "banks[].attributes", + "banks[].attributes[]", + "banks[].attributes[].name", + "banks[].attributes[].value", + "banks[].bank_code", + "banks[].bank_id", + "banks[].bank_routings", + "banks[].bank_routings[]", + "banks[].bank_routings[].address", + "banks[].bank_routings[].scheme", + "banks[].full_name", + "banks[].logo", + "banks[].website" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/api/versions", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv6.0.0-getScannedApiVersions", + "documented_path": "/obp/v7.0.0/api/versions", + "fields": [ + "scanned_api_versions", + "scanned_api_versions[]", + "scanned_api_versions[].api_short_version", + "scanned_api_versions[].api_standard", + "scanned_api_versions[].fully_qualified_version", + "scanned_api_versions[].is_active", + "scanned_api_versions[].url_prefix" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv1.4.0-getResourceDocsObp", + "documented_path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "fields": [] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/domain-apis", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv7.0.0-getPubliclyDiscoverableDomainApisInEverySpace", + "documented_path": "/obp/v7.0.0/domain-apis", + "fields": [ + "domain_apis", + "domain_apis[]", + "domain_apis[].bank_id", + "domain_apis[].base_path", + "domain_apis[].description", + "domain_apis[].openapi_url", + "domain_apis[].title", + "domain_apis[].url", + "domain_apis[].version" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/banks/BANK_ID/domain-apis/resource-docs", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv7.0.0-getDomainApiResourceDocs", + "documented_path": "/obp/v7.0.0/banks/BANK_ID/domain-apis/resource-docs", + "fields": [] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/api/glossary", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv3.0.0-getApiGlossary", + "documented_path": "/obp/v5.1.0/api/glossary", + "fields": [ + "glossary_items", + "glossary_items[]", + "glossary_items[].description", + "glossary_items[].description.html", + "glossary_items[].description.markdown", + "glossary_items[].title" + ] + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/system/connectors", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv6.0.0-getConnectors", + "documented_path": "/obp/v6.0.0/system/connectors", + "fields": [ + "connectors", + "connectors[]", + "connectors[].connector_name", + "connectors[].is_available_in_method_routing" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/message-docs/CONNECTOR", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv2.2.0-getMessageDocs", + "documented_path": "/obp/v5.1.0/message-docs/CONNECTOR", + "fields": [ + "message_docs", + "message_docs[]", + "message_docs[].adapter_implementation", + "message_docs[].adapter_implementation.group", + "message_docs[].adapter_implementation.suggested_order", + "message_docs[].dependent_endpoints", + "message_docs[].dependent_endpoints[]", + "message_docs[].dependent_endpoints[].name", + "message_docs[].dependent_endpoints[].version", + "message_docs[].description", + "message_docs[].example_inbound_message", + "message_docs[].example_inbound_message.jsonString", + "message_docs[].example_outbound_message", + "message_docs[].example_outbound_message.jsonString", + "message_docs[].inboundAvroSchema", + "message_docs[].inboundAvroSchema.jsonString", + "message_docs[].inbound_topic", + "message_docs[].message_format", + "message_docs[].outboundAvroSchema", + "message_docs[].outboundAvroSchema.jsonString", + "message_docs[].outbound_topic", + "message_docs[].process", + "message_docs[].requiredFieldInfo", + "message_docs[].requiredFieldInfo.data.bankId", + "message_docs[].requiredFieldInfo.data.bankId[]" + ] + }, + { + "verb": "GET", + "path": "/obp/v6.0.0/message-docs/CONNECTOR/json-schema", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv6.0.0-getMessageDocsJsonSchema", + "documented_path": "/obp/v6.0.0/message-docs/CONNECTOR/json-schema", + "fields": [] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv1.4.0-getResourceDocsObp", + "documented_path": "/obp/v7.0.0/resource-docs/API_VERSION/obp", + "fields": [] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/message-docs/CONNECTOR", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv2.2.0-getMessageDocs", + "documented_path": "/obp/v5.1.0/message-docs/CONNECTOR", + "fields": [ + "message_docs", + "message_docs[]", + "message_docs[].adapter_implementation", + "message_docs[].adapter_implementation.group", + "message_docs[].adapter_implementation.suggested_order", + "message_docs[].dependent_endpoints", + "message_docs[].dependent_endpoints[]", + "message_docs[].dependent_endpoints[].name", + "message_docs[].dependent_endpoints[].version", + "message_docs[].description", + "message_docs[].example_inbound_message", + "message_docs[].example_inbound_message.jsonString", + "message_docs[].example_outbound_message", + "message_docs[].example_outbound_message.jsonString", + "message_docs[].inboundAvroSchema", + "message_docs[].inboundAvroSchema.jsonString", + "message_docs[].inbound_topic", + "message_docs[].message_format", + "message_docs[].outboundAvroSchema", + "message_docs[].outboundAvroSchema.jsonString", + "message_docs[].outbound_topic", + "message_docs[].process", + "message_docs[].requiredFieldInfo", + "message_docs[].requiredFieldInfo.data.bankId", + "message_docs[].requiredFieldInfo.data.bankId[]" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/api/versions", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv6.0.0-getScannedApiVersions", + "documented_path": "/obp/v7.0.0/api/versions", + "fields": [ + "scanned_api_versions", + "scanned_api_versions[]", + "scanned_api_versions[].api_short_version", + "scanned_api_versions[].api_standard", + "scanned_api_versions[].fully_qualified_version", + "scanned_api_versions[].is_active", + "scanned_api_versions[].url_prefix" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/current", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv3.0.0-getCurrentUser", + "documented_path": "/obp/v5.1.0/users/current", + "fields": [ + "email", + "entitlements", + "entitlements.list", + "entitlements.list[]", + "entitlements.list[].bank_id", + "entitlements.list[].entitlement_id", + "entitlements.list[].role_name", + "provider", + "provider_id", + "user_id", + "username", + "views", + "views.list", + "views.list[]", + "views.list[].account_id", + "views.list[].bank_id", + "views.list[].view_id" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/well-known", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv5.1.0-getOAuth2ServerWellKnown", + "documented_path": "/obp/v5.1.0/well-known", + "fields": [ + "jwks_uris", + "jwks_uris[]", + "jwks_uris[].jwks_uri" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/users/current", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv3.0.0-getCurrentUser", + "documented_path": "/obp/v5.1.0/users/current", + "fields": [ + "email", + "entitlements", + "entitlements.list", + "entitlements.list[]", + "entitlements.list[].bank_id", + "entitlements.list[].entitlement_id", + "entitlements.list[].role_name", + "provider", + "provider_id", + "user_id", + "username", + "views", + "views.list", + "views.list[]", + "views.list[].account_id", + "views.list[].bank_id", + "views.list[].view_id" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/well-known", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv5.1.0-getOAuth2ServerWellKnown", + "documented_path": "/obp/v5.1.0/well-known", + "fields": [ + "jwks_uris", + "jwks_uris[]", + "jwks_uris[].jwks_uri" + ] + }, + { + "verb": "GET", + "path": "/obp/v5.1.0/root", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv5.1.0-root", + "documented_path": "/obp/v5.1.0/root", + "fields": [ + "connector", + "energy_source", + "energy_source.organisation", + "energy_source.organisation_website", + "git_commit", + "hosted_at", + "hosted_at.organisation", + "hosted_at.organisation_website", + "hosted_by", + "hosted_by.email", + "hosted_by.organisation", + "hosted_by.organisation_website", + "hosted_by.phone", + "hostname", + "local_identity_provider", + "resource_docs_requires_role", + "version", + "version_status" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/banks/SYS/my/roles/ROLE_NAME", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv7.0.0-getMyRole", + "documented_path": "/obp/v7.0.0/banks/BANK_ID/my/roles/ROLE_NAME", + "fields": [ + "allowed_for_auth_modes", + "allowed_for_auth_modes[]", + "bank_id", + "caller", + "caller.application_only", + "caller.consumer_id", + "caller.user_id", + "held_by", + "held_by.consumer", + "held_by.user", + "role_name", + "scopes_required" + ] + }, + { + "verb": "GET", + "path": "/obp/v7.0.0/consumers/current/identity", + "docs_from": "https://k8s.openbankproject.com", + "operation_id": "OBPv7.0.0-getCurrentConsumerIdentity", + "documented_path": "/obp/v7.0.0/consumers/current/identity", + "fields": [ + "consumer_id", + "consumer_name" + ] + } + ] +} diff --git a/obp-api-contract/snapshot.py b/obp-api-contract/snapshot.py new file mode 100644 index 0000000..221f79e --- /dev/null +++ b/obp-api-contract/snapshot.py @@ -0,0 +1,200 @@ +#!/usr/bin/env python3 +# Copyright (C) 2025-2026 TESOBE GmbH +# SPDX-License-Identifier: AGPL-3.0-or-later +# Licensed under the GNU Affero General Public License v3 or later: see the LICENSE and NOTICE files. +"""Write snapshot.json: what an OBP-API documents for each call in contract.json. + + python3 obp-api-contract/snapshot.py --base https://k8s.openbankproject.com \ + [--fallback https://apisandbox.openbankproject.com] + +For every version used in contract.json it reads /obp/{v}/resource-docs/{v}/obp once, +from --base, or from --fallback when --base does not serve that version (a deployment +that switched it off). It finds the endpoint each call reaches and records its operation +id and every response field path, taken from typed_success_response_body. A call with no +endpoint is recorded as missing, so the contract test fails on it. Needs no credentials; +uses only the standard library. + +Matching: OBP writes placeholders in capitals (BANK_ID) and so are some literal segments +(the transaction request type OPEN_CORRIDOR_PROMISE). A segment matches when it is equal, +when the documented one is in capitals (a placeholder for a value the call fills in), or +when both are in capitals. The documented path with the most equal segments wins. + +A literal segment also matches a placeholder, so a call whose own endpoint is gone can match +a neighbouring one (/consumers/current/scopes against /consumers/CONSUMER_ID/scopes). To keep +that from passing unnoticed, a call that matched one operation in the snapshot.json already on +disk and now matches another is listed and nothing is written; check each one, then rerun +with --accept-rebind. + +A path with no /obp/vX.Y.Z prefix (DirectLogin at /my/logins/direct, the unversioned +/obp/dynamic-entity/... routes) belongs to no version's resource docs, so it is not looked +up: it is recorded as missing and unversioned, and the contract must say why. +""" +import argparse +import datetime +import json +import os +import re +import sys +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +PLACEHOLDER = re.compile(r"^[A-Z][A-Z0-9_]*$") +VERSION = re.compile(r"^v\d+\.\d+\.\d+$") + + +def get_json(url): + req = urllib.request.Request(url, headers={"Accept": "application/json"}) + with urllib.request.urlopen(req, timeout=300) as resp: + return json.load(resp) + + +def segments(path): + return [s for s in path.split("?")[0].split("/") if s] + + +def match_score(contract_path, documented_path): + """Number of equal segments, or None when the paths cannot be the same endpoint.""" + a, b = segments(contract_path), segments(documented_path) + if len(a) != len(b): + return None + score = 0 + for x, y in zip(a, b): + if x == y: + score += 1 + elif not PLACEHOLDER.match(y): + return None + return score + + +def schema_fields(schema, prefix=""): + """Every field path in a JSON Schema: `a`, `a.b`, `a.list[]`, `a.list[].c`.""" + out = set() + if not isinstance(schema, dict): + return out + if schema.get("type") == "array" or "items" in schema: + out |= schema_fields(schema.get("items", {}), prefix + "[]") + for name, sub in (schema.get("properties") or {}).items(): + path = f"{prefix}.{name}" if prefix else name + out.add(path) + out |= schema_fields(sub, path) + if isinstance(sub, dict) and (sub.get("type") == "array" or "items" in sub): + out.add(path + "[]") + return out + + +def version_of(path): + """The version of an /obp/vX.Y.Z/... path, or None for a path without one.""" + s = segments(path) + return s[1] if len(s) > 1 and s[0] == "obp" and VERSION.match(s[1]) else None + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--base", required=True, help="OBP-API base URL") + ap.add_argument("--fallback", help="OBP-API that still serves the versions --base switched off") + ap.add_argument("--out", default=os.path.join(HERE, "snapshot.json")) + ap.add_argument("--accept-rebind", action="store_true", + help="write the snapshot although calls now match a different operation than before") + args = ap.parse_args() + base = args.base.rstrip("/") + contract = json.load(open(os.path.join(HERE, "contract.json"))) + calls = contract["calls"] + + fallback = args.fallback.rstrip("/") if args.fallback else None + docs, docs_from = {}, {} + for v in sorted({version_of(c["path"]) for c in calls} - {None}): + for host in [base] + ([fallback] if fallback else []): + url = f"{host}/obp/{v}/resource-docs/{v}/obp" + print(f"reading {url}", file=sys.stderr) + try: + docs[v] = get_json(url)["resource_docs"] + docs_from[v] = host + break + except urllib.error.HTTPError as e: + print(f" HTTP {e.code}", file=sys.stderr) + # 404 / 400 is how OBP-API says a version is switched off; any other + # status (401, 429, 5xx) is a broken server, not a reason to read another one. + if e.code not in (400, 404): + sys.exit(f"{url} answered HTTP {e.code}; not falling back to another OBP-API for that") + if v not in docs: + sys.exit(f"no OBP-API given serves the resource docs of {v}") + if not docs[v]: + sys.exit(f"{docs_from[v]} returned no resource docs for {v}; refusing to record every call as missing") + + def about(host): + newest = max((v for v in docs if docs_from[v] == host), + key=lambda v: tuple(int(p) for p in v[1:].split("."))) + root = get_json(f"{host}/obp/{newest}/root") + return {"version": root.get("version"), "git_commit": root.get("git_commit")} + hosts = {h: about(h) for h in sorted(set(docs_from.values()))} + + endpoints = [] + for c in calls: + v = version_of(c["path"]) + if v is None: + endpoints.append({"verb": c["verb"], "path": c["path"], "unversioned": True, "missing": True}) + continue + scored = [] + for d in docs[v]: + if d["request_verb"] != c["verb"]: + continue + score = match_score(c["path"], d.get("specified_url") or d["request_url"]) + if score is not None: + scored.append((score, d)) + scored.sort(key=lambda sd: -sd[0]) + entry = {"verb": c["verb"], "path": c["path"], "docs_from": docs_from[v]} + if scored and len(scored) > 1 and scored[0][0] == scored[1][0]: + entry["ambiguous"] = sorted(d["operation_id"] for s, d in scored if s == scored[0][0]) + if scored: + d = scored[0][1] + entry.update({ + "operation_id": d["operation_id"], + "documented_path": d.get("specified_url") or d["request_url"], + "fields": sorted(schema_fields(d.get("typed_success_response_body") or {})), + }) + else: + entry["missing"] = True + endpoints.append(entry) + + try: + with open(args.out) as f: + before = {(e["verb"], e["path"]): e for e in json.load(f)["endpoints"]} + except (OSError, ValueError, KeyError): + before = {} + rebound = [] + for e in endpoints: + was = before.get((e["verb"], e["path"])) + if was is None: + continue + name = f'{e["verb"]} {e["path"]}' + was_op, now_op = was.get("operation_id"), e.get("operation_id") + if was_op and now_op and was_op != now_op: + rebound.append(f"{name}: was {was_op}, now {now_op}") + elif was_op and not now_op: + rebound.append(f"{name}: was {was_op}, now no endpoint") + elif not was_op and now_op and not was.get("unversioned"): + rebound.append(f"{name}: had no endpoint, now {now_op}") + for line in rebound: + print(f" matches another operation: {line}", file=sys.stderr) + if rebound and not args.accept_rebind: + sys.exit(f"{args.out} not written: {len(rebound)} call(s) match a different operation than before, " + "which usually means their own endpoint is gone. Check each one, then rerun with --accept-rebind.") + + snapshot = { + "about": "Written by obp-api-contract/snapshot.py; do not edit by hand.", + "obp_api": hosts, + "taken_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), + "endpoints": endpoints, + } + with open(args.out, "w") as f: + json.dump(snapshot, f, indent=1, ensure_ascii=False) + f.write("\n") + missing = [e["verb"] + " " + e["path"] for e in endpoints if e.get("missing")] + print(f"wrote {args.out}: {len(endpoints)} calls, {len(missing)} with no endpoint", file=sys.stderr) + for m in missing: + print(f" no endpoint: {m}", file=sys.stderr) + + +if __name__ == "__main__": + main() diff --git a/server/app.ts b/server/app.ts index 5ecb1db..503b696 100644 --- a/server/app.ts +++ b/server/app.ts @@ -52,6 +52,9 @@ import statusRoutes from './routes/status.js' import obpRoutes from './routes/obp.js' import grpcRoutes from './routes/grpc.js' import monitoringRoutes from './routes/monitoring.js' +import { createProbeRoutes } from './routes/probes.js' +import OBPClientService from './services/OBPClientService.js' +import { createCachedReachability } from './services/ObpReachability.js' // ES module equivalent of __dirname const __filename = fileURLToPath(import.meta.url) @@ -149,6 +152,37 @@ console.info(`Trust proxy: ${trustProxy}`) if (app.get('env') === 'production') { sessionObject.cookie.secure = true // serve secure cookies } + +// /alive, /health and /status at the root, for probes and uptime monitors. They come before the +// session middleware so that they need no login and never read the session store in Redis. +const probeObpClientService = Container.get(OBPClientService) +const probeObpReachable = createCachedReachability(probeObpClientService, () => + probeObpClientService.getOBPVersion() +) +app.use( + createProbeRoutes( + { + // Redis holds the sessions, so it must be connected and answer a PING within two seconds. + redis: async () => { + if (!redisClient.isReady) return false + const pingTimeoutMs = 2000 + let timeoutHandle: NodeJS.Timeout | undefined + const timeout = new Promise((resolve) => { + timeoutHandle = setTimeout(() => resolve('timeout'), pingTimeoutMs) + }) + try { + return (await Promise.race([redisClient.ping(), timeout])) === 'PONG' + } finally { + clearTimeout(timeoutHandle) + } + }, + // OBP-API must answer its root endpoint. The answer is cached for a few seconds. + obpApi: probeObpReachable + }, + { gitCommit: () => commitId } + ) +) + app.use(session(sessionObject)) // OAuth2 Multi-Provider Setup only - no legacy fallback @@ -218,10 +252,13 @@ let instance: any `Backend is running. You can check a status at http://localhost:${port}${routePrefix}/status` ) - // Get commit ID + // Get commit ID: from GIT_COMMIT, set when the Docker image is built, else from the git checkout try { // Try to get the commit ID - commitId = execSync('git rev-parse HEAD', { encoding: 'utf-8' }).trim() + commitId = + process.env.GIT_COMMIT && process.env.GIT_COMMIT !== 'unknown' + ? process.env.GIT_COMMIT + : execSync('git rev-parse HEAD', { encoding: 'utf-8' }).trim() console.log('Current Commit ID:', commitId) } catch (error: any) { // Log the error but do not terminate the process diff --git a/server/routes/probes.ts b/server/routes/probes.ts new file mode 100644 index 0000000..d89dbe7 --- /dev/null +++ b/server/routes/probes.ts @@ -0,0 +1,136 @@ +/* + * Open Bank Project - API Explorer II + * Copyright (C) 2023-2026, TESOBE GmbH + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + * Email: contact@tesobe.com + * TESOBE GmbH + * Osloerstrasse 16/17 + * Berlin 13359, Germany + * + * This product includes software developed at + * TESOBE (http://www.tesobe.com/) + * + */ + +import { Router } from 'express' +import type { Request, Response, NextFunction } from 'express' + +// The checks the /status page runs. Each one answers true when the dependency works. +export interface ProbeChecks { + redis: () => Promise + obpApi: () => Promise +} + +// Build details shown on the /status page. +export interface ProbeBuildInfo { + gitCommit: () => string +} + +type CheckResult = 'ok' | 'fail' + +// Runs a check and turns its answer, or an error, into "ok" or "fail". +async function runCheck(checkName: string, check: () => Promise): Promise { + try { + return (await check()) ? 'ok' : 'fail' + } catch (error) { + console.warn(`Status page: the ${checkName} check failed:`, error instanceof Error ? error.message : error) + return 'fail' + } +} + +function htmlEscape(text: string): string { + return text.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"') +} + +// Probe answers describe this moment only, so no browser or proxy may keep them. +function noStore(req: Request, res: Response, next: NextFunction) { + res.setHeader('Cache-Control', 'no-store') + next() +} + +/** + * Plain probe endpoints at the root of the backend, modelled on OBP-API: + * - GET /alive answers `true`. It checks nothing. + * - GET /health answers {"status":"ok"}. It shows the process is up and serves HTTP, and never touches Redis or OBP-API. + * - GET /status checks Redis and OBP-API. It answers HTML, or JSON when the request's Accept prefers application/json, with 503 when a check fails. + * They need no login. Mount them before the session middleware so that they never read the session store. + * The routes under /api (/api/health, /api/ready and /api/status) are separate and unchanged. + */ +export function createProbeRoutes(checks: ProbeChecks, buildInfo: ProbeBuildInfo): Router { + const router = Router() + + router.get('/alive', noStore, (req: Request, res: Response) => { + res.status(200).type('application/json').send('true') + }) + + router.get('/health', noStore, (req: Request, res: Response) => { + res.status(200).type('application/json').send('{"status":"ok"}') + }) + + router.get('/status', noStore, async (req: Request, res: Response) => { + const [redisResult, obpApiResult] = await Promise.all([ + runCheck('redis', checks.redis), + runCheck('obp_api', checks.obpApi) + ]) + const allOk = redisResult === 'ok' && obpApiResult === 'ok' + const overall = allOk ? 'ok' : 'degraded' + const gitCommit = buildInfo.gitCommit() || 'unknown' + const uptimeSeconds = Math.floor(process.uptime()) + res.status(allOk ? 200 : 503) + + if (req.accepts(['text/html', 'application/json']) === 'application/json') { + res.json({ + status: overall, + git_commit: gitCommit, + uptime_seconds: uptimeSeconds, + checks: { redis: redisResult, obp_api: obpApiResult } + }) + return + } + + const badge = (result: string) => + `${htmlEscape(result)}` + res.type('text/html').send(` + + + API Explorer II - Status + + + +

API Explorer II Status: ${badge(overall)}

+

Instance

+ + + +
git_commit${htmlEscape(gitCommit)}
uptime_seconds${uptimeSeconds}
+

Checks

+ + + +
redis${badge(redisResult)}
obp_api${badge(obpApiResult)}
+ +`) + }) + + return router +} diff --git a/server/test/OBPClientService.test.ts b/server/test/OBPClientService.test.ts deleted file mode 100644 index 0bfb2cf..0000000 --- a/server/test/OBPClientService.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import {describe, it, expect} from 'vitest' -import OBPClientService from "../services/OBPClientService.js"; -import { before } from 'node:test'; - -describe('OBPClientService.getOauthHeaders', () => { - let obpClientService: OBPClientService; - beforeAll(() => { - obpClientService = new OBPClientService(); - }) - it('Should return an object with the correct oauth headers', async () => { - // This can't work as we don't have an access token yet, which means the function returns an empty string - // TODO - Mock OAuth1 flow, or at least have a fake filled out clientConfig - const headers = await obpClientService.getOAuthHeader('/test', 'GET'); - console.log("OAuth Headers: ", headers) - const clientConfig = await obpClientService.getOBPClientConfig(); - console.log("Client Config: ", clientConfig) - expect(headers).toBeTypeOf('string'); - - }) -}) \ No newline at end of file diff --git a/server/test/monitoring.test.ts b/server/test/monitoring.test.ts index 70893f9..8fd3525 100644 --- a/server/test/monitoring.test.ts +++ b/server/test/monitoring.test.ts @@ -69,31 +69,36 @@ describe('obpRoleCheck', () => { }) afterEach(() => vi.unstubAllGlobals()) - const answer = (status: number, modes: string[] = []) => - Promise.resolve(new Response(JSON.stringify({ allowed_for_auth_modes: modes }), { status })) + const answer = (status: number, allowed = false) => + Promise.resolve(new Response(JSON.stringify({ allowed }), { status })) - it('allows a token OBP-API allows for UserOrApplication, asking at SYS', async () => { - fetchMock.mockReturnValueOnce(answer(200, ['ApplicationOnly', 'UserOrApplication'])) + it('allows a token OBP-API allows, asking at SYS', async () => { + fetchMock.mockReturnValueOnce(answer(200, true)) expect(await tokenMayUseAnyRole('http://obp', 't', ['CanGetTelemetry'])).toBe('allowed') expect(fetchMock.mock.calls[0][0]).toBe('http://obp/obp/v7.0.0/banks/SYS/my/roles/CanGetTelemetry') expect(fetchMock.mock.calls[0][1].headers.Authorization).toBe('Bearer t') }) + it('refuses a token OBP-API does not allow', async () => { + fetchMock.mockReturnValueOnce(answer(200, false)) + expect(await tokenMayUseAnyRole('http://obp', 't', ['CanGetTelemetry'])).toBe('forbidden') + }) + it('tries the next Role when one is not allowed', async () => { - fetchMock.mockReturnValueOnce(answer(200, ['UserOnly'])).mockReturnValueOnce(answer(200, ['UserOrApplication'])) + fetchMock.mockReturnValueOnce(answer(200, false)).mockReturnValueOnce(answer(200, true)) expect(await tokenMayUseAnyRole('http://obp', 't', ['CanGetSystemLogCacheError', 'CanGetSystemLogCacheAll'])).toBe('allowed') expect(fetchMock).toHaveBeenCalledTimes(2) }) it('refuses when no Role is allowed, and says unauthorized when OBP-API rejects the token', async () => { - fetchMock.mockReturnValueOnce(answer(200, [])).mockReturnValueOnce(answer(404)) + fetchMock.mockReturnValueOnce(answer(200, false)).mockReturnValueOnce(answer(404)) expect(await tokenMayUseAnyRole('http://obp', 't', ['A', 'B'])).toBe('forbidden') fetchMock.mockReturnValueOnce(answer(401)) expect(await tokenMayUseAnyRole('http://obp', 'bad', ['A'])).toBe('unauthorized') }) it('reuses an answer for a minute', async () => { - fetchMock.mockImplementation(() => answer(200, ['UserOrApplication'])) + fetchMock.mockImplementation(() => answer(200, true)) await tokenMayUseAnyRole('http://obp', 't', ['A'], 0) await tokenMayUseAnyRole('http://obp', 't', ['A'], 59_999) expect(fetchMock).toHaveBeenCalledTimes(1) @@ -104,11 +109,11 @@ describe('obpRoleCheck', () => { describe('monitoring endpoints', () => { // A fake OBP-API: what each token may do, as GET /banks/SYS/my/roles/ROLE answers it. - const tokens: Record> = { - 'error-reader': { CanGetSystemLogCacheError: ['UserOrApplication'] }, - 'all-reader': { CanGetSystemLogCacheAll: ['UserOrApplication'] }, - 'telemetry-reader': { CanGetTelemetry: ['UserOrApplication'] }, - 'user-only': { CanGetSystemLogCacheAll: ['UserOnly'], CanGetTelemetry: ['UserOnly'] }, + const tokens: Record> = { + 'error-reader': { CanGetSystemLogCacheError: true }, + 'all-reader': { CanGetSystemLogCacheAll: true }, + 'telemetry-reader': { CanGetTelemetry: true }, + 'not-allowed': { CanGetSystemLogCacheAll: false, CanGetTelemetry: false }, 'no-roles': {} } const fakeObpApi = vi.fn(async (url: string, init: any) => { @@ -116,7 +121,7 @@ describe('monitoring endpoints', () => { if (!url.startsWith('http://obp/obp/v7.0.0/banks/SYS/my/roles/')) return new Response('{}', { status: 404 }) if (!(token in tokens)) return new Response('{}', { status: 401 }) const role = decodeURIComponent(url.split('/').pop()!) - return new Response(JSON.stringify({ allowed_for_auth_modes: tokens[token][role] ?? [] }), { status: 200 }) + return new Response(JSON.stringify({ allowed: tokens[token][role] ?? false }), { status: 200 }) }) // Stands in for the session middleware: a header X-Test-Session-Token puts that token in the session. @@ -151,7 +156,7 @@ describe('monitoring endpoints', () => { const capitalised = (level: string) => level.charAt(0).toUpperCase() + level.slice(1) it.each(levels)('returns the %s log cache to a token allowed its level Role or the All Role', async (level) => { - tokens[`${level}-only`] = { [`CanGetSystemLogCache${capitalised(level)}`]: ['UserOrApplication'] } + tokens[`${level}-only`] = { [`CanGetSystemLogCache${capitalised(level)}`]: true } for (const token of [`${level}-only`, 'all-reader']) { const res = await get(`/api/monitoring/log-cache/${level}`, token) expect(res.status).toBe(200) @@ -160,8 +165,8 @@ describe('monitoring endpoints', () => { }) it.each(levels)('refuses the %s log cache to tokens without its Roles, returning no lines', async (level) => { - for (const token of ['no-roles', 'telemetry-reader', 'user-only', level === 'error' ? 'all-but-error' : 'error-reader']) { - tokens['all-but-error'] = { CanGetSystemLogCacheInfo: ['UserOrApplication'] } + for (const token of ['no-roles', 'telemetry-reader', 'not-allowed', level === 'error' ? 'all-but-error' : 'error-reader']) { + tokens['all-but-error'] = { CanGetSystemLogCacheInfo: true } const res = await get(`/api/monitoring/log-cache/${level}`, token) expect(res.status).toBe(403) expect(res.body.entries).toBeUndefined() @@ -183,7 +188,7 @@ describe('monitoring endpoints', () => { expect(ok.status).toBe(200) expect(ok.body.git_commit).toBe('test-commit') expect(ok.body.meters.length).toBeGreaterThan(0) - for (const token of ['all-reader', 'user-only', 'no-roles']) { + for (const token of ['all-reader', 'not-allowed', 'no-roles']) { const res = await get('/api/monitoring/telemetry', token) expect(res.status).toBe(403) expect(res.body.meters).toBeUndefined() diff --git a/server/test/obpApiContract.test.ts b/server/test/obpApiContract.test.ts new file mode 100644 index 0000000..06fc3b5 --- /dev/null +++ b/server/test/obpApiContract.test.ts @@ -0,0 +1,204 @@ +// The contract between API Explorer II and OBP-API. +// +// obp-api-contract/contract.json lists every OBP-API call the Explorer's own code makes, with the +// response fields the code reads. obp-api-contract/snapshot.json is what an OBP-API documents for +// those calls, written by obp-api-contract/snapshot.py from its resource docs. These tests need no +// server: they check that the list matches the code, and that every call reaches an endpoint +// OBP-API documents, with every field the code reads. Retake the snapshot from a new OBP-API build +// to learn whether that build breaks the Explorer. + +import { describe, expect, it } from 'vitest' + +// vitest.config.js polyfills node built-ins for the browser, which turns `node:fs` into an empty +// stub, so the real module is taken from the Node runtime (Node 20.16 or newer). +const { readFileSync, readdirSync, statSync } = (process as any).getBuiltinModule('node:fs') + +// The repository root, which vitest runs in. +const ROOT = process.cwd() + +interface Needle { + source: string + needle: string +} + +interface Call { + verb: string + path: string + source: string + needles: string[] + version_from?: Needle[] + reads: string[] + undocumented_fields?: string[] + undocumented_endpoint?: string +} + +const load = (name: string) => JSON.parse(readFileSync(`${ROOT}/obp-api-contract/${name}`, 'utf8')) +const contract = load('contract.json') +const calls: Call[] = contract.calls +const notCalls: (Needle & { reason: string })[] = contract.not_calls ?? [] +const read = (file: string): string => readFileSync(`${ROOT}/${file}`, 'utf8') +const key = (call: { verb: string; path: string }) => `${call.verb} ${call.path}` + +// The snapshot entry for a call, or undefined. +const documented = (call: Call, snapshot: any) => + snapshot.endpoints.find((e: any) => key(e) === key(call)) + +// The reads of `call` that `fields` does not document. A read written `a|b` is satisfied by either. +export function undocumentedReads(call: { reads: string[] }, fields: Set): string[] { + return call.reads.filter((r) => !r.split('|').some((f) => fields.has(f))) +} + +// The front end and server code, without tests. +function sourceFiles(dir: string, out: string[] = []): string[] { + for (const name of readdirSync(`${ROOT}/${dir}`) as string[]) { + const path = `${dir}/${name}` + if (name === 'test' || name === 'node_modules') continue + if (statSync(`${ROOT}/${path}`).isDirectory()) { + sourceFiles(path, out) + } else if (/\.(ts|mts|tsx|js|mjs|cjs|vue|svelte)$/.test(name) && !/\.(test|spec|d)\.ts$/.test(name)) { + out.push(path) + } + } + return out +} + +// Whether `line` builds an OBP-API path: a string holding obp/vX or obp/${...}, or a string that +// starts or ends a path at /obp, so a path put together from pieces ('/obp/' + version, +// '/obp' + '/v6.0.0/...') is seen too. Imports such as '../obp/keys' are not paths. +export function buildsObpPath(line: string): boolean { + if (/['"`]/.test(line) && /obp\/(v\d|\$\{)/.test(line)) return true + return /(? { + const code = line.trim() + if (/^(\/\/|\/\*|\*|