From ce6bac58bb8db0d28b9a2e612ee473b2394b488f Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 12 Nov 2026 08:52:25 +0530 Subject: [PATCH 1/4] OpenConceptLab/ocl_online#201 | Saved endpoint tokens aren't returned: the Mapper reads has_token, asks for a custom algorithm's key each session, and keeps tokens out of copies and run snapshots --- src/components/map-projects/LookupConfig.jsx | 16 ++++++++-- src/components/map-projects/MapProject.jsx | 16 +++++++--- .../map-projects/MultiAlgoSelector.jsx | 11 +++++-- src/i18n/locales/en/translations.json | 4 +++ src/i18n/locales/es/translations.json | 4 +++ src/i18n/locales/pt-BR/translations.json | 4 +++ src/i18n/locales/zh/translations.json | 4 +++ src/services/__tests__/attribution.test.js | 8 +++++ src/services/__tests__/tokenScope.test.js | 29 ++++++++++++++++++- src/services/attribution.js | 5 ++-- src/services/tokenScope.js | 21 ++++++++++++++ 11 files changed, 109 insertions(+), 13 deletions(-) diff --git a/src/components/map-projects/LookupConfig.jsx b/src/components/map-projects/LookupConfig.jsx index 54d90fa7..756f9cbd 100644 --- a/src/components/map-projects/LookupConfig.jsx +++ b/src/components/map-projects/LookupConfig.jsx @@ -11,12 +11,22 @@ import DownIcon from '@mui/icons-material/ArrowDropDown'; import VisibilityIcon from '@mui/icons-material/Visibility'; import VisibilityOffIcon from '@mui/icons-material/VisibilityOff'; import { lookupTokenHasSpaces, normalizeLookupConfig } from './lookupConfigFields' +import { isOCLAPILookupURL } from '../../services/tokenScope' +import { getAPIURL } from '../../common/utils' const LookupConfig = ({value, onChange}) => { const { t } = useTranslation() const [open, setOpen] = React.useState(false) const [showToken, setShowToken] = React.useState(false) const tokenHasSpaces = lookupTokenHasSpaces(value?.token) + const isOCLAPI = isOCLAPILookupURL(value?.url, getAPIURL()) + const getTokenHelperText = () => { + if(tokenHasSpaces) + return t('map_project.lookup_configuration_token_has_spaces') + if(isOCLAPI) + return t('map_project.lookup_configuration_token_ocl') + return value?.has_token && !value?.token ? t('map_project.lookup_configuration_token_saved') : '' + } return (
@@ -34,7 +44,7 @@ const LookupConfig = ({value, onChange}) => { fullWidth required value={value?.url || ''} - onChange={event => onChange({...value, url: event.target.value.trim()})} + onChange={event => onChange({...value, url: event.target.value.trim(), has_token: undefined})} />
@@ -46,7 +56,7 @@ const LookupConfig = ({value, onChange}) => { onChange={event => onChange({...value, token: event.target.value || ''})} onBlur={() => onChange(normalizeLookupConfig(value))} color={tokenHasSpaces ? 'warning' : 'primary'} - helperText={tokenHasSpaces ? t('map_project.lookup_configuration_token_has_spaces') : ''} + helperText={getTokenHelperText()} slotProps={{ input: { endAdornment: ( @@ -57,7 +67,7 @@ const LookupConfig = ({value, onChange}) => { ), }, - formHelperText: {sx: {color: 'warning.main'}}, + formHelperText: tokenHasSpaces ? {sx: {color: 'warning.main'}} : {}, }} />
diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 53f18f4d..8813a871 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -70,7 +70,7 @@ import pick from 'lodash/pick' import { OperationsContext } from '../app/LayoutContext'; import APIService, { isTransientNetworkError, retryWithBackoff } from '../../services/APIService'; -import { matchToken, lookupToken } from '../../services/tokenScope' +import { matchToken, lookupToken, needsSessionToken, withoutTokens } from '../../services/tokenScope' import { buildAttributionHeaders, buildConfigSnapshot, summarizeRunCompletion, matchesOnOCL } from '../../services/attribution' import { CAPACITY_LIMIT, RATE_LIMIT, CAPACITY_WAIT_CAP_MS, HEAVY_REQUEST_TIMEOUT_MS, LIGHT_REQUEST_TIMEOUT_MS, createCapacityGate, createLimiter, isRetryableError, requestWithCapacityRetry, sleepUnlessCancelled, untilCancelled } from '../../services/capacity' import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCurrentUserCapabilitiesCache } from '../../common/utils'; @@ -883,11 +883,12 @@ const MapProject = () => { setProjectPromptTemplateKey(copiedProject.prompt_template_key || '') setName(copiedProject.name ? t('map_project.create_similar_name', {name: copiedProject.name}) : '') setFilters(copiedProject.filters || {}) - setLookupConfig(normalizeLookupConfig(copiedProject.lookup_config || {})) + // A copy starts without the original's saved tokens. + setLookupConfig(normalizeLookupConfig(withoutTokens(copiedProject.lookup_config || {}))) setNamespace(copiedProject.namespace || '') setCandidatesScore(copiedProject.score_configuration || {recommended: 99, available: 70}) setRetired(Boolean(copiedProject.include_retired || false)) - setAlgosSelected(copiedProject.algorithms || []) + setAlgosSelected(withoutTokens(copiedProject.algorithms || [])) setEncoderModel(copiedProject.encoder_model || DEFAULT_ENCODER_MODEL) setUseLexicalVariants(Boolean(copiedProject.use_lexical_variants)) setInputLocale((copiedProject.input_locales || [])[0] || '') @@ -3186,8 +3187,11 @@ const MapProject = () => { event.stopPropagation() event.preventDefault() setAlert(false) + const algoWithoutKey = find(algosSelected, algo => selectedAlgos.includes(algo.id) && needsSessionToken(algo)) const run = hasAutoMatchWork(selectedAlgos) ? getAutoMatchRunRows(data, selectedAlgos) : null - if(!run?.runRows.length) { + if(algoWithoutKey) { + setAlert({message: t('map_project.api_token_needed', {name: algoWithoutKey.name || algoWithoutKey.id}), severity: 'warning'}) + } else if(!run?.runRows.length) { setAlert({message: t('map_project.auto_match_nothing_to_run'), severity: 'warning'}) } else if(isAnyValidColumn()){ setStartMatchingAt(moment()) @@ -4095,6 +4099,10 @@ const MapProject = () => { const fetchOCLOrCustomCandidates = (algoDef, _row, offset=0, _retired, _filters, callback) => { // can be algo=ocl-search | ocl-semantic | custom let __row = isEmpty(_row) ? row : _row + if(needsSessionToken(algoDef)) { + setAlert({message: t('map_project.api_token_needed', {name: algoDef.name || algoDef.id}), severity: 'warning'}) + return + } const payload = getPayloadForMatching([__row], repo, _filters) if(!values(omit(payload.rows[0], '__index')).length){ diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index d5d7e436..2a835253 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -37,6 +37,7 @@ import { OperationsContext } from '../app/LayoutContext' import { isLikelyCanonicalUrl } from './algorithms' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import APIService from '../../services/APIService'; +import { needsSessionToken } from '../../services/tokenScope'; import { getRequestLimits, getRequestSettings } from './requestLimits' import { dropVersion } from '../../common/utils' import { @@ -509,7 +510,8 @@ export default function MultiAlgoSelector({ label={t('map_project.api_url')} value={sel.url || ""} onChange={(e) => { - updateSelected(sel.__key, { url: e.target.value }); + // A saved key belongs to the URL it was saved with. + updateSelected(sel.__key, { url: e.target.value, has_token: undefined }); if(customMeta.requestError || customMeta.requestSuccess || customMeta.tokenRequired) { setCustomAlgoState(sel.__key, { requestError: '', @@ -525,7 +527,7 @@ export default function MultiAlgoSelector({ /> { + const snapshot = buildConfigSnapshot({ + selectedAlgos: [{id: 'custom-1', type: 'custom', url: 'https://match.example.com/', token: 'T', has_token: true}], + }) + assert.deepEqual(snapshot.algorithms, [{id: 'custom-1', type: 'custom', url: 'https://match.example.com/'}]) + assert.equal(JSON.stringify(snapshot).includes('"token"'), false) +}) diff --git a/src/services/__tests__/tokenScope.test.js b/src/services/__tests__/tokenScope.test.js index fc96c217..8f1569f2 100644 --- a/src/services/__tests__/tokenScope.test.js +++ b/src/services/__tests__/tokenScope.test.js @@ -6,7 +6,7 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { isAPIHost, matchToken, lookupToken, joinAPIPath } from '../tokenScope.js' +import { isAPIHost, matchToken, lookupToken, joinAPIPath, isOCLAPILookupURL, needsSessionToken, withoutTokens } from '../tokenScope.js' const API = 'https://api.example.org' const USER = 'USER-TOKEN' @@ -63,3 +63,30 @@ test('overrideURL cannot change the host', () => { assert.equal(new URL(joinAPIPath(API, ':80@evil.com/')).host, 'api.example.org') assert.equal(joinAPIPath(API, '/orgs/x/'), `${API}/orgs/x/`) }) + +test('isOCLAPILookupURL: no URL, a path, or the API origin', () => { + assert.equal(isOCLAPILookupURL(undefined, API), true) + assert.equal(isOCLAPILookupURL('', API), true) + assert.equal(isOCLAPILookupURL('/orgs/CIEL/sources/CIEL/', API), true) + assert.equal(isOCLAPILookupURL(`${API}/orgs/CIEL/`, API), true) + assert.equal(isOCLAPILookupURL('https://terms.example.com/orgs/X/', API), false) +}) + +test('needsSessionToken: a custom algorithm with a saved key not entered this session', () => { + const url = 'https://match.example.com/' + assert.equal(needsSessionToken({type: 'custom', url, has_token: true}), true) + assert.equal(needsSessionToken({type: 'custom', url, has_token: true, token: 'T'}), false) + assert.equal(needsSessionToken({type: 'custom', url}), false) + assert.equal(needsSessionToken({type: 'custom', has_token: true}), false) + assert.equal(needsSessionToken({type: 'ocl-semantic', url, has_token: true}), false) + assert.equal(needsSessionToken(undefined), false) +}) + +test('withoutTokens: removes token and has_token at any depth', () => { + assert.deepEqual( + withoutTokens([{url: 'u', token: 'T', has_token: true, nested: {token: 'N', keep: 1}}, 'x']), + [{url: 'u', nested: {keep: 1}}, 'x'] + ) + assert.deepEqual(withoutTokens({url: 'u', has_token: true}), {url: 'u'}) + assert.equal(withoutTokens(null), null) +}) diff --git a/src/services/attribution.js b/src/services/attribution.js index 336ef416..25a9a774 100644 --- a/src/services/attribution.js +++ b/src/services/attribution.js @@ -19,6 +19,7 @@ */ import isFunction from 'lodash/isFunction.js' +import { withoutTokens } from './tokenScope.js' export const REQUEST_SOURCE = { AUTOMATCH: 'automatch', @@ -100,7 +101,7 @@ export const buildAttributionHeaders = ({ /** * Assemble the JSON-safe project config captured at run start * (AutomatchRun.config_snapshot). Strips function-valued algorithm fields - * (e.g. getIcon) so the POST body serializes cleanly. + * (e.g. getIcon) so the POST body serializes cleanly, and every token. * * @param {object} [opts] * @param {object[]} [opts.selectedAlgos] algorithms selected for the run @@ -124,7 +125,7 @@ export const buildConfigSnapshot = ({ Object.keys(algo || {}).forEach(key => { if(!isFunction(algo[key])) clean[key] = algo[key] }) - return clean + return withoutTokens(clean) }), encoder: encoderModel || null, score_config: scoreConfig || null, diff --git a/src/services/tokenScope.js b/src/services/tokenScope.js index a75e23ab..93d968ec 100644 --- a/src/services/tokenScope.js +++ b/src/services/tokenScope.js @@ -32,3 +32,24 @@ export const joinAPIPath = (apiURL, path) => { const value = String(path ?? '') return `${apiURL}${value.startsWith('/') ? '' : '/'}${value}` } + +// A lookup the Mapper sends to the OCL API: none (the target repo), a path, or +// a URL on the API's origin. The API doesn't save a token for one. +export const isOCLAPILookupURL = (url, apiURL) => + !url || !String(url).startsWith('http') || isAPIHost(url, apiURL) + +// The API never returns a saved token, only has_token. A custom algorithm with +// a saved key needs it entered again before it can run in this session. +export const needsSessionToken = algo => + Boolean(algo?.type === 'custom' && algo?.url && algo?.has_token && !algo?.token) + +// Removes token and has_token, at any depth: for copies and run snapshots. +export const withoutTokens = value => { + if(Array.isArray(value)) + return value.map(withoutTokens) + if(value && typeof value === 'object') + return Object.fromEntries( + Object.entries(value).filter(([key]) => key !== 'token' && key !== 'has_token').map(([key, val]) => [key, withoutTokens(val)]) + ) + return value +} From d51eb496d6a7e3b9f6060ebde717cd7d4d7a51fb Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 12 Nov 2026 12:16:56 +0530 Subject: [PATCH 2/4] OpenConceptLab/ocl_online#201 | Saved tokens: missing key fails the row and goes on, lookup token warning, http(s) URL rule matches the API, saved-token URL kept locally, explicit remove --- src/components/map-projects/LookupConfig.jsx | 20 ++++++-- src/components/map-projects/MapProject.jsx | 34 +++++++++----- .../map-projects/MultiAlgoSelector.jsx | 15 ++++-- src/i18n/locales/en/translations.json | 2 + src/i18n/locales/es/translations.json | 2 + src/i18n/locales/pt-BR/translations.json | 2 + src/i18n/locales/zh/translations.json | 2 + src/services/__tests__/tokenScope.test.js | 47 ++++++++++++++++++- src/services/tokenScope.js | 40 ++++++++++++++-- 9 files changed, 140 insertions(+), 24 deletions(-) diff --git a/src/components/map-projects/LookupConfig.jsx b/src/components/map-projects/LookupConfig.jsx index 756f9cbd..76ce8c38 100644 --- a/src/components/map-projects/LookupConfig.jsx +++ b/src/components/map-projects/LookupConfig.jsx @@ -11,7 +11,7 @@ import DownIcon from '@mui/icons-material/ArrowDropDown'; import VisibilityIcon from '@mui/icons-material/Visibility'; import VisibilityOffIcon from '@mui/icons-material/VisibilityOff'; import { lookupTokenHasSpaces, normalizeLookupConfig } from './lookupConfigFields' -import { isOCLAPILookupURL } from '../../services/tokenScope' +import { isOCLAPILookupURL, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope' import { getAPIURL } from '../../common/utils' const LookupConfig = ({value, onChange}) => { @@ -25,7 +25,16 @@ const LookupConfig = ({value, onChange}) => { return t('map_project.lookup_configuration_token_has_spaces') if(isOCLAPI) return t('map_project.lookup_configuration_token_ocl') - return value?.has_token && !value?.token ? t('map_project.lookup_configuration_token_saved') : '' + if(!value?.has_token || value?.token) + return '' + return ( + <> + {t('map_project.lookup_configuration_token_saved')} + + + ) } return ( @@ -44,7 +53,10 @@ const LookupConfig = ({value, onChange}) => { fullWidth required value={value?.url || ''} - onChange={event => onChange({...value, url: event.target.value.trim(), has_token: undefined})} + onChange={event => { + const url = event.target.value.trim() + onChange({...value, url, has_token: getTokenFlag(value, url)}) + }} />
@@ -53,7 +65,7 @@ const LookupConfig = ({value, onChange}) => { label={t('map_project.lookup_configuration_token')} fullWidth value={value?.token || ''} - onChange={event => onChange({...value, token: event.target.value || ''})} + onChange={event => onChange({...value, token: tokenInputValue(value, event.target.value)})} onBlur={() => onChange(normalizeLookupConfig(value))} color={tokenHasSpaces ? 'warning' : 'primary'} helperText={getTokenHelperText()} diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 8813a871..1cbf3e39 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -70,7 +70,7 @@ import pick from 'lodash/pick' import { OperationsContext } from '../app/LayoutContext'; import APIService, { isTransientNetworkError, retryWithBackoff } from '../../services/APIService'; -import { matchToken, lookupToken, needsSessionToken, withoutTokens } from '../../services/tokenScope' +import { matchToken, lookupToken, needsSessionToken, needsSessionLookupToken, withoutTokens, withSavedTokenURL, withoutLocalKeys, isAbsoluteURL } from '../../services/tokenScope' import { buildAttributionHeaders, buildConfigSnapshot, summarizeRunCompletion, matchesOnOCL } from '../../services/attribution' import { CAPACITY_LIMIT, RATE_LIMIT, CAPACITY_WAIT_CAP_MS, HEAVY_REQUEST_TIMEOUT_MS, LIGHT_REQUEST_TIMEOUT_MS, createCapacityGate, createLimiter, isRetryableError, requestWithCapacityRetry, sleepUnlessCancelled, untilCancelled } from '../../services/capacity' import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCurrentUserCapabilitiesCache } from '../../common/utils'; @@ -326,6 +326,7 @@ const MapProject = () => { const getConfigurationSnapshotRef = React.useRef(null) const projectIdRef = React.useRef(null) const onSaveRef = React.useRef(null) + const lookupTokenWarnedRef = React.useRef(false) const projectLogRef = React.useRef(() => {}) // A save can complete after the user has left the project // (OpenConceptLab/ocl_issues#2829): these track the request still in flight @@ -934,7 +935,7 @@ const MapProject = () => { const sheet = workbook.Sheets[sheetName]; const data = XLSX.utils.sheet_to_json(sheet, { raw: false, defval: '' }) setProjectFromData(data, response.data) - setAlgosSelected(response?.data?.algorithms || []) + setAlgosSelected(map(response?.data?.algorithms || [], withSavedTokenURL)) if (response?.data.columns?.length > 0) { // Saved mappings are the user's, so they are never re-suggested. const _columns = response.data.columns.map(col => ({...omit(col, ['hidden', 'auto', 'suggested'])})) @@ -1015,7 +1016,7 @@ const MapProject = () => { setRowMatchState(_rowMatchState) conceptCacheRef.current = _cache rowMatchStateRef.current = _rowMatchState - setAlgosSelected(response.data.algorithms) + setAlgosSelected(map(response.data.algorithms, withSavedTokenURL)) setRowStage(_rowStage) setName(response.data?.name || '') @@ -1023,7 +1024,8 @@ const MapProject = () => { setOwner(response.data?.owner_url) setRetired(Boolean(response.data?.include_retired)) setCandidatesScore(response.data?.score_configuration) - setLookupConfig(normalizeLookupConfig(response.data?.lookup_config)) + setLookupConfig(normalizeLookupConfig(withSavedTokenURL(response.data?.lookup_config))) + lookupTokenWarnedRef.current = false setNamespace(response.data?.namespace || '') setEncoderModel(response.data?.encoder_model || DEFAULT_ENCODER_MODEL) setProjectPromptTemplateKey(response.data?.prompt_template_key || '') @@ -1754,9 +1756,9 @@ const MapProject = () => { source: repo.short_code || repo.id, source_version: selectedTargetRepoVersion })) - formData.append('algorithms', JSON.stringify(map(algosSelected, algo => omit(algo, ['__key'])))) + formData.append('algorithms', JSON.stringify(map(algosSelected, withoutLocalKeys))) formData.append('score_configuration', JSON.stringify(candidatesScore)) - formData.append('lookup_config', JSON.stringify(lookupConfig)) + formData.append('lookup_config', JSON.stringify(withoutLocalKeys(lookupConfig))) // Always send `namespace` (including empty string) so clearing the field // in the UI actually propagates to the server. The server reads empty // as "use the project owner default"; gating the append on truthiness @@ -3191,6 +3193,8 @@ const MapProject = () => { const run = hasAutoMatchWork(selectedAlgos) ? getAutoMatchRunRows(data, selectedAlgos) : null if(algoWithoutKey) { setAlert({message: t('map_project.api_token_needed', {name: algoWithoutKey.name || algoWithoutKey.id}), severity: 'warning'}) + } else if(needsSessionLookupToken(lookupConfig, getAPIURL())) { + setAlert({message: t('map_project.lookup_token_needed'), severity: 'warning'}) } else if(!run?.runRows.length) { setAlert({message: t('map_project.auto_match_nothing_to_run'), severity: 'warning'}) } else if(isAnyValidColumn()){ @@ -4099,10 +4103,6 @@ const MapProject = () => { const fetchOCLOrCustomCandidates = (algoDef, _row, offset=0, _retired, _filters, callback) => { // can be algo=ocl-search | ocl-semantic | custom let __row = isEmpty(_row) ? row : _row - if(needsSessionToken(algoDef)) { - setAlert({message: t('map_project.api_token_needed', {name: algoDef.name || algoDef.id}), severity: 'warning'}) - return - } const payload = getPayloadForMatching([__row], repo, _filters) if(!values(omit(payload.rows[0], '__index')).length){ @@ -4329,7 +4329,12 @@ const MapProject = () => { } } - if(['ocl-semantic', 'ocl-search', 'custom'].includes(algoDef.type)) { + if(needsSessionToken(algoDef)) { + // Fails this algorithm for the row and goes on with the others. + setAlert({message: t('map_project.api_token_needed', {name: algoDef.name || algoDef.id}), severity: 'warning'}) + markAlgo(__row.__index, algoId, -2) + goOnAfterFailure() + } else if(['ocl-semantic', 'ocl-search', 'custom'].includes(algoDef.type)) { fetchOCLOrCustomCandidates(algoDef, _row, offset, _retired, _filters, onResponse) } else if (algoDef.type === 'ocl-scispacy') { fetchScispacyCandidates(__row, scrollToBottom, forceReload, false, onResponse, goOnAfterFailure) @@ -5129,7 +5134,7 @@ const MapProject = () => { const getLookupService = () => { let service = APIService.new() if(lookupConfig?.url) { - if(lookupConfig.url.startsWith('http')) + if(isAbsoluteURL(lookupConfig.url)) service.URL = lookupConfig.url else service.overrideURL(lookupConfig.url) @@ -5143,6 +5148,11 @@ const MapProject = () => { const getLookupToken = url => lookupToken(lookupConfig?.token, url, getAPIURL(), currentUserToken()) const requestLookup = query => { + // Lookups still go out without the saved token, so say once why they may fail. + if(!lookupTokenWarnedRef.current && needsSessionLookupToken(lookupConfig, getAPIURL())) { + lookupTokenWarnedRef.current = true + setAlert({message: t('map_project.lookup_token_needed'), severity: 'warning'}) + } const service = getLookupService() return service.request('GET', undefined, getLookupToken(service.URL), {query, handlesThrottle: true, timeout: LIGHT_REQUEST_TIMEOUT_MS}) } diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index 2a835253..b682fc4a 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -37,7 +37,7 @@ import { OperationsContext } from '../app/LayoutContext' import { isLikelyCanonicalUrl } from './algorithms' import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete' import APIService from '../../services/APIService'; -import { needsSessionToken } from '../../services/tokenScope'; +import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope'; import { getRequestLimits, getRequestSettings } from './requestLimits' import { dropVersion } from '../../common/utils' import { @@ -511,7 +511,7 @@ export default function MultiAlgoSelector({ value={sel.url || ""} onChange={(e) => { // A saved key belongs to the URL it was saved with. - updateSelected(sel.__key, { url: e.target.value, has_token: undefined }); + updateSelected(sel.__key, { url: e.target.value, has_token: getTokenFlag(sel, e.target.value) }); if(customMeta.requestError || customMeta.requestSuccess || customMeta.tokenRequired) { setCustomAlgoState(sel.__key, { requestError: '', @@ -532,7 +532,7 @@ export default function MultiAlgoSelector({ label={t('map_project.api_token')} value={sel.token || ""} onChange={(e) => { - updateSelected(sel.__key, { token: e.target.value }); + updateSelected(sel.__key, { token: tokenInputValue(sel, e.target.value) }); if(customMeta.requestError || customMeta.requestSuccess) { setCustomAlgoState(sel.__key, { requestError: '', @@ -549,7 +549,14 @@ export default function MultiAlgoSelector({ error={Boolean(customMeta.tokenRequired && !sel.token)} helperText={ customMeta.tokenRequired && !sel.token ? 'Authentication is required for this algorithm.' : - (needsSessionToken(sel) ? t('map_project.api_token_saved') : '') + (needsSessionToken(sel) ? ( + <> + {t('map_project.api_token_saved')} + + + ) : '') } /> diff --git a/src/i18n/locales/en/translations.json b/src/i18n/locales/en/translations.json index 3a4a6e2e..0f5e377e 100644 --- a/src/i18n/locales/en/translations.json +++ b/src/i18n/locales/en/translations.json @@ -262,6 +262,7 @@ "api_token": "API Token", "api_token_saved": "A token is saved for this endpoint but isn't shown. Enter it again to use this algorithm in this session.", "api_token_needed": "Enter the API token for {{name}} in the project configuration. A saved token isn't shown, so it's needed again each session.", + "remove_saved_token": "Remove saved token", "score_configuration": "Score Configuration", "score_configuration_description": "Configure Score threshold to group candidates recommendations", "not_recommended": "Not Recommended", @@ -498,6 +499,7 @@ "lookup_configuration_url": "Repository URL", "lookup_configuration_token": "Token", "lookup_configuration_token_saved": "A token is saved for this lookup but isn't shown. Enter it again to use it in this session.", + "lookup_token_needed": "Enter the lookup token in the project configuration. A saved token isn't shown, so it's needed again each session; until then, lookups go without it.", "lookup_configuration_token_ocl": "Lookups on OCL use your own sign-in. A token entered here is used in this session only and isn't saved.", "lookup_configuration_token_has_spaces": "Tokens don't contain spaces. Paste only the token itself, without a \"Token\" or \"Bearer\" prefix.", "lookup_configuration_description": "Configure a Source/CodeSystem for lookup operation to fetch candidates definitions.", diff --git a/src/i18n/locales/es/translations.json b/src/i18n/locales/es/translations.json index 1efd1ada..f0dc2849 100644 --- a/src/i18n/locales/es/translations.json +++ b/src/i18n/locales/es/translations.json @@ -481,6 +481,7 @@ "api_token": "Token de API", "api_token_saved": "Hay un token guardado para este endpoint, pero no se muestra. Ingréselo de nuevo para usar este algoritmo en esta sesión.", "api_token_needed": "Ingrese el token de API de {{name}} en la configuración del proyecto. Un token guardado no se muestra, así que se necesita de nuevo en cada sesión.", + "remove_saved_token": "Eliminar token guardado", "ocl_search_algorithm": "Algoritmo de búsqueda de OCL", "scispacy_warming_up": "El servicio de coincidencia scispacy de OCL se está iniciando. Reintentará automáticamente en 2 minutos.", "algorithms": "Algoritmos", @@ -490,6 +491,7 @@ "lookup_configuration_url": "URL del repositorio", "lookup_configuration_token": "Token", "lookup_configuration_token_saved": "Hay un token guardado para esta búsqueda, pero no se muestra. Ingréselo de nuevo para usarlo en esta sesión.", + "lookup_token_needed": "Ingrese el token de búsqueda en la configuración del proyecto. Un token guardado no se muestra, así que se necesita de nuevo en cada sesión; mientras tanto, las búsquedas se hacen sin él.", "lookup_configuration_token_ocl": "Las búsquedas en OCL usan su propia sesión. Un token ingresado aquí solo se usa en esta sesión y no se guarda.", "lookup_configuration_token_has_spaces": "Los tokens no contienen espacios. Pegue solo el token, sin el prefijo \"Token\" o \"Bearer\".", "lookup_configuration_description": "Configure una Fuente/Sistema de códigos para la operación de búsqueda y recuperar definiciones de candidatos.", diff --git a/src/i18n/locales/pt-BR/translations.json b/src/i18n/locales/pt-BR/translations.json index 04aa4edf..c1d24487 100644 --- a/src/i18n/locales/pt-BR/translations.json +++ b/src/i18n/locales/pt-BR/translations.json @@ -262,6 +262,7 @@ "api_token": "Token da API", "api_token_saved": "Há um token salvo para este endpoint, mas ele não é exibido. Digite-o novamente para usar este algoritmo nesta sessão.", "api_token_needed": "Digite o token de API de {{name}} na configuração do projeto. Um token salvo não é exibido, então é necessário novamente a cada sessão.", + "remove_saved_token": "Remover token salvo", "score_configuration": "Configuração de Pontuação", "score_configuration_description": "Configurar limite de pontuação para agrupar recomendações de candidatos", "not_recommended": "Não Recomendado", @@ -498,6 +499,7 @@ "lookup_configuration_url": "URL do Repositório", "lookup_configuration_token": "Token", "lookup_configuration_token_saved": "Há um token salvo para esta consulta, mas ele não é exibido. Digite-o novamente para usá-lo nesta sessão.", + "lookup_token_needed": "Digite o token de consulta na configuração do projeto. Um token salvo não é exibido, então é necessário novamente a cada sessão; até lá, as consultas são feitas sem ele.", "lookup_configuration_token_ocl": "Consultas no OCL usam o seu próprio login. Um token digitado aqui é usado somente nesta sessão e não é salvo.", "lookup_configuration_token_has_spaces": "Tokens não contêm espaços. Cole apenas o token, sem o prefixo \"Token\" ou \"Bearer\".", "lookup_configuration_description": "Configure um Source/CodeSystem para operação de busca para buscar definições de candidatos.", diff --git a/src/i18n/locales/zh/translations.json b/src/i18n/locales/zh/translations.json index c56e0dd8..54e18693 100644 --- a/src/i18n/locales/zh/translations.json +++ b/src/i18n/locales/zh/translations.json @@ -492,6 +492,7 @@ "api_token": "API 令牌", "api_token_saved": "此端点已保存令牌,但不会显示。请再次输入,以便在本次会话中使用此算法。", "api_token_needed": "请在项目配置中输入 {{name}} 的 API 令牌。已保存的令牌不会显示,因此每次会话都需要重新输入。", + "remove_saved_token": "删除已保存的令牌", "ocl_search_algorithm": "OCL 搜索算法", "scispacy_warming_up": "OCL的scispacy匹配服务正在启动中,将在2分钟后自动重试。", "algorithms": "算法", @@ -501,6 +502,7 @@ "lookup_configuration_url": "仓库 URL", "lookup_configuration_token": "令牌", "lookup_configuration_token_saved": "此查找已保存令牌,但不会显示。请再次输入,以便在本次会话中使用。", + "lookup_token_needed": "请在项目配置中输入查找令牌。已保存的令牌不会显示,因此每次会话都需要重新输入;在此之前,查找将不带令牌进行。", "lookup_configuration_token_ocl": "在 OCL 上的查找使用您自己的登录。在此输入的令牌仅在本次会话中使用,不会保存。", "lookup_configuration_token_has_spaces": "令牌不包含空格。请只粘贴令牌本身,不要带 \"Token\" 或 \"Bearer\" 前缀。", "lookup_configuration_description": "配置用于查找操作的源/代码系统,以获取候选项定义。", diff --git a/src/services/__tests__/tokenScope.test.js b/src/services/__tests__/tokenScope.test.js index 8f1569f2..437bbe1f 100644 --- a/src/services/__tests__/tokenScope.test.js +++ b/src/services/__tests__/tokenScope.test.js @@ -6,7 +6,11 @@ import test from 'node:test' import assert from 'node:assert/strict' -import { isAPIHost, matchToken, lookupToken, joinAPIPath, isOCLAPILookupURL, needsSessionToken, withoutTokens } from '../tokenScope.js' +import { + isAPIHost, matchToken, lookupToken, joinAPIPath, isOCLAPILookupURL, needsSessionToken, withoutTokens, + isAbsoluteURL, needsSessionLookupToken, withSavedTokenURL, getTokenFlag, tokenInputValue, removeSavedToken, + withoutLocalKeys, TOKEN_URL_KEY, +} from '../tokenScope.js' const API = 'https://api.example.org' const USER = 'USER-TOKEN' @@ -70,6 +74,47 @@ test('isOCLAPILookupURL: no URL, a path, or the API origin', () => { assert.equal(isOCLAPILookupURL('/orgs/CIEL/sources/CIEL/', API), true) assert.equal(isOCLAPILookupURL(`${API}/orgs/CIEL/`, API), true) assert.equal(isOCLAPILookupURL('https://terms.example.com/orgs/X/', API), false) + assert.equal(isOCLAPILookupURL('HTTPS://terms.example.com/orgs/X/', API), false) + assert.equal(isOCLAPILookupURL('//terms.example.com/orgs/X/', API), true) +}) + +test('isAbsoluteURL: only http(s)://, in any case', () => { + assert.equal(isAbsoluteURL('HTTPS://x.org/'), true) + assert.equal(isAbsoluteURL('http://x.org/'), true) + assert.equal(isAbsoluteURL('//x.org/'), false) + assert.equal(isAbsoluteURL('/orgs/X/'), false) + assert.equal(isAbsoluteURL(undefined), false) +}) + +test('needsSessionLookupToken: a saved token on another host, not entered this session', () => { + const url = 'https://terms.example.com/orgs/X/' + assert.equal(needsSessionLookupToken({url, has_token: true}, API), true) + assert.equal(needsSessionLookupToken({url, has_token: true, token: 'T'}, API), false) + assert.equal(needsSessionLookupToken({url: '/orgs/X/', has_token: true}, API), false) + assert.equal(needsSessionLookupToken({url}, API), false) +}) + +test('saved token URL: has_token comes back on the original URL, and is never sent', () => { + const url = 'https://match.example.com/' + const loaded = withSavedTokenURL({__key: 'k', url, has_token: true}) + assert.equal(getTokenFlag(loaded, 'https://other.example.com/'), undefined) + assert.equal(getTokenFlag(loaded, url), true) + assert.equal(getTokenFlag({url}, url), undefined) + assert.deepEqual(withoutLocalKeys(loaded), {url, has_token: true}) + assert.deepEqual(withSavedTokenURL({url}), {url}) + assert.equal(withoutTokens(loaded)[TOKEN_URL_KEY], undefined) +}) + +test('an emptied token field keeps a saved token; removing it clears it', () => { + const loaded = withSavedTokenURL({url: 'u', has_token: true}) + assert.equal(tokenInputValue(loaded, ''), undefined) + assert.equal(tokenInputValue(loaded, 'T'), 'T') + assert.equal(tokenInputValue({url: 'u'}, ''), '') + const removed = removeSavedToken(loaded) + assert.equal(removed.token, '') + assert.equal(removed.has_token, undefined) + assert.equal(tokenInputValue(removed, ''), '') + assert.equal(JSON.parse(JSON.stringify(withoutLocalKeys(removed))).token, '') }) test('needsSessionToken: a custom algorithm with a saved key not entered this session', () => { diff --git a/src/services/tokenScope.js b/src/services/tokenScope.js index 93d968ec..e445fa9a 100644 --- a/src/services/tokenScope.js +++ b/src/services/tokenScope.js @@ -33,23 +33,57 @@ export const joinAPIPath = (apiURL, path) => { return `${apiURL}${value.startsWith('/') ? '' : '/'}${value}` } +// Only an http(s):// URL, in any case, is absolute; anything else is a path on the OCL API. +export const isAbsoluteURL = url => /^https?:\/\//i.test(String(url ?? '')) + // A lookup the Mapper sends to the OCL API: none (the target repo), a path, or // a URL on the API's origin. The API doesn't save a token for one. export const isOCLAPILookupURL = (url, apiURL) => - !url || !String(url).startsWith('http') || isAPIHost(url, apiURL) + !url || !isAbsoluteURL(url) || isAPIHost(url, apiURL) // The API never returns a saved token, only has_token. A custom algorithm with // a saved key needs it entered again before it can run in this session. export const needsSessionToken = algo => Boolean(algo?.type === 'custom' && algo?.url && algo?.has_token && !algo?.token) -// Removes token and has_token, at any depth: for copies and run snapshots. +// The same for a lookup on another host. +export const needsSessionLookupToken = (config, apiURL) => + Boolean(config?.has_token && !config?.token && !isOCLAPILookupURL(config?.url, apiURL)) + +// The URL a loaded entry's token was saved with, kept locally so has_token +// comes back if the URL is edited back to it. Never sent to the API. +export const TOKEN_URL_KEY = '__token_url' + +export const withSavedTokenURL = entry => + entry?.has_token ? {...entry, [TOKEN_URL_KEY]: entry.url} : entry + +export const getTokenFlag = (entry, url) => + (entry?.[TOKEN_URL_KEY] && url === entry[TOKEN_URL_KEY]) ? true : undefined + +// An emptied field keeps a saved token (the key is left out); '' clears one +// only once removeSavedToken has been used. +export const tokenInputValue = (entry, value) => + value || (entry?.[TOKEN_URL_KEY] ? undefined : '') + +export const removeSavedToken = entry => + ({...entry, token: '', has_token: undefined, [TOKEN_URL_KEY]: undefined}) + +// The entry as sent to the API: without the Mapper's own local keys. +export const withoutLocalKeys = entry => { + if(!entry || typeof entry !== 'object') + return entry + return Object.fromEntries(Object.entries(entry).filter(([key]) => key !== '__key' && key !== TOKEN_URL_KEY)) +} + +const TOKEN_KEYS = ['token', 'has_token', TOKEN_URL_KEY] + +// Removes tokens and their flags, at any depth: for copies and run snapshots. export const withoutTokens = value => { if(Array.isArray(value)) return value.map(withoutTokens) if(value && typeof value === 'object') return Object.fromEntries( - Object.entries(value).filter(([key]) => key !== 'token' && key !== 'has_token').map(([key, val]) => [key, withoutTokens(val)]) + Object.entries(value).filter(([key]) => !TOKEN_KEYS.includes(key)).map(([key, val]) => [key, withoutTokens(val)]) ) return value } From 502fbe960020c22c151cca7577407b7b5dd80460 Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 12 Nov 2026 13:42:50 +0530 Subject: [PATCH 3/4] OpenConceptLab/ocl_online#201 | Saved key: no unauthenticated check on URL blur; remove action shown with the auth error --- .../map-projects/MultiAlgoSelector.jsx | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/components/map-projects/MultiAlgoSelector.jsx b/src/components/map-projects/MultiAlgoSelector.jsx index b682fc4a..2c7abf56 100644 --- a/src/components/map-projects/MultiAlgoSelector.jsx +++ b/src/components/map-projects/MultiAlgoSelector.jsx @@ -520,7 +520,11 @@ export default function MultiAlgoSelector({ }); } }} - onBlur={() => verifyCustomAlgorithm(sel.__key)} + onBlur={() => { + // Without its saved key this session, a check would only get a 401. + if(!needsSessionToken(sel)) + verifyCustomAlgorithm(sel.__key) + }} placeholder="https://example.com/match" error={Boolean(customMeta.requestError)} helperText={customMeta.requestError || customMeta.requestSuccess || ''} @@ -548,15 +552,16 @@ export default function MultiAlgoSelector({ placeholder="••••••••" error={Boolean(customMeta.tokenRequired && !sel.token)} helperText={ - customMeta.tokenRequired && !sel.token ? 'Authentication is required for this algorithm.' : - (needsSessionToken(sel) ? ( - <> - {t('map_project.api_token_saved')} + (customMeta.tokenRequired && !sel.token) || needsSessionToken(sel) ? ( + <> + {customMeta.tokenRequired && !sel.token ? 'Authentication is required for this algorithm.' : t('map_project.api_token_saved')} + {needsSessionToken(sel) && ( - - ) : '') + )} + + ) : '' } /> From 6f485c1b72b12228edeaafd7887c127f21e04e4a Mon Sep 17 00:00:00 2001 From: Sunny Aggarwal Date: Thu, 12 Nov 2026 14:32:28 +0530 Subject: [PATCH 4/4] OpenConceptLab/ocl_online#201 | No tokens in the Created log entry; detail fetch uses isAbsoluteURL; blank token keeps a saved one; lookup token only to its own origin --- src/components/map-projects/MapProject.jsx | 10 +++++----- .../__tests__/lookupConfigFields.test.js | 7 +++++++ src/components/map-projects/lookupConfigFields.js | 8 +++++++- src/services/__tests__/tokenScope.test.js | 13 ++++++++++++- src/services/tokenScope.js | 8 +++++++- 5 files changed, 38 insertions(+), 8 deletions(-) diff --git a/src/components/map-projects/MapProject.jsx b/src/components/map-projects/MapProject.jsx index 1cbf3e39..23e8065d 100644 --- a/src/components/map-projects/MapProject.jsx +++ b/src/components/map-projects/MapProject.jsx @@ -70,7 +70,7 @@ import pick from 'lodash/pick' import { OperationsContext } from '../app/LayoutContext'; import APIService, { isTransientNetworkError, retryWithBackoff } from '../../services/APIService'; -import { matchToken, lookupToken, needsSessionToken, needsSessionLookupToken, withoutTokens, withSavedTokenURL, withoutLocalKeys, isAbsoluteURL } from '../../services/tokenScope' +import { matchToken, lookupTokenFor, needsSessionToken, needsSessionLookupToken, withoutTokens, withSavedTokenURL, withoutLocalKeys, isAbsoluteURL } from '../../services/tokenScope' import { buildAttributionHeaders, buildConfigSnapshot, summarizeRunCompletion, matchesOnOCL } from '../../services/attribution' import { CAPACITY_LIMIT, RATE_LIMIT, CAPACITY_WAIT_CAP_MS, HEAVY_REQUEST_TIMEOUT_MS, LIGHT_REQUEST_TIMEOUT_MS, createCapacityGate, createLimiter, isRetryableError, requestWithCapacityRetry, sleepUnlessCancelled, untilCancelled } from '../../services/capacity' import { getAPIURL, highlightTexts, dropVersion, getCurrentUser, hasAuthGroup, hasCapability, getMapperPreview, getNewProjectBlockReason, downloadObject, currentUserToken, refreshCurrentUserCapabilitiesCache } from '../../common/utils'; @@ -1803,7 +1803,7 @@ const MapProject = () => { description: isAutoSave ? t('map_project.auto_saved_changes') : undefined, created_at: moment().toDate(), user: user.username || user.id, - extras: isAutoSave ? {reasons: options.reasons || []} : (isUpdate ? undefined : {project: response.data}) + extras: isAutoSave ? {reasons: options.reasons || []} : (isUpdate ? undefined : {project: withoutTokens(response.data)}) } // Entries logged while the save was in flight are kept. A save that // lands after the user opened another project uses the logs as they @@ -5144,8 +5144,8 @@ const MapProject = () => { return service.appendToUrl('concepts/') } - // The token a lookup request to this URL gets (see lookupToken). - const getLookupToken = url => lookupToken(lookupConfig?.token, url, getAPIURL(), currentUserToken()) + // The token a lookup request to this URL gets (see lookupTokenFor). + const getLookupToken = url => lookupTokenFor(lookupConfig, url, getAPIURL(), currentUserToken()) const requestLookup = query => { // Lookups still go out without the saved token, so say once why they may fail. @@ -5285,7 +5285,7 @@ const MapProject = () => { const dataPromise = session.fetchOnce(oclUrl, () => { const attemptFetch = async () => { let service = APIService.new() - if(oclUrl.startsWith('http://') || oclUrl.startsWith('https://')) { + if(isAbsoluteURL(oclUrl)) { service.URL = oclUrl } else { service = service.overrideURL(oclUrl) diff --git a/src/components/map-projects/__tests__/lookupConfigFields.test.js b/src/components/map-projects/__tests__/lookupConfigFields.test.js index 769e2a63..cd512ead 100644 --- a/src/components/map-projects/__tests__/lookupConfigFields.test.js +++ b/src/components/map-projects/__tests__/lookupConfigFields.test.js @@ -27,3 +27,10 @@ test('lookupTokenHasSpaces flags whitespace inside the token only', () => { assert.equal(lookupTokenHasSpaces(''), false) assert.equal(lookupTokenHasSpaces(undefined), false) }) + +test('normalizeLookupConfig: a blank token keeps a saved one, and clears none otherwise', () => { + const saved = normalizeLookupConfig({url: 'https://x.org/', has_token: true, __token_url: 'https://x.org/', token: ' '}) + assert.equal(saved.token, undefined) + assert.equal(JSON.stringify(saved).includes('"token"'), false) + assert.equal(normalizeLookupConfig({url: 'https://x.org/', token: ' '}).token, '') +}) diff --git a/src/components/map-projects/lookupConfigFields.js b/src/components/map-projects/lookupConfigFields.js index 379b7c0d..f238f899 100644 --- a/src/components/map-projects/lookupConfigFields.js +++ b/src/components/map-projects/lookupConfigFields.js @@ -1,3 +1,5 @@ +import { TOKEN_URL_KEY } from '../../services/tokenScope.js' + // Stray whitespace in the lookup URL or token breaks every lookup request: // a padded URL becomes `.../%20concepts/` and a token with a space is // rejected by the API (OpenConceptLab/ocl_issues#2925). @@ -5,7 +7,11 @@ // left for the user to fix. const trim = value => typeof value === 'string' ? value.trim() : value -export const normalizeLookupConfig = config => config ? {...config, url: trim(config.url), token: trim(config.token)} : config +// A token that trims to nothing keeps a saved one (the key is left out), as an +// emptied field does. +export const normalizeLookupConfig = config => config ? { + ...config, url: trim(config.url), token: trim(config.token) || (config[TOKEN_URL_KEY] ? undefined : trim(config.token)), +} : config // A token never contains whitespace; one that does was most likely pasted // with a `Token `/`Bearer ` prefix. diff --git a/src/services/__tests__/tokenScope.test.js b/src/services/__tests__/tokenScope.test.js index 437bbe1f..c5d5a97d 100644 --- a/src/services/__tests__/tokenScope.test.js +++ b/src/services/__tests__/tokenScope.test.js @@ -9,7 +9,7 @@ import assert from 'node:assert/strict' import { isAPIHost, matchToken, lookupToken, joinAPIPath, isOCLAPILookupURL, needsSessionToken, withoutTokens, isAbsoluteURL, needsSessionLookupToken, withSavedTokenURL, getTokenFlag, tokenInputValue, removeSavedToken, - withoutLocalKeys, TOKEN_URL_KEY, + withoutLocalKeys, TOKEN_URL_KEY, lookupTokenFor, } from '../tokenScope.js' const API = 'https://api.example.org' @@ -110,6 +110,7 @@ test('an emptied token field keeps a saved token; removing it clears it', () => assert.equal(tokenInputValue(loaded, ''), undefined) assert.equal(tokenInputValue(loaded, 'T'), 'T') assert.equal(tokenInputValue({url: 'u'}, ''), '') + assert.equal(tokenInputValue(loaded, ' '), undefined) const removed = removeSavedToken(loaded) assert.equal(removed.token, '') assert.equal(removed.has_token, undefined) @@ -135,3 +136,13 @@ test('withoutTokens: removes token and has_token at any depth', () => { assert.deepEqual(withoutTokens({url: 'u', has_token: true}), {url: 'u'}) assert.equal(withoutTokens(null), null) }) + +test('lookupTokenFor: the configured token goes only to the lookup origin', () => { + const external = {url: 'https://terms.example.com/orgs/X/', token: 'LOOKUP'} + assert.equal(lookupTokenFor(external, 'https://terms.example.com/orgs/X/concepts/', API, USER), 'LOOKUP') + assert.equal(lookupTokenFor(external, `${API}/orgs/CIEL/concepts/1/`, API, USER), USER) + assert.equal(lookupTokenFor(external, 'https://evil.example/x/', API, USER), false) + const onOCL = {url: '/orgs/X/sources/Y/', token: 'OWN'} + assert.equal(lookupTokenFor(onOCL, `${API}/orgs/X/sources/Y/concepts/`, API, USER), 'OWN') + assert.equal(lookupTokenFor({}, `${API}/orgs/X/`, API, USER), USER) +}) diff --git a/src/services/tokenScope.js b/src/services/tokenScope.js index e445fa9a..b37de0f6 100644 --- a/src/services/tokenScope.js +++ b/src/services/tokenScope.js @@ -27,6 +27,12 @@ export const matchToken = algo => export const lookupToken = (configToken, url, apiURL, userToken) => configToken || (isAPIHost(url, apiURL) ? userToken : false) +// The configured lookup token goes only to the lookup's own origin: its URL's, or +// the API's for a path. Elsewhere, such as an OCL concept's own URL, lookupToken +// decides without it. +export const lookupTokenFor = (config, url, apiURL, userToken) => + lookupToken(isAPIHost(url, isAbsoluteURL(config?.url) ? config.url : apiURL) ? config?.token : undefined, url, apiURL, userToken) + // Without a leading '/', a value like '@host/x' would change the request's host. export const joinAPIPath = (apiURL, path) => { const value = String(path ?? '') @@ -63,7 +69,7 @@ export const getTokenFlag = (entry, url) => // An emptied field keeps a saved token (the key is left out); '' clears one // only once removeSavedToken has been used. export const tokenInputValue = (entry, value) => - value || (entry?.[TOKEN_URL_KEY] ? undefined : '') + value?.trim() ? value : (entry?.[TOKEN_URL_KEY] ? undefined : '') export const removeSavedToken = entry => ({...entry, token: '', has_token: undefined, [TOKEN_URL_KEY]: undefined})