story 2-11-security-mapping-ui: implemented and reviewed via bmad-loop
This commit is contained in:
1 parent
b18a84b2c5
commit
4307c1d90d
7 files changed
+1840
-17
No files matched your search
Vendored
+47
-3
@@ -376,14 +376,23 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls {
|
||||
.openapi-import-security-status {
|
||||
padding: 6px 0 6px 28px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls,
|
||||
.openapi-import-security-controls {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px 14px;
|
||||
padding-left: 28px;
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls label {
|
||||
.openapi-import-decision-controls label,
|
||||
.openapi-import-security-controls label {
|
||||
display: grid;
|
||||
gap: 5px;
|
||||
color: var(--text-secondary);
|
||||
@@ -392,7 +401,9 @@
|
||||
}
|
||||
|
||||
.openapi-import-decision-controls select,
|
||||
.openapi-import-decision-controls input {
|
||||
.openapi-import-decision-controls input,
|
||||
.openapi-import-security-controls select,
|
||||
.openapi-import-security-controls input {
|
||||
min-width: 210px;
|
||||
max-width: min(100%, 360px);
|
||||
padding: 8px 10px;
|
||||
@@ -402,6 +413,39 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.openapi-import-security {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status {
|
||||
padding-left: 28px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status[data-status="blocked"] {
|
||||
color: var(--red);
|
||||
}
|
||||
|
||||
.openapi-import-security-op-status[data-status="resolved"] {
|
||||
color: var(--green, var(--text-secondary));
|
||||
}
|
||||
|
||||
.openapi-import-security-findings {
|
||||
align-self: center;
|
||||
color: var(--amber, var(--text-secondary));
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.openapi-import-security-guidance {
|
||||
color: var(--text-secondary);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
max-width: 360px;
|
||||
}
|
||||
|
||||
.openapi-import-plan-blocked-help {
|
||||
margin: 0;
|
||||
color: var(--red);
|
||||
|
||||
@@ -612,6 +612,26 @@ var TRANSLATIONS = {
|
||||
'wizard.step2.auth_mode.existing': 'Use existing authorization profile',
|
||||
'wizard.step2.auth_mode.create': 'Create authorization profile now',
|
||||
'openapi.error.plan_too_large': 'Select at most 512 operations and leave at most 512 excluded operations.',
|
||||
'openapi.security.alternative_label': 'Security alternative',
|
||||
'openapi.security.alternative_placeholder': 'Choose a security alternative',
|
||||
'openapi.security.no_auth': 'No authentication',
|
||||
'openapi.security.unsupported': 'unsupported',
|
||||
'openapi.security.profile_label': 'Auth Profile',
|
||||
'openapi.security.profile_placeholder': 'Choose an Auth Profile',
|
||||
'openapi.security.status_no_auth': 'No authentication',
|
||||
'openapi.security.status_required': 'Authentication required',
|
||||
'openapi.security.status_unresolved': 'Unresolved',
|
||||
'openapi.security.status_unverified': 'Unverified',
|
||||
'openapi.security.status_resolved': 'Resolved',
|
||||
'openapi.security.status_blocked': 'Blocked',
|
||||
'openapi.security.empty_profiles': 'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.',
|
||||
'openapi.finding.unsupported_security_scheme': 'Some security requirements could not be imported. Choose a supported alternative or remove the unsupported requirement.',
|
||||
'openapi.finding.unsupported_security_and_requirement': 'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.',
|
||||
'openapi.error.security_with_skip': 'A skipped operation cannot be bound to an Auth Profile or a security alternative.',
|
||||
'openapi.error.auth_unavailable': 'The selected Auth Profile is unavailable or its required Secret is missing. Choose another compatible profile and create a new plan.',
|
||||
'openapi.error.auth_incompatible': 'The Auth Profile scheme does not match the selected security alternative. Choose a compatible alternative or profile and create a new plan.',
|
||||
'openapi.error.auth_profile_required': 'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.',
|
||||
'openapi.error.security_alternative_required': 'The Auth Profile matches multiple security alternatives. Select the exact alternative and create a new plan.',
|
||||
'wizard.step2.auth_profile': 'Authorization profile',
|
||||
'wizard.step2.auth_profile_hint': 'The selected profile is applied automatically on every tool call.',
|
||||
'wizard.step2.auth_profile_empty': 'No authorization profiles yet. Create one below.',
|
||||
@@ -1660,6 +1680,26 @@ var TRANSLATIONS = {
|
||||
'wizard.step2.auth_mode.existing': 'Использовать существующий профиль авторизации',
|
||||
'wizard.step2.auth_mode.create': 'Создать профиль авторизации сейчас',
|
||||
'openapi.error.plan_too_large': 'Выберите не более 512 операций и оставьте не более 512 исключённых операций.',
|
||||
'openapi.security.alternative_label': 'Вариант безопасности',
|
||||
'openapi.security.alternative_placeholder': 'Выберите вариант безопасности',
|
||||
'openapi.security.no_auth': 'Без аутентификации',
|
||||
'openapi.security.unsupported': 'не поддерживается',
|
||||
'openapi.security.profile_label': 'Профиль авторизации',
|
||||
'openapi.security.profile_placeholder': 'Выберите профиль авторизации',
|
||||
'openapi.security.status_no_auth': 'Без аутентификации',
|
||||
'openapi.security.status_required': 'Требуется аутентификация',
|
||||
'openapi.security.status_unresolved': 'Не разрешено',
|
||||
'openapi.security.status_unverified': 'Не проверено',
|
||||
'openapi.security.status_resolved': 'Разрешено',
|
||||
'openapi.security.status_blocked': 'Заблокировано',
|
||||
'openapi.security.empty_profiles': 'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.',
|
||||
'openapi.finding.unsupported_security_scheme': 'Некоторые security requirements нельзя импортировать. Выберите поддерживаемый вариант или уберите неподдерживаемое требование.',
|
||||
'openapi.finding.unsupported_security_and_requirement': 'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.',
|
||||
'openapi.error.security_with_skip': 'Пропускаемая операция не может быть связана с профилем авторизации или вариантом безопасности.',
|
||||
'openapi.error.auth_unavailable': 'Выбранный профиль авторизации недоступен, либо отсутствует его обязательный Secret. Выберите другой совместимый профиль и создайте новый план.',
|
||||
'openapi.error.auth_incompatible': 'Схема профиля авторизации не совпадает с выбранным вариантом безопасности. Выберите совместимый вариант или профиль и создайте новый план.',
|
||||
'openapi.error.auth_profile_required': 'Для этой операции требуется профиль авторизации. Выберите совместимый профиль и создайте новый план.',
|
||||
'openapi.error.security_alternative_required': 'Профиль авторизации подходит к нескольким вариантам безопасности. Выберите точный вариант и создайте новый план.',
|
||||
'wizard.step2.auth_profile': 'Профиль авторизации',
|
||||
'wizard.step2.auth_profile_hint': 'Выбранный профиль применяется автоматически при каждом вызове инструмента.',
|
||||
'wizard.step2.auth_profile_empty': 'Профилей авторизации пока нет. Создайте профиль ниже.',
|
||||
|
||||
+437
-13
@@ -12,6 +12,9 @@
|
||||
operationsReady: false,
|
||||
decisions: Object.create(null),
|
||||
plan: null,
|
||||
securityChoices: [],
|
||||
securityStatus: 'unresolved',
|
||||
securityByOperation: Object.create(null),
|
||||
filterQuery: '',
|
||||
filterMethod: '',
|
||||
revision: 0,
|
||||
@@ -130,7 +133,13 @@
|
||||
|
||||
function decisionFor(operationKey) {
|
||||
if (!state.decisions[operationKey]) {
|
||||
state.decisions[operationKey] = { action: 'create', targetOperationId: '', confirmedName: '' };
|
||||
state.decisions[operationKey] = {
|
||||
action: 'create',
|
||||
targetOperationId: '',
|
||||
confirmedName: '',
|
||||
securityAlternativeIndex: null,
|
||||
authProfileId: null,
|
||||
};
|
||||
}
|
||||
return state.decisions[operationKey];
|
||||
}
|
||||
@@ -185,6 +194,8 @@
|
||||
}
|
||||
}
|
||||
renderDecisionControls(operation, row);
|
||||
renderSecurityControls(operation, row);
|
||||
updateSecuritySummary();
|
||||
});
|
||||
actionLabel.appendChild(actionSelect);
|
||||
controls.appendChild(actionLabel);
|
||||
@@ -285,6 +296,8 @@
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
updateSecuritySummary();
|
||||
}
|
||||
|
||||
function applyFilters() {
|
||||
@@ -342,6 +355,9 @@
|
||||
missing_servers: 'openapi.finding.missing_servers',
|
||||
multiple_servers: 'openapi.finding.multiple_servers',
|
||||
unsupported_request_body: 'openapi.finding.unsupported_request_body',
|
||||
unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme',
|
||||
unsupported_security_and_requirement: 'openapi.finding.unsupported_security_and_requirement',
|
||||
auth_profile_required: 'openapi.error.auth_profile_required',
|
||||
operation_name_renamed: 'openapi.finding.operation_name_renamed',
|
||||
operation_name_conflict: 'openapi.finding.operation_name_conflict',
|
||||
weak_tool_description: 'openapi.finding.weak_tool_description',
|
||||
@@ -462,6 +478,303 @@
|
||||
});
|
||||
}
|
||||
|
||||
var SECURITY_STATUS_KEYS = {
|
||||
no_auth: 'openapi.security.status_no_auth',
|
||||
required: 'openapi.security.status_required',
|
||||
unresolved: 'openapi.security.status_unresolved',
|
||||
unverified: 'openapi.security.status_unverified',
|
||||
resolved: 'openapi.security.status_resolved',
|
||||
blocked: 'openapi.security.status_blocked',
|
||||
};
|
||||
var SECURITY_PLAN_ERROR_CODES = [
|
||||
'import_plan_auth_unavailable',
|
||||
'import_plan_auth_incompatible',
|
||||
'import_plan_security_alternative_required',
|
||||
];
|
||||
|
||||
function securityStatusLabel(status) {
|
||||
return tKey(SECURITY_STATUS_KEYS[status] || SECURITY_STATUS_KEYS.unresolved);
|
||||
}
|
||||
|
||||
function renderSecurityStatus() {
|
||||
var node = qs('openapi-import-security-status');
|
||||
if (!node) return;
|
||||
node.textContent = securityStatusLabel(state.securityStatus);
|
||||
}
|
||||
|
||||
function setSecurityStatus(status) {
|
||||
state.securityStatus = status;
|
||||
renderSecurityStatus();
|
||||
}
|
||||
|
||||
function securityOperationNode(operationKey) {
|
||||
// Compare dataset values against a constant selector: imported operation
|
||||
// keys are untrusted and must never be interpolated into a CSS selector.
|
||||
var nodes = document.querySelectorAll('[data-openapi-security-op-status]');
|
||||
for (var i = 0; i < nodes.length; i += 1) {
|
||||
if (nodes[i].dataset.openapiSecurityOpStatus === operationKey) return nodes[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function renderOperationSecurityStatus(operationKey) {
|
||||
var node = securityOperationNode(operationKey);
|
||||
if (!node) return;
|
||||
var status = state.securityByOperation[operationKey] || 'unresolved';
|
||||
node.dataset.status = status;
|
||||
node.textContent = securityStatusLabel(status);
|
||||
}
|
||||
|
||||
function setOperationSecurityStatus(operationKey, status) {
|
||||
state.securityByOperation[operationKey] = status;
|
||||
renderOperationSecurityStatus(operationKey);
|
||||
}
|
||||
|
||||
// Summary only: the per-operation nodes carry the authority, this aggregate
|
||||
// id reports whether any selected operation still needs attention.
|
||||
function updateSecuritySummary() {
|
||||
var selected = new Set(selectedKeys());
|
||||
var statuses = [];
|
||||
importOperations().forEach(function(operation) {
|
||||
if (!selected.has(operation.key)) return;
|
||||
statuses.push(state.securityByOperation[operation.key] || baselineSecurityStatus(operation));
|
||||
});
|
||||
var summary = 'unresolved';
|
||||
if (statuses.indexOf('blocked') >= 0) summary = 'blocked';
|
||||
else if (statuses.indexOf('required') >= 0) summary = 'required';
|
||||
else if (statuses.indexOf('unverified') >= 0) summary = 'unverified';
|
||||
else if (statuses.indexOf('resolved') >= 0) summary = 'resolved';
|
||||
else if (statuses.length && statuses.every(function(status) { return status === 'no_auth'; })) summary = 'no_auth';
|
||||
setSecurityStatus(summary);
|
||||
}
|
||||
|
||||
function securityAlternativesFor(operation) {
|
||||
var requirements = operation && operation.security_requirements;
|
||||
return requirements && Array.isArray(requirements.alternatives) ? requirements.alternatives : [];
|
||||
}
|
||||
|
||||
function alternativeFor(operation, index) {
|
||||
if (index === null || index === undefined) return null;
|
||||
return securityAlternativesFor(operation)[Number(index)] || null;
|
||||
}
|
||||
|
||||
function isAnonymousAlternative(alternative) {
|
||||
if (!alternative || alternative.supported === false) return false;
|
||||
var schemes = Array.isArray(alternative.schemes) ? alternative.schemes : [];
|
||||
return schemes.length === 0;
|
||||
}
|
||||
|
||||
function operationRequiresAuth(operation) {
|
||||
return securityAlternativesFor(operation).some(function(alternative) {
|
||||
return alternative && alternative.supported !== false
|
||||
&& Array.isArray(alternative.schemes) && alternative.schemes.length > 0;
|
||||
});
|
||||
}
|
||||
|
||||
function securityProfilesFor(operation, alternativeIndex) {
|
||||
var profiles = [];
|
||||
(state.securityChoices || []).forEach(function(choice) {
|
||||
if (!choice || choice.operation_key !== operation.key) return;
|
||||
// Filter to the exact selected alternative. While no alternative is
|
||||
// chosen the safe union supports profile-first selection and lets the
|
||||
// API own compatibility validation.
|
||||
if (alternativeIndex !== null && alternativeIndex !== undefined
|
||||
&& Number(choice.alternative_index) !== Number(alternativeIndex)) return;
|
||||
if (Array.isArray(choice.profiles)) profiles = profiles.concat(choice.profiles);
|
||||
});
|
||||
// Keep a stable order across alternatives: first occurrence wins.
|
||||
var seen = {};
|
||||
return profiles.filter(function(profile) {
|
||||
if (!profile || typeof profile.id !== 'string' || !profile.id || seen[profile.id]) return false;
|
||||
seen[profile.id] = true;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// Local expectation only; resolved/blocked never originate here.
|
||||
function baselineSecurityStatus(operation) {
|
||||
var alternatives = securityAlternativesFor(operation);
|
||||
if (!alternatives.length) return 'no_auth';
|
||||
var decision = decisionFor(operation.key);
|
||||
if (decision.action === 'skip') return 'unresolved';
|
||||
if (!alternatives.some(function(alternative) { return alternative && alternative.supported !== false; })) {
|
||||
return 'blocked';
|
||||
}
|
||||
if (!operationRequiresAuth(operation)) return 'no_auth';
|
||||
var alternative = alternativeFor(operation, decision.securityAlternativeIndex);
|
||||
if (isAnonymousAlternative(alternative)) return 'unresolved';
|
||||
if (decision.authProfileId) return 'unresolved';
|
||||
return 'required';
|
||||
}
|
||||
|
||||
function resetSecurityStatuses() {
|
||||
importOperations().forEach(function(operation) {
|
||||
state.securityByOperation[operation.key] = baselineSecurityStatus(operation);
|
||||
renderOperationSecurityStatus(operation.key);
|
||||
});
|
||||
updateSecuritySummary();
|
||||
}
|
||||
|
||||
function operationRowFor(operation) {
|
||||
return Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(row) {
|
||||
var input = row.querySelector('[data-openapi-operation]');
|
||||
return input && input.value === operation.key;
|
||||
}) || null;
|
||||
}
|
||||
|
||||
function invalidatePendingPlan() {
|
||||
// Even without a stored plan a prior blocked state must be cleared: the
|
||||
// edited selection is unverified until the next plan response arrives.
|
||||
if (state.plan) {
|
||||
state.plan = null;
|
||||
qs('openapi-import-plan-confirmation').hidden = true;
|
||||
qs('openapi-import-plan-counts').replaceChildren();
|
||||
qs('openapi-import-plan-candidates').replaceChildren();
|
||||
qs('openapi-import-versioning-consequences').hidden = true;
|
||||
qs('openapi-import-plan-blocked-help').hidden = true;
|
||||
}
|
||||
resetSecurityStatuses();
|
||||
}
|
||||
|
||||
function renderSecurityControls(operation, row) {
|
||||
var previous = row.querySelector('.openapi-import-security');
|
||||
if (previous) previous.remove();
|
||||
|
||||
var decision = decisionFor(operation.key);
|
||||
var alternatives = securityAlternativesFor(operation);
|
||||
|
||||
if (decision.action === 'skip') {
|
||||
// A skipped operation keeps the existing operation untouched: no
|
||||
// security binding may be attached, so clear it instead of trapping the
|
||||
// user in a local validation error.
|
||||
decision.authProfileId = null;
|
||||
decision.securityAlternativeIndex = null;
|
||||
setOperationSecurityStatus(operation.key, 'unresolved');
|
||||
return;
|
||||
}
|
||||
|
||||
var wrapper = document.createElement('div');
|
||||
wrapper.className = 'openapi-import-security';
|
||||
|
||||
var statusNode = document.createElement('span');
|
||||
statusNode.className = 'openapi-import-security-op-status';
|
||||
statusNode.setAttribute('data-openapi-security-op-status', operation.key);
|
||||
statusNode.setAttribute('data-testid', 'openapi-security-op-status');
|
||||
// Announce per-operation changes even when the aggregate text is unchanged.
|
||||
statusNode.setAttribute('role', 'status');
|
||||
statusNode.setAttribute('aria-live', 'polite');
|
||||
wrapper.appendChild(statusNode);
|
||||
|
||||
if (alternatives.length) {
|
||||
var controls = document.createElement('div');
|
||||
controls.className = 'openapi-import-security-controls';
|
||||
|
||||
// Only the alternative index and the typed profile id are stored locally.
|
||||
// The API remains the authority for OR/AND semantics and compatibility.
|
||||
var alternativeLabel = document.createElement('label');
|
||||
var alternativeSelect = document.createElement('select');
|
||||
alternativeLabel.textContent = tKey('openapi.security.alternative_label');
|
||||
alternativeSelect.dataset.openapiSecurityAlternative = operation.key;
|
||||
|
||||
var alternativePlaceholder = document.createElement('option');
|
||||
alternativePlaceholder.value = '';
|
||||
alternativePlaceholder.textContent = tKey('openapi.security.alternative_placeholder');
|
||||
alternativeSelect.appendChild(alternativePlaceholder);
|
||||
|
||||
var findingsNode = null;
|
||||
alternatives.forEach(function(alternative, index) {
|
||||
var option = document.createElement('option');
|
||||
var schemes = alternative && Array.isArray(alternative.schemes) ? alternative.schemes : [];
|
||||
option.value = String(index);
|
||||
option.textContent = schemes.length ? schemes.join(' + ') : tKey('openapi.security.no_auth');
|
||||
if (alternative && alternative.supported === false) {
|
||||
option.disabled = true;
|
||||
option.textContent += ' · ' + tKey('openapi.security.unsupported');
|
||||
var finding = Array.isArray(alternative.findings) && alternative.findings[0];
|
||||
// Surface the blocker as a safe, localized message next to the control.
|
||||
if (finding) {
|
||||
if (!findingsNode) {
|
||||
findingsNode = document.createElement('span');
|
||||
findingsNode.className = 'openapi-import-security-findings';
|
||||
}
|
||||
var findingSpan = document.createElement('span');
|
||||
findingSpan.className = 'openapi-import-finding openapi-import-finding-warning';
|
||||
findingSpan.textContent = findingMessage({ code: finding });
|
||||
findingsNode.appendChild(findingSpan);
|
||||
}
|
||||
}
|
||||
alternativeSelect.appendChild(option);
|
||||
});
|
||||
|
||||
alternativeSelect.value = decision.securityAlternativeIndex === null
|
||||
? ''
|
||||
: String(decision.securityAlternativeIndex);
|
||||
alternativeSelect.addEventListener('change', function() {
|
||||
// Switching the alternative invalidates the previous profile binding and
|
||||
// any server-confirmed plan: the API revalidates the current selection.
|
||||
decision.securityAlternativeIndex = alternativeSelect.value === ''
|
||||
? null
|
||||
: Number(alternativeSelect.value);
|
||||
decision.authProfileId = null;
|
||||
invalidatePendingPlan();
|
||||
renderSecurityControls(operation, row);
|
||||
});
|
||||
alternativeLabel.appendChild(alternativeSelect);
|
||||
controls.appendChild(alternativeLabel);
|
||||
if (findingsNode) controls.appendChild(findingsNode);
|
||||
|
||||
var selectedAlternative = alternativeFor(operation, decision.securityAlternativeIndex);
|
||||
var anonymous = isAnonymousAlternative(selectedAlternative);
|
||||
var profiles = securityProfilesFor(operation, decision.securityAlternativeIndex);
|
||||
|
||||
// An anonymous alternative must offer no profile at all.
|
||||
if (!anonymous) {
|
||||
var profileLabel = document.createElement('label');
|
||||
var profileSelect = document.createElement('select');
|
||||
profileLabel.textContent = tKey('openapi.security.profile_label');
|
||||
profileSelect.dataset.openapiSecurityProfile = operation.key;
|
||||
|
||||
var profilePlaceholder = document.createElement('option');
|
||||
profilePlaceholder.value = '';
|
||||
profilePlaceholder.textContent = tKey('openapi.security.profile_placeholder');
|
||||
profileSelect.appendChild(profilePlaceholder);
|
||||
|
||||
profiles.forEach(function(profile) {
|
||||
// Safe metadata only: id, name, kind. Never credential material.
|
||||
var option = document.createElement('option');
|
||||
option.value = profile.id;
|
||||
option.textContent = String(profile.name || profile.id);
|
||||
if (profile.kind) option.textContent += ' · ' + profile.kind;
|
||||
profileSelect.appendChild(option);
|
||||
});
|
||||
|
||||
var emptyProfiles = decision.securityAlternativeIndex !== null
|
||||
&& selectedAlternative && selectedAlternative.supported !== false
|
||||
&& !anonymous && profiles.length === 0;
|
||||
if (emptyProfiles) {
|
||||
profileSelect.disabled = true;
|
||||
var guidance = document.createElement('span');
|
||||
guidance.className = 'openapi-import-security-guidance';
|
||||
guidance.textContent = tKey('openapi.security.empty_profiles');
|
||||
profileLabel.appendChild(guidance);
|
||||
}
|
||||
|
||||
profileSelect.value = decision.authProfileId || '';
|
||||
profileSelect.addEventListener('change', function() {
|
||||
decision.authProfileId = profileSelect.value || null;
|
||||
invalidatePendingPlan();
|
||||
});
|
||||
profileLabel.appendChild(profileSelect);
|
||||
controls.appendChild(profileLabel);
|
||||
}
|
||||
|
||||
wrapper.appendChild(controls);
|
||||
}
|
||||
|
||||
row.appendChild(wrapper);
|
||||
setOperationSecurityStatus(operation.key, baselineSecurityStatus(operation));
|
||||
}
|
||||
|
||||
function renderPreview(response) {
|
||||
var preview = response.preview;
|
||||
var count = (preview.groups || []).reduce(function(sum, group) {
|
||||
@@ -475,6 +788,10 @@
|
||||
state.existingOperations = [];
|
||||
state.operationsReady = false;
|
||||
state.decisions = Object.create(null);
|
||||
state.securityChoices = Array.isArray(response.security_profile_choices)
|
||||
? response.security_profile_choices
|
||||
: [];
|
||||
state.securityByOperation = Object.create(null);
|
||||
importOperations().forEach(function(operation) { decisionFor(operation.key); });
|
||||
state.filterQuery = '';
|
||||
state.filterMethod = '';
|
||||
@@ -543,6 +860,7 @@
|
||||
}
|
||||
|
||||
renderDecisionControls(operation, row);
|
||||
renderSecurityControls(operation, row);
|
||||
groupNode.appendChild(row);
|
||||
});
|
||||
|
||||
@@ -560,6 +878,7 @@
|
||||
input.addEventListener('change', updateSelection);
|
||||
});
|
||||
applyFilters();
|
||||
resetSecurityStatuses();
|
||||
}
|
||||
|
||||
function validateFile(file) {
|
||||
@@ -592,6 +911,9 @@
|
||||
state.existingOperations = [];
|
||||
state.operationsReady = false;
|
||||
state.decisions = Object.create(null);
|
||||
state.securityChoices = [];
|
||||
state.securityStatus = 'unresolved';
|
||||
state.securityByOperation = Object.create(null);
|
||||
state.plan = null;
|
||||
state.applyRequest = null;
|
||||
state.applyMetadata = [];
|
||||
@@ -607,6 +929,7 @@
|
||||
qs('openapi-import-versioning-consequences').hidden = true;
|
||||
qs('openapi-import-plan-blocked-help').hidden = true;
|
||||
qs('openapi-import-groups').replaceChildren();
|
||||
renderSecurityStatus();
|
||||
qs('openapi-import-result').hidden = true;
|
||||
qs('openapi-import-result').replaceChildren();
|
||||
updateSelection();
|
||||
@@ -665,6 +988,9 @@
|
||||
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
|
||||
input.disabled = locked;
|
||||
});
|
||||
document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) {
|
||||
input.disabled = locked;
|
||||
});
|
||||
}
|
||||
|
||||
function lockPlanEditing(locked) {
|
||||
@@ -684,6 +1010,9 @@
|
||||
document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) {
|
||||
input.disabled = locked;
|
||||
});
|
||||
document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) {
|
||||
input.disabled = locked;
|
||||
});
|
||||
}
|
||||
|
||||
function markApplyOutcomeUnknown(options) {
|
||||
@@ -743,6 +1072,9 @@
|
||||
'openapi_upload.storage_unavailable': 'openapi.error.storage_unavailable',
|
||||
'openapi_upload.source_integrity': 'openapi.error.source_integrity',
|
||||
'openapi_upload.source_unavailable': 'openapi.error.source_unavailable',
|
||||
'import_plan_auth_unavailable': 'openapi.error.auth_unavailable',
|
||||
'import_plan_auth_incompatible': 'openapi.error.auth_incompatible',
|
||||
'import_plan_security_alternative_required': 'openapi.error.security_alternative_required',
|
||||
};
|
||||
var message = tKey(known[error && error.code] || fallback);
|
||||
var identifiers = [];
|
||||
@@ -796,11 +1128,11 @@
|
||||
state.existingOperations = operationResponse.items;
|
||||
state.operationsReady = true;
|
||||
importOperations().forEach(function(operation) {
|
||||
var row = Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(candidateRow) {
|
||||
var input = candidateRow.querySelector('[data-openapi-operation]');
|
||||
return input && input.value === operation.key;
|
||||
});
|
||||
if (row) renderDecisionControls(operation, row);
|
||||
var row = operationRowFor(operation);
|
||||
if (row) {
|
||||
renderDecisionControls(operation, row);
|
||||
renderSecurityControls(operation, row);
|
||||
}
|
||||
});
|
||||
qs('openapi-import-create').disabled = false;
|
||||
setStatus(tKey('openapi.status.preview_ready'));
|
||||
@@ -997,6 +1329,33 @@
|
||||
var versioningNode = qs('openapi-import-versioning-consequences');
|
||||
var counts = plan.counts || {};
|
||||
var hasBlocked = (Number(counts.blocked) || 0) > 0;
|
||||
var operationsByKey = Object.create(null);
|
||||
importOperations().forEach(function(operation) { operationsByKey[operation.key] = operation; });
|
||||
|
||||
// The plan API is the sole authority for each operation's binding outcome.
|
||||
(Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) {
|
||||
if (!candidate || !candidate.key) return;
|
||||
var operation = operationsByKey[candidate.key];
|
||||
var alternativeIndex = candidate.security_alternative_index;
|
||||
var anonymous = alternativeIndex !== null && alternativeIndex !== undefined
|
||||
&& isAnonymousAlternative(alternativeFor(operation, alternativeIndex));
|
||||
var status;
|
||||
if (candidate.state === 'blocked') {
|
||||
status = 'blocked';
|
||||
} else if (candidate.state === 'actionable') {
|
||||
// Only a genuine auth binding confirmed by the API is resolved; a
|
||||
// no-auth/anonymous or unbound candidate must never read as resolved.
|
||||
if (candidate.auth_profile_id) status = 'resolved';
|
||||
else if (operation && !operationRequiresAuth(operation)) status = 'no_auth';
|
||||
else if (anonymous) status = 'no_auth';
|
||||
else status = 'unresolved';
|
||||
} else {
|
||||
// Excluded/skipped candidates keep the operation untouched.
|
||||
status = 'unresolved';
|
||||
}
|
||||
setOperationSecurityStatus(candidate.key, status);
|
||||
});
|
||||
updateSecuritySummary();
|
||||
var countSpecs = [
|
||||
['selected', 'openapi.plan.selected'],
|
||||
['excluded', 'openapi.plan.excluded'],
|
||||
@@ -1241,6 +1600,8 @@
|
||||
state.plan = null;
|
||||
qs('openapi-import-plan-confirmation').hidden = true;
|
||||
lockPlanEditing(false);
|
||||
// A rejected/repreview Apply voids the prior resolved security review.
|
||||
resetSecurityStatuses();
|
||||
if (!qs('openapi-import-modal').hidden) {
|
||||
if (recovery === 'repreview_required') {
|
||||
setStatus(tKey('openapi.plan.repreview'), true, true);
|
||||
@@ -1308,6 +1669,16 @@
|
||||
var selectedSet = new Set(keys);
|
||||
var decisions = [];
|
||||
var invalidDecision = null;
|
||||
importOperations().forEach(function(operation) {
|
||||
if (!selectedSet.has(operation.key)) return;
|
||||
var decision = decisionFor(operation.key);
|
||||
// Skip decisions keep the existing operation untouched: no security
|
||||
// binding may be attached to them.
|
||||
if (decision.action === 'skip'
|
||||
&& (decision.authProfileId || decision.securityAlternativeIndex !== null)) {
|
||||
invalidDecision = 'openapi.error.security_with_skip';
|
||||
}
|
||||
});
|
||||
importOperations().forEach(function(operation) {
|
||||
if (!selectedSet.has(operation.key) || invalidDecision) return;
|
||||
var decision = decisionFor(operation.key);
|
||||
@@ -1332,7 +1703,19 @@
|
||||
invalidDecision = 'openapi.error.decision_action';
|
||||
return;
|
||||
}
|
||||
if (decision.action !== 'create') decisions.push(output);
|
||||
// Security binding is a typed reference only: alternative index and,
|
||||
// when chosen, the profile id. Resolution stays server-side.
|
||||
if (decision.action !== 'skip') {
|
||||
if (decision.authProfileId) output.auth_profile_id = decision.authProfileId;
|
||||
if (decision.securityAlternativeIndex !== null) {
|
||||
output.security_alternative_index = decision.securityAlternativeIndex;
|
||||
}
|
||||
}
|
||||
if (decision.action !== 'create'
|
||||
|| decision.authProfileId
|
||||
|| decision.securityAlternativeIndex !== null) {
|
||||
decisions.push(output);
|
||||
}
|
||||
});
|
||||
if (invalidDecision) {
|
||||
setStatus(tKey(invalidDecision), true, true);
|
||||
@@ -1386,6 +1769,16 @@
|
||||
}
|
||||
setStatus(errorStatus(error, 'openapi.error.plan'), true, true);
|
||||
showRetry(true);
|
||||
// A typed API rejection of a security binding is authoritative blocked;
|
||||
// a transport/network failure only means the selection is unverified.
|
||||
var securityRejection = Number.isInteger(error && error.status)
|
||||
&& error.status >= 400 && error.status < 500
|
||||
&& SECURITY_PLAN_ERROR_CODES.indexOf(String(error.code)) >= 0;
|
||||
importOperations().forEach(function(operation) {
|
||||
if (!selectedSet.has(operation.key) || !securityAlternativesFor(operation).length) return;
|
||||
setOperationSecurityStatus(operation.key, securityRejection ? 'blocked' : 'unverified');
|
||||
});
|
||||
updateSecuritySummary();
|
||||
} finally {
|
||||
if (state.planController === controller) {
|
||||
state.planController = null;
|
||||
@@ -1422,6 +1815,9 @@
|
||||
function backToImportSelection() {
|
||||
if (state.applyInFlight || state.applyOutcomeUnknown) return;
|
||||
state.plan = null;
|
||||
// Returning to editing voids the previous review: revalidation is done by
|
||||
// the next plan request.
|
||||
resetSecurityStatuses();
|
||||
qs('openapi-import-plan-confirmation').hidden = true;
|
||||
qs('openapi-import-plan-counts').replaceChildren();
|
||||
qs('openapi-import-plan-candidates').replaceChildren();
|
||||
@@ -1530,6 +1926,18 @@
|
||||
|
||||
renderFileName();
|
||||
|
||||
// Dedicated screen-reader output for the API-authoritative binding state.
|
||||
var groupsNode = qs('openapi-import-groups');
|
||||
if (!qs('openapi-import-security-status') && groupsNode && groupsNode.parentNode) {
|
||||
var securityStatusNode = document.createElement('div');
|
||||
securityStatusNode.id = 'openapi-import-security-status';
|
||||
securityStatusNode.className = 'openapi-import-security-status';
|
||||
securityStatusNode.setAttribute('data-testid', 'openapi-security-status');
|
||||
securityStatusNode.setAttribute('role', 'status');
|
||||
securityStatusNode.setAttribute('aria-live', 'polite');
|
||||
groupsNode.parentNode.insertBefore(securityStatusNode, groupsNode);
|
||||
}
|
||||
|
||||
qs('openapi-import-file-select').addEventListener('click', function(event) {
|
||||
event.preventDefault();
|
||||
qs('openapi-import-file').click();
|
||||
@@ -1601,14 +2009,30 @@
|
||||
setStatus(tKey('openapi.status.context_changed'));
|
||||
}
|
||||
}
|
||||
function handleLanguageChange() {
|
||||
if (!qs('openapi-import-modal').hidden && state.plan && !state.applyInFlight && !state.applyOutcomeUnknown) {
|
||||
renderImportPlan(state.plan);
|
||||
setStatus(tKey('openapi.status.plan_ready'));
|
||||
return;
|
||||
}
|
||||
function handleLanguageChange() {
|
||||
// While an Apply owns the locked controls, re-rendering would re-enable
|
||||
// them. Route straight to the context-change path, which marks the apply
|
||||
// outcome unknown and keeps the controls locked.
|
||||
if (state.applyInFlight || state.applyController || (state.applyOutcomeUnknown && state.applyRequest)) {
|
||||
renderSecurityStatus();
|
||||
invalidateForContext();
|
||||
return;
|
||||
}
|
||||
importOperations().forEach(function(operation) {
|
||||
var row = operationRowFor(operation);
|
||||
if (row) {
|
||||
renderDecisionControls(operation, row);
|
||||
renderSecurityControls(operation, row);
|
||||
}
|
||||
});
|
||||
if (!qs('openapi-import-modal').hidden && state.plan) {
|
||||
renderImportPlan(state.plan);
|
||||
setStatus(tKey('openapi.status.plan_ready'));
|
||||
return;
|
||||
}
|
||||
updateSecuritySummary();
|
||||
invalidateForContext();
|
||||
}
|
||||
window.addEventListener('crank:langchange', handleLanguageChange);
|
||||
window.addEventListener('crank:workspacechange', function(event) {
|
||||
if (!qs('openapi-import-modal').hidden) {
|
||||
|
||||
@@ -0,0 +1,979 @@
|
||||
const { test, expect } = require('@playwright/test');
|
||||
const { browserJson, getCurrentWorkspace, login, localized, uniqueName } = require('./helpers');
|
||||
|
||||
const operationKey = 'get:/protected';
|
||||
const profileId = 'auth_profile_safe_bearer';
|
||||
const secretCanary = 'SECRET_CANARY_do_not_render_or_store';
|
||||
|
||||
function securityPreview() {
|
||||
return {
|
||||
job_id: 'job_security_mapping_atdd',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
preview: {
|
||||
source: { servers: ['https://api.example.test'] },
|
||||
findings: [],
|
||||
groups: [{
|
||||
title: 'protected operations',
|
||||
operations: [{
|
||||
key: operationKey,
|
||||
method: 'GET',
|
||||
path: '/protected',
|
||||
suggested_name: 'protected_operation',
|
||||
suggested_display_name: 'Protected operation',
|
||||
input_fields: 0,
|
||||
output_fields: 0,
|
||||
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
|
||||
findings: [{
|
||||
code: 'unsupported_security_scheme',
|
||||
severity: 'warning',
|
||||
message: 'Unsupported scheme details are intentionally opaque',
|
||||
construct_id: 'security_scheme_unsupported',
|
||||
location: { path: '/paths/~1protected/get/security' },
|
||||
operation_key: operationKey,
|
||||
}],
|
||||
security_requirements: {
|
||||
source: 'document',
|
||||
alternatives: [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: [], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
],
|
||||
},
|
||||
}],
|
||||
}],
|
||||
},
|
||||
security_profile_choices: [
|
||||
{
|
||||
operation_key: operationKey,
|
||||
alternative_index: 0,
|
||||
schemes: ['bearerAuth'],
|
||||
profiles: [{ id: profileId, name: 'Production bearer', kind: 'bearer' }],
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function protectedOperation(key, suggestedName, alternatives) {
|
||||
return {
|
||||
key,
|
||||
method: 'GET',
|
||||
path: '/' + key.split('/').pop(),
|
||||
suggested_name: suggestedName,
|
||||
suggested_display_name: suggestedName,
|
||||
input_fields: 0,
|
||||
output_fields: 0,
|
||||
draft: { input_mapping: { rules: [] }, output_mapping: { rules: [] } },
|
||||
findings: [],
|
||||
security_requirements: { source: 'document', alternatives },
|
||||
};
|
||||
}
|
||||
|
||||
function previewWith(operations, choices) {
|
||||
return {
|
||||
job_id: 'job_security_multi_atdd',
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
preview: {
|
||||
source: { servers: ['https://api.example.test'] },
|
||||
findings: [],
|
||||
groups: [{ title: 'protected operations', operations }],
|
||||
},
|
||||
security_profile_choices: choices,
|
||||
};
|
||||
}
|
||||
|
||||
async function dismissOnboardingIfOpen(page) {
|
||||
// Same harness hygiene as openapi-import-plan.spec.js and operations.spec.js:
|
||||
// the overlay intercepts pointer events on a fresh E2E stack.
|
||||
await page.locator('#crank-onboarding-panel').waitFor({ state: 'attached' });
|
||||
await page.locator('[data-testid="onboarding-dismiss"]').waitFor({ state: 'attached' });
|
||||
await page.evaluate(() => {
|
||||
const dismiss = document.querySelector('[data-testid="onboarding-dismiss"]');
|
||||
if (dismiss) dismiss.click();
|
||||
});
|
||||
await expect(page.locator('#crank-onboarding-panel')).toBeHidden();
|
||||
}
|
||||
|
||||
async function openSecurityPreview(page, locale = 'en', previewPayload = securityPreview()) {
|
||||
// Register the preview boundary before navigation so the upload is deterministic.
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(previewPayload),
|
||||
});
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate((language) => window.setLang(language), locale);
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
}
|
||||
|
||||
function actionablePlan(decision) {
|
||||
return {
|
||||
plan_reference: 'plan_security_mapping_atdd',
|
||||
plan_digest: 'c'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: 'protected_operation',
|
||||
state: 'actionable',
|
||||
action: decision.action,
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index,
|
||||
reason: null,
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
function containsCredentialField(value) {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
return Object.entries(value).some(([key, nested]) =>
|
||||
/^(password|access_token|refresh_token|secret_value|credential_value|raw_credentials?)$/i.test(key)
|
||||
|| containsCredentialField(nested));
|
||||
}
|
||||
|
||||
test('[P1] AC-1 sends the selected OR alternative and Auth Profile, then renders API authority', async ({ page }) => {
|
||||
// Given an OpenAPI preview with OR security choices and safe workspace profile metadata
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await openSecurityPreview(page);
|
||||
|
||||
// When an administrator selects a supported alternative and its compatible profile
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
// Then the existing plan API receives only the typed profile reference and alternative index
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({
|
||||
operation_key: operationKey,
|
||||
auth_profile_id: profileId,
|
||||
security_alternative_index: 0,
|
||||
});
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
|
||||
expect(JSON.stringify(planRequests[0])).not.toContain(secretCanary);
|
||||
expect(containsCredentialField(planRequests[0])).toBe(false);
|
||||
});
|
||||
|
||||
test('[P1] AC-2 replaces a prior resolved plan with a blocker after profile revalidation fails', async ({ page }) => {
|
||||
// Given an API-confirmed resolved plan for a profile that becomes unavailable before revalidation
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
if (planRequests.length === 1) {
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page);
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
// When the API first confirms the selection and then rejects the stale profile
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Resolved', 'Разрешено'));
|
||||
await page.locator('#openapi-import-plan-back').click();
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
// Then the old resolved value is replaced by the exact API-authoritative blocker state
|
||||
await expect.poll(() => planRequests.length).toBe(2);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({ auth_profile_id: profileId, security_alternative_index: 0 });
|
||||
});
|
||||
|
||||
test('[P1] AC-3 shows safe security guidance in RU and EN without exposing error or secret canaries', async ({ page }) => {
|
||||
// Given safe profile metadata and an unsupported AND alternative in the preview
|
||||
let previewCalls = 0;
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
previewCalls += 1;
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(securityPreview()) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_security_alternative_required', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
|
||||
// When the administrator inspects both locales, the unsupported AND alternative is visible but disabled
|
||||
// Native option elements are not visually visible inside a select; the safe
|
||||
// metadata must be present and selectable.
|
||||
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).locator('option[value="' + profileId + '"]')).toBeAttached();
|
||||
await expect(page.getByLabel(localized('Security alternative', 'Вариант безопасности')).locator('option[value="2"]')).toHaveAttribute('disabled', '');
|
||||
await page.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await page.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('Blocked', 'Заблокировано'));
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await expect(page.locator('#openapi-import-retry')).toBeVisible();
|
||||
await page.locator('#openapi-import-retry').click();
|
||||
await expect.poll(() => previewCalls).toBe(2);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
// A fresh preview resets the selection, so the operation is required again,
|
||||
// never a leftover unresolved/resolved binding from the rejected plan.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(
|
||||
localized('Authentication required', 'Требуется аутентификация'),
|
||||
);
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
const exposed = await page.evaluate(() => ({
|
||||
html: document.documentElement.innerText,
|
||||
local: JSON.stringify(localStorage),
|
||||
session: JSON.stringify(sessionStorage),
|
||||
}));
|
||||
expect(JSON.stringify(exposed)).not.toContain(secretCanary);
|
||||
});
|
||||
|
||||
/* ── Mandatory matrix branches (green phase) ─────────────────────────── */
|
||||
|
||||
test('[P1] anonymous alternative submits only the OR index, never an unrequested profile', async ({ page }) => {
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
const decision = payload.decisions[0];
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({
|
||||
action: decision.action,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
|
||||
})),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
// The anonymous (empty-scheme) alternative is selectable; selecting it must
|
||||
// keep the profile unbound.
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
await alternative.selectOption('1');
|
||||
// The anonymous alternative must not offer any Auth Profile control.
|
||||
await expect(page.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
const decision = planRequests[0].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
// A confirmed anonymous alternative is no-auth, never a resolved auth binding.
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
|
||||
expect(JSON.stringify(planRequests[0])).not.toContain(profileId);
|
||||
});
|
||||
|
||||
test('[P1] changing the alternative clears the profile and invalidates a prior plan', async ({ page }) => {
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
planRequests.push(payload);
|
||||
const decision = payload.decisions[0];
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({
|
||||
action: decision.action,
|
||||
auth_profile_id: decision.auth_profile_id || null,
|
||||
security_alternative_index: decision.security_alternative_index === undefined ? null : decision.security_alternative_index,
|
||||
})),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await alternative.selectOption('0');
|
||||
await profile.selectOption(profileId);
|
||||
|
||||
// A confirmed plan exists for (alternative 0, profile).
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
// Back to editing: the selection survives, the plan does not.
|
||||
await page.locator('#openapi-import-plan-back').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
|
||||
// Switching the alternative drops the bound profile; the anonymous choice
|
||||
// hides the profile control entirely and the new plan carries only the index.
|
||||
await alternative.selectOption('1');
|
||||
await expect(profile).toHaveCount(0);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect.poll(() => planRequests.length).toBe(2);
|
||||
|
||||
const decision = planRequests[1].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, security_alternative_index: 1 });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + operationKey + '"]')).toHaveText('No authentication');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText(localized('No authentication', 'Без аутентификации'));
|
||||
});
|
||||
|
||||
test('[P1] empty compatible-profile list keeps the selection safe and the API blocker authoritative', async ({ page }) => {
|
||||
const emptyPreview = securityPreview();
|
||||
emptyPreview.security_profile_choices = [];
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
// Actual public contract: a 200 plan whose candidate is blocked with the
|
||||
// safe reason the API owns, not a synthesized top-level error code.
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_empty_profiles_atdd',
|
||||
plan_digest: 'f'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 1 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: 'protected_operation',
|
||||
state: 'blocked',
|
||||
action: 'create',
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
security_alternative_index: 0,
|
||||
reason: 'auth_profile_required',
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', emptyPreview);
|
||||
|
||||
// The empty compatible-profile list disables the profile control and shows
|
||||
// safe localized guidance instead of offering an arbitrary error payload.
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await expect(profileSelect.locator('option')).toHaveCount(1);
|
||||
await alternative.selectOption('0');
|
||||
await expect(profileSelect).toBeDisabled();
|
||||
await expect(page.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0]).toMatchObject({
|
||||
operation_key: operationKey,
|
||||
security_alternative_index: 0,
|
||||
});
|
||||
expect(planRequests[0].decisions[0]).not.toHaveProperty('auth_profile_id');
|
||||
// The API candidate is authoritative: blocked, with safe translated guidance.
|
||||
await expect(page.locator('.openapi-import-security-op-status')).toHaveText('Blocked');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
await expect(page.locator('.openapi-import-plan-reason')).toHaveText(
|
||||
'This operation requires an Auth Profile. Choose a compatible profile and create a new plan.');
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
});
|
||||
|
||||
test('[P2] security controls keep accessible names, keyboard focus and a live status', async ({ page }) => {
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await expect(alternative).toBeEditable();
|
||||
await expect(profile).toBeEditable();
|
||||
|
||||
// Keyboard-only selection: focus the native select and change it with keys,
|
||||
// never programmatically.
|
||||
await alternative.focus();
|
||||
expect(await alternative.evaluate((el) => el === document.activeElement)).toBe(true);
|
||||
await alternative.press('ArrowDown');
|
||||
await expect(alternative).toHaveValue('0');
|
||||
await profile.focus();
|
||||
expect(await profile.evaluate((el) => el === document.activeElement)).toBe(true);
|
||||
await profile.press('ArrowDown');
|
||||
await expect(profile).toHaveValue(profileId);
|
||||
|
||||
const status = page.getByTestId('openapi-security-status');
|
||||
await expect(status).toHaveAttribute('role', 'status');
|
||||
await expect(status).toHaveAttribute('aria-live', 'polite');
|
||||
const opStatus = page.locator('.openapi-import-security-op-status');
|
||||
await expect(opStatus).toHaveAttribute('role', 'status');
|
||||
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
|
||||
|
||||
await page.locator('body').press('Escape');
|
||||
await expect(page.locator('#openapi-import-modal')).toBeHidden();
|
||||
});
|
||||
|
||||
test('[P1] a delayed preview response cannot restore state after the user cancelled', async ({ page }) => {
|
||||
let releasePreview;
|
||||
const previewReleased = new Promise((resolve) => {
|
||||
releasePreview = resolve;
|
||||
});
|
||||
let previewFulfilled = false;
|
||||
await page.route('**/imports/openapi/preview', async (route) => {
|
||||
await previewReleased;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(securityPreview()),
|
||||
});
|
||||
previewFulfilled = true;
|
||||
});
|
||||
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from('openapi: 3.0.3\ninfo: { title: Security mapping, version: "1" }\npaths: {}\n'),
|
||||
});
|
||||
const previewRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && request.url().includes('/imports/openapi/preview'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await previewRequest;
|
||||
await page.locator('#openapi-import-cancel').click();
|
||||
|
||||
// Release the stale response and wait for the handler to settle instead of a
|
||||
// fixed timeout, then prove it could not restore the panel.
|
||||
releasePreview();
|
||||
await expect.poll(() => previewFulfilled).toBe(true);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
|
||||
await expect(page.locator('#openapi-import-cancel')).toBeHidden();
|
||||
});
|
||||
|
||||
/* ── Per-operation authority and selection lifecycle ────────────────── */
|
||||
|
||||
test('[P1] offers only profiles compatible with the chosen OR alternative and hides them for anonymous', async ({ page }) => {
|
||||
const key = 'get:/multi';
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'multi_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['basicAuth'], supported: true, findings: [] },
|
||||
{ schemes: [], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
|
||||
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
|
||||
]));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'multi_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
|
||||
// Profile-first selection may offer the safe union while no alternative is chosen.
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
|
||||
await expect(alternative.locator('option[value="3"]')).toHaveAttribute('disabled', '');
|
||||
|
||||
await alternative.selectOption('0');
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toHaveCount(0);
|
||||
|
||||
await alternative.selectOption('1');
|
||||
await expect(profile.locator('option[value="prof_basic"]')).toBeAttached();
|
||||
await expect(profile.locator('option[value="prof_bearer"]')).toHaveCount(0);
|
||||
|
||||
// An anonymous alternative must offer no profile control at all.
|
||||
await alternative.selectOption('2');
|
||||
await expect(row.locator('.openapi-import-security-controls select')).toHaveCount(1);
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveCount(0);
|
||||
});
|
||||
|
||||
test('[P1] reports per-operation resolved and blocked authority for a mixed plan', async ({ page }) => {
|
||||
const keyA = 'get:/alpha';
|
||||
const keyB = 'get:/beta';
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_multi_mixed_atdd',
|
||||
plan_digest: 'd'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 2, excluded: 0, actionable: 1, blocked: 1 },
|
||||
candidates: [
|
||||
{ key: keyA, name: 'alpha_operation', state: 'actionable', action: 'create', auth_profile_id: 'prof_a', security_alternative_index: 0, reason: null },
|
||||
{ key: keyB, name: 'beta_operation', state: 'blocked', action: 'create', auth_profile_id: 'prof_b', security_alternative_index: 0, reason: 'auth_profile_required' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(keyA, 'alpha_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
protectedOperation(keyB, 'beta_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
], [
|
||||
{ operation_key: keyA, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_a', name: 'A profile', kind: 'bearer' }] },
|
||||
{ operation_key: keyB, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_b', name: 'B profile', kind: 'bearer' }] },
|
||||
]));
|
||||
|
||||
// Before the plan both protected operations require an explicit binding.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
|
||||
|
||||
const rowA = page.locator('.openapi-import-operation').filter({ hasText: 'alpha_operation' });
|
||||
const rowB = page.locator('.openapi-import-operation').filter({ hasText: 'beta_operation' });
|
||||
await rowA.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await rowA.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_a');
|
||||
await rowB.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await rowB.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_b');
|
||||
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + keyA + '"]')).toHaveText('Resolved');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + keyB + '"]')).toHaveText('Blocked');
|
||||
// The summary must surface the blocked operation, not mask it behind a resolved one.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
});
|
||||
|
||||
test('[P1] editing the alternative after an authoritative blocker clears the blocked authority', async ({ page }) => {
|
||||
const key = 'get:/reset';
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary } }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'reset_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['basicAuth'], supported: true, findings: [] },
|
||||
]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: 'prof_bearer', name: 'Bearer profile', kind: 'bearer' }] },
|
||||
{ operation_key: key, alternative_index: 1, schemes: ['basicAuth'], profiles: [{ id: 'prof_basic', name: 'Basic profile', kind: 'basic' }] },
|
||||
]));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'reset_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption('prof_bearer');
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Blocked');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Blocked');
|
||||
|
||||
// Editing must void the blocked authority and clear the bound profile.
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('1');
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toHaveValue('');
|
||||
await expect(page.locator('[data-openapi-security-op-status="' + key + '"]')).toHaveText('Authentication required');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Authentication required');
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
});
|
||||
|
||||
test('[P1] binding then choosing skip removes the auth fields from the plan payload', async ({ page }) => {
|
||||
const suggestedName = 'protected_operation';
|
||||
const planRequests = [];
|
||||
await page.route('**/api/admin/workspaces/*/operations', async (route) => {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
items: [{ id: 'op_skip_target', name: suggestedName, protocol: 'rest', status: 'draft' }],
|
||||
page: 1,
|
||||
page_size: 1,
|
||||
total: 1,
|
||||
}),
|
||||
});
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_skip_atdd',
|
||||
plan_digest: 'e'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 0, blocked: 0 },
|
||||
candidates: [{
|
||||
key: operationKey,
|
||||
name: suggestedName,
|
||||
state: 'excluded',
|
||||
action: 'skip',
|
||||
target_operation_id: 'op_skip_target',
|
||||
confirmed_name: null,
|
||||
auth_profile_id: null,
|
||||
security_alternative_index: null,
|
||||
reason: 'skipped',
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: suggestedName });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
await row.locator('[data-openapi-decision-action]').selectOption('skip');
|
||||
await expect(row.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
const decision = planRequests[0].decisions[0];
|
||||
expect(decision).toMatchObject({ operation_key: operationKey, action: 'skip', target_operation_id: 'op_skip_target' });
|
||||
expect(decision).not.toHaveProperty('auth_profile_id');
|
||||
expect(decision).not.toHaveProperty('security_alternative_index');
|
||||
});
|
||||
|
||||
test('[P1] language change during a pending Apply keeps security controls disabled', async ({ page }) => {
|
||||
let releaseApply;
|
||||
const applyHeld = new Promise((resolve) => {
|
||||
releaseApply = resolve;
|
||||
});
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
await applyHeld;
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_digest: 'c'.repeat(64),
|
||||
counts: { created: 1 },
|
||||
outcomes: [{ key: operationKey, name: 'protected_operation', status: 'created' }],
|
||||
}),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The context change aborts the request; it must not update the modal.
|
||||
}
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
await alternative.selectOption('0');
|
||||
await profile.selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
await expect(alternative).toBeDisabled();
|
||||
// A language change while Apply is in flight must not re-render and re-enable
|
||||
// the security controls.
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
await expect(alternative).toBeDisabled();
|
||||
await expect(profile).toBeDisabled();
|
||||
await expect(page.locator('#openapi-import-file-select')).toBeDisabled();
|
||||
releaseApply();
|
||||
});
|
||||
|
||||
test('[P1] a rejected Apply clears a previously resolved security authority', async ({ page }) => {
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
const payload = route.request().postDataJSON();
|
||||
await route.fulfill({ contentType: 'application/json', body: JSON.stringify(actionablePlan(payload.decisions[0])) });
|
||||
});
|
||||
await page.route('**/imports/openapi/*/apply', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 422,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'import_plan_auth_unavailable', message: secretCanary }, recovery: 'repreview_required' }),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
|
||||
await page.locator('#openapi-import-plan-apply').click();
|
||||
// The rejected Apply must not retain the prior resolved authority.
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
await expect(page.locator('body')).not.toContainText(secretCanary);
|
||||
});
|
||||
|
||||
test('[P1] a delayed plan response cannot restore authority after cancel', async ({ page }) => {
|
||||
let releasePlan;
|
||||
const planHeld = new Promise((resolve) => {
|
||||
releasePlan = resolve;
|
||||
});
|
||||
let planFulfilled = false;
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await planHeld;
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
|
||||
});
|
||||
planFulfilled = true;
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
|
||||
const planRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await planRequest;
|
||||
await page.locator('#openapi-import-cancel').click();
|
||||
|
||||
releasePlan();
|
||||
await expect.poll(() => planFulfilled).toBe(true);
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeHidden();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Unresolved');
|
||||
});
|
||||
|
||||
test('[P1] a quoted or backslash operation key cannot break per-operation status', async ({ page }) => {
|
||||
const key = 'get:/quoted"path\\segment';
|
||||
const planRequests = [];
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
planRequests.push(route.request().postDataJSON());
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
plan_reference: 'plan_quoted_key_atdd',
|
||||
plan_digest: 'a'.repeat(64),
|
||||
expires_at: '2099-01-01T00:00:00Z',
|
||||
selection_mode: 'full',
|
||||
counts: { selected: 1, excluded: 0, actionable: 1, blocked: 0 },
|
||||
candidates: [{
|
||||
key,
|
||||
name: 'quoted_operation',
|
||||
state: 'actionable',
|
||||
action: 'create',
|
||||
target_operation_id: null,
|
||||
confirmed_name: null,
|
||||
auth_profile_id: profileId,
|
||||
security_alternative_index: 0,
|
||||
reason: null,
|
||||
}],
|
||||
}),
|
||||
});
|
||||
});
|
||||
await openSecurityPreview(page, 'en', previewWith([
|
||||
protectedOperation(key, 'quoted_operation', [{ schemes: ['bearerAuth'], supported: true, findings: [] }]),
|
||||
], [
|
||||
{ operation_key: key, alternative_index: 0, schemes: ['bearerAuth'], profiles: [{ id: profileId, name: 'Bearer profile', kind: 'bearer' }] },
|
||||
]));
|
||||
|
||||
// Rendering a CSS-hostile key must not throw and the preview must render.
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'quoted_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
|
||||
await expect.poll(() => planRequests.length).toBe(1);
|
||||
expect(planRequests[0].decisions[0].operation_key).toBe(key);
|
||||
// Status is matched by dataset value, never by interpolating the key into CSS.
|
||||
await expect(row.locator('.openapi-import-security-op-status')).toHaveText('Resolved');
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
});
|
||||
|
||||
test('[P1] localizes unsupported findings and empty-profile guidance in RU and EN', async ({ page }) => {
|
||||
const key = 'get:/locale';
|
||||
await openSecurityPreview(page, 'ru', previewWith([
|
||||
protectedOperation(key, 'locale_operation', [
|
||||
{ schemes: ['bearerAuth'], supported: true, findings: [] },
|
||||
{ schemes: ['oauthAuth', 'apiKeyAuth'], supported: false, findings: ['unsupported_security_and_requirement'] },
|
||||
]),
|
||||
], []));
|
||||
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'locale_operation' });
|
||||
const alternative = row.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profile = row.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
|
||||
// RU: exact unsupported finding copy and empty-profile guidance.
|
||||
await expect(row.locator('.openapi-import-security-findings')).toContainText(
|
||||
'Это security requirement невозможно выполнить со схемой, поддержанной Crank, или доступным профилем авторизации.');
|
||||
await alternative.selectOption('0');
|
||||
await expect(profile).toBeDisabled();
|
||||
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'Для выбранного варианта нет совместимых профилей авторизации. Выберите другой вариант или создайте план для повторной проверки.');
|
||||
const opStatus = row.locator('.openapi-import-security-op-status');
|
||||
await expect(opStatus).toHaveAttribute('role', 'status');
|
||||
await expect(opStatus).toHaveAttribute('aria-live', 'polite');
|
||||
|
||||
// EN: switching language invalidates an unconfirmed preview, so re-preview
|
||||
// and assert the exact translated copy in the second locale.
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await expect(row.locator('.openapi-import-security-findings')).toContainText(
|
||||
'This security requirement cannot be satisfied with a supported scheme or an available Auth Profile.');
|
||||
await expect(row.getByLabel(localized('Auth Profile', 'Профиль авторизации'))).toBeDisabled();
|
||||
await expect(row.locator('.openapi-import-security-guidance')).toHaveText(
|
||||
'No compatible Auth Profiles for the selected alternative. Choose another alternative or create a plan to revalidate.');
|
||||
});
|
||||
|
||||
test('[P1] a stale security plan cannot restore authority after a language or workspace change', async ({ page }) => {
|
||||
const releases = [];
|
||||
let planReleased = 0;
|
||||
await page.route('**/imports/openapi/*/plans', async (route) => {
|
||||
await new Promise((resolve) => releases.push(resolve));
|
||||
planReleased += 1;
|
||||
try {
|
||||
await route.fulfill({
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(actionablePlan({ action: 'create', auth_profile_id: profileId, security_alternative_index: 0 })),
|
||||
});
|
||||
} catch (_error) {
|
||||
// The context change aborts the request; it must not update the modal.
|
||||
}
|
||||
});
|
||||
await openSecurityPreview(page, 'en');
|
||||
|
||||
async function bindSelection() {
|
||||
const row = page.locator('.openapi-import-operation').filter({ hasText: 'protected_operation' });
|
||||
await row.getByLabel(localized('Security alternative', 'Вариант безопасности')).selectOption('0');
|
||||
await row.getByLabel(localized('Auth Profile', 'Профиль авторизации')).selectOption(profileId);
|
||||
}
|
||||
async function startPlan() {
|
||||
const request = page.waitForRequest((r) => r.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(r.url()));
|
||||
await page.locator('#openapi-import-create').click();
|
||||
await request;
|
||||
await expect.poll(() => releases.length).toBeGreaterThanOrEqual(1);
|
||||
}
|
||||
|
||||
// 1) Language change while a security plan is pending.
|
||||
await bindSelection();
|
||||
await startPlan();
|
||||
await page.evaluate(() => window.setLang('ru'));
|
||||
releases.shift()();
|
||||
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(1);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
|
||||
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
|
||||
// 2) Workspace change while a security plan is pending.
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
await bindSelection();
|
||||
await startPlan();
|
||||
await page.evaluate(() => {
|
||||
window.dispatchEvent(new CustomEvent('crank:workspacechange', { detail: { id: 'ws-stale-security' } }));
|
||||
});
|
||||
releases.shift()();
|
||||
await expect.poll(() => planReleased).toBeGreaterThanOrEqual(2);
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Не разрешено');
|
||||
await expect(page.locator('.openapi-import-security-controls')).toHaveCount(0);
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeHidden();
|
||||
});
|
||||
|
||||
/* ── Real API evidence ───────────────────────────────────────────────── */
|
||||
|
||||
test('[P1][api] real preview/plan round-trip resolves a typed reference (real secret + bearer profile)', async ({ page }) => {
|
||||
await login(page);
|
||||
await dismissOnboardingIfOpen(page);
|
||||
await page.evaluate(() => window.setLang('en'));
|
||||
|
||||
const workspace = await getCurrentWorkspace(page);
|
||||
const prefix = uniqueName('secmap');
|
||||
const secretValue = 'secmap-bearer-' + prefix;
|
||||
const secret = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets`,
|
||||
{ name: prefix + '_secret', kind: 'token', value: secretValue },
|
||||
);
|
||||
let profile = null;
|
||||
try {
|
||||
profile = await browserJson(
|
||||
page,
|
||||
'POST',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/auth-profiles`,
|
||||
{
|
||||
name: prefix + '_profile',
|
||||
kind: 'bearer',
|
||||
config: { bearer: { header_name: 'Authorization', secret_id: secret.id } },
|
||||
},
|
||||
);
|
||||
expect(String(profile.id)).toMatch(/^auth_/);
|
||||
|
||||
await page.getByRole('button', { name: localized('Import OpenAPI', 'Импорт OpenAPI') }).click();
|
||||
await page.locator('#openapi-import-file').setInputFiles({
|
||||
name: 'security-mapping-real.yaml',
|
||||
mimeType: 'application/yaml',
|
||||
buffer: Buffer.from([
|
||||
'openapi: 3.0.3',
|
||||
'info: { title: Security mapping real, version: "1" }',
|
||||
'servers: [{ url: "https://api.example.test" }]',
|
||||
'paths:',
|
||||
' /' + prefix + ':',
|
||||
' get:',
|
||||
' operationId: ' + prefix + '_operation',
|
||||
' security:',
|
||||
' - bearerAuth: []',
|
||||
' - {}',
|
||||
' responses:',
|
||||
' \'200\': { description: OK }',
|
||||
'components:',
|
||||
' securitySchemes:',
|
||||
' bearerAuth: { type: http, scheme: bearer }',
|
||||
].join('\n')),
|
||||
});
|
||||
await page.locator('#openapi-import-preview').click();
|
||||
await expect(page.locator('#openapi-import-preview-panel')).toBeVisible();
|
||||
|
||||
const alternative = page.getByLabel(localized('Security alternative', 'Вариант безопасности'));
|
||||
const profileSelect = page.getByLabel(localized('Auth Profile', 'Профиль авторизации'));
|
||||
const bearerOption = alternative.locator('option', { hasText: 'bearerAuth' });
|
||||
await bearerOption.waitFor({ state: 'attached' });
|
||||
const bearerIndex = await bearerOption.getAttribute('value');
|
||||
expect(bearerIndex).toMatch(/^\d+$/); // option value, not the select's current value
|
||||
await alternative.selectOption(bearerIndex);
|
||||
const realProfileOption = profileSelect.locator('option[value="' + profile.id + '"]');
|
||||
await expect(realProfileOption).toBeAttached();
|
||||
await profileSelect.selectOption(profile.id);
|
||||
|
||||
const planRequest = page.waitForRequest((request) =>
|
||||
request.method() === 'POST' && /\/imports\/openapi\/[^/]+\/plans$/.test(request.url()),
|
||||
);
|
||||
await page.locator('#openapi-import-create').click();
|
||||
const sent = await planRequest;
|
||||
const response = await sent.response();
|
||||
|
||||
// Happy path is deterministic: the created profile matches the bearer
|
||||
// scheme, so the real API must accept the typed reference.
|
||||
expect(response.status()).toBe(200);
|
||||
const payload = await sent.postDataJSON();
|
||||
const planDecision = (payload.decisions || [])[0];
|
||||
expect(planDecision).toMatchObject({ auth_profile_id: profile.id, security_alternative_index: Number(bearerIndex) });
|
||||
await expect(page.locator('#openapi-import-plan-confirmation')).toBeVisible();
|
||||
await expect(page.getByTestId('openapi-security-status')).toHaveText('Resolved');
|
||||
await expect(page.locator('body')).not.toContainText(secretValue);
|
||||
} finally {
|
||||
// Best-effort cleanup. The Secret is guarded (409) while the live profile
|
||||
// references it; the referenced Auth Profile has no delete endpoint, so we
|
||||
// only attempt to release the Secret and never widen the backend surface.
|
||||
try {
|
||||
await browserJson(
|
||||
page,
|
||||
'DELETE',
|
||||
`/api/admin/workspaces/${encodeURIComponent(workspace.id)}/secrets/${encodeURIComponent(secret.id)}`,
|
||||
[],
|
||||
[404, 409],
|
||||
);
|
||||
} catch (_error) {}
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user