Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24fb8cdc56 | ||
|
|
710dcfc7c9 | ||
|
|
c50ef814e2 | ||
|
|
30001062d4 | ||
|
|
92f0314a20 | ||
|
|
fa75f8317d | ||
|
|
90b6c509c0 | ||
|
|
102f4279dc | ||
|
|
b7e62f0468 | ||
|
|
7f8aae0d62 | ||
|
|
6899bc40d3 | ||
|
|
9f44281f9f | ||
|
|
e68e1a483c | ||
|
|
4cd1ab8c8e | ||
|
|
10b890437d |
@@ -0,0 +1,83 @@
|
||||
# IAM Impersonation API
|
||||
|
||||
> Источник: Swagger `https://auth-api-dev.ngcloud.ru/api/v1/documentation/`
|
||||
> Дата: 2026-06-16
|
||||
|
||||
## Все эндпоинты имперсонации
|
||||
|
||||
| Метод | Путь | Описание |
|
||||
|-------|------|----------|
|
||||
| `POST` | `/api/v1/impersonation/start` | Начать имперсонацию |
|
||||
| `POST` | `/api/v1/impersonation/end` | Завершить имперсонацию |
|
||||
| `POST` | `/api/v1/impersonation/extend` | Продлить сессию имперсонации |
|
||||
| `GET` | `/api/v1/impersonation/status` | Статус текущей имперсонации |
|
||||
| `GET` | `/api/v1/impersonation/history` | История своих имперсонаций |
|
||||
| `GET` | `/api/v1/impersonation/history/all` | История имперсонаций всех админов |
|
||||
|
||||
## Формат ImpersonationStartRequest
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "user",
|
||||
"entity_id": "UUID контакта (contactId из userInfo)",
|
||||
"reason": "описание причины"
|
||||
}
|
||||
```
|
||||
|
||||
- `entity_id` — **UUID таргета** (кого имперсонируем), не свой
|
||||
- `type` — всегда `"user"`
|
||||
|
||||
## curl-команды
|
||||
|
||||
### Начать имперсонацию
|
||||
|
||||
```bash
|
||||
curl --http2 -X POST \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
"https://auth-api.ngcloud.ru/api/v1/impersonation/start" \
|
||||
-d '{"type":"user","entity_id":"UUID_таргета","reason":"тест"}'
|
||||
```
|
||||
|
||||
### Статус
|
||||
|
||||
```bash
|
||||
curl --http2 \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Accept: application/json" \
|
||||
"https://auth-api.ngcloud.ru/api/v1/impersonation/status"
|
||||
```
|
||||
|
||||
### История
|
||||
|
||||
```bash
|
||||
curl --http2 \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Accept: application/json" \
|
||||
"https://auth-api.ngcloud.ru/api/v1/impersonation/history"
|
||||
```
|
||||
|
||||
### Продлить
|
||||
|
||||
```bash
|
||||
curl --http2 -X POST \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Accept: application/json" \
|
||||
"https://auth-api.ngcloud.ru/api/v1/impersonation/extend"
|
||||
```
|
||||
|
||||
### Завершить
|
||||
|
||||
```bash
|
||||
curl --http2 -X POST \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Accept: application/json" \
|
||||
"https://auth-api.ngcloud.ru/api/v1/impersonation/end"
|
||||
```
|
||||
|
||||
## Примечания
|
||||
|
||||
- Требуется роль IAM-админа или право на объект `impersonation`
|
||||
- `--http2` обязателен для обхода ddos-guard
|
||||
- Стенды: `auth-api.ngcloud.ru` (prod), `auth-api-test.ngcloud.ru` (test), `auth-api-dev.ngcloud.ru` (dev)
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ipwhitelist",
|
||||
"version": "0.5.143",
|
||||
"version": "0.5.150",
|
||||
"description": "IP WhiteList microservice for cloud provider",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
// ── IAM API ───────────────────────────────────────────────────────────────────
|
||||
// URL IAM-сервиса для получения профилей пользователя (GET /api/v1/auth/user)
|
||||
// и переключения активной компании (POST /api/v1/user/switch-profile).
|
||||
const IAM_API_URL = (process.env.IAM_API_URL || 'https://auth-api-dev.ngcloud.ru').replace(/\/$/, '');
|
||||
const IAM_API_URL = (process.env.IAM_API_URL || 'https://auth-api.ngcloud.ru').replace(/\/$/, '');
|
||||
|
||||
// ── Мок-пользователи (только dev/staging) ─────────────────────────────────────
|
||||
// В продакшене этот список не используется — вход через Keycloak.
|
||||
|
||||
+183
-1
@@ -50,6 +50,81 @@ function createV2Router() {
|
||||
res.send(debugPage(u, config.version));
|
||||
});
|
||||
|
||||
// ── GET /v2/iam_response — сырой ответ IAM ─────────────────────────
|
||||
router.get('/iam_response', async (req, res) => {
|
||||
const token = req.session && req.session.token;
|
||||
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||
try {
|
||||
const mainAuth = require('../src/auth');
|
||||
const iamData = await mainAuth.fetchIamUser(token);
|
||||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(rawPage('IAM PROD', iamData.raw));
|
||||
} catch (e) {
|
||||
res.send('<h2>Ошибка IAM</h2><pre>' + e.message + '</pre>');
|
||||
}
|
||||
});
|
||||
|
||||
// ── GET /v2/iam_response_test — IAM test стенд ──────────────────────
|
||||
router.get('/iam_response_test', async (req, res) => {
|
||||
const token = req.session && req.session.token;
|
||||
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||
try {
|
||||
const raw = await iamFetch(token, config.iamApiBase + '/auth/user');
|
||||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(rawPage('IAM TEST', raw));
|
||||
} catch (e) {
|
||||
res.send('<h2>Ошибка IAM Test</h2><pre>' + e.message + '</pre>');
|
||||
}
|
||||
});
|
||||
|
||||
// ── GET /v2/iam_response_dev — IAM dev стенд ────────────────────────
|
||||
router.get('/iam_response_dev', async (req, res) => {
|
||||
const token = req.session && req.session.token;
|
||||
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||
try {
|
||||
const raw = await iamFetch(token, config.iamApiBase + '/auth/user');
|
||||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(rawPage('IAM DEV', raw));
|
||||
} catch (e) {
|
||||
res.send('<h2>Ошибка IAM Dev</h2><pre>' + e.message + '</pre>');
|
||||
}
|
||||
});
|
||||
|
||||
// ── GET /v2/iam-gateway-test — сравнение auth-api vs lk-api-gateway ──
|
||||
router.get('/iam-gateway-test', async (req, res) => {
|
||||
const token = req.session && req.session.token;
|
||||
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||
|
||||
const base = config.iamApiBase;
|
||||
const tests = [
|
||||
{
|
||||
name: 'auth-api /auth/user',
|
||||
url: base + '/auth/user',
|
||||
},
|
||||
{
|
||||
name: 'lk-api-gateway /iam/auth/user',
|
||||
url: 'https://lk-api-gateway.ngcloud.ru/api/v1/iam/auth/user',
|
||||
},
|
||||
{
|
||||
name: 'auth-api /impersonation/status',
|
||||
url: base + '/impersonation/status',
|
||||
},
|
||||
];
|
||||
|
||||
const results = {};
|
||||
for (const t of tests) {
|
||||
try {
|
||||
const data = await iamFetch(token, t.url);
|
||||
results[t.name] = { ok: true, data };
|
||||
} catch (e) {
|
||||
results[t.name] = { ok: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||
res.send(iamComparePage(results));
|
||||
});
|
||||
|
||||
// ── /v2/app — пользовательский CRUD (только с сессией) ──────────────
|
||||
router.use('/app', enhanceImpersonation, resolveContext, createUserRouter());
|
||||
|
||||
@@ -71,11 +146,59 @@ function createV2Router() {
|
||||
router.use('/export', createExportRouter());
|
||||
|
||||
// ── GET /v2/logout — редирект на основной выход ─────────────────────
|
||||
router.get('/logout', (req, res) => res.redirect('/logout'));
|
||||
router.get('/logout', (req, res) => {
|
||||
const ua = (req.headers['user-agent'] || '').toLowerCase();
|
||||
const isBrowser = ua.includes('mozilla') || ua.includes('chrome') || ua.includes('safari');
|
||||
if (isBrowser) {
|
||||
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||
return res.send('<!DOCTYPE html><html><head><meta charset="utf-8"><title>Выход</title>'
|
||||
+ '<style>body{font-family:sans-serif;background:#111;color:#eee;padding:40px;text-align:center}'
|
||||
+ 'h2{color:#4fc3f7}p{font-size:16px;margin:20px 0}'
|
||||
+ '.btn{display:inline-block;padding:12px 24px;margin:0 10px;border-radius:6px;text-decoration:none;font-size:16px}'
|
||||
+ '.btn-yes{background:#ef5350;color:#fff}.btn-no{background:#333;color:#eee}'
|
||||
+ '</style></head><body>'
|
||||
+ '<h2>Выход из приложения</h2>'
|
||||
+ '<p>Выход завершит сессию во всех сервисах Nubes (Keycloak SSO).<br>Вы уверены?</p>'
|
||||
+ '<a href="/logout" class="btn btn-yes">Да, выйти</a>'
|
||||
+ '<a href="/v2/app" class="btn btn-no">Отмена</a>'
|
||||
+ '</body></html>');
|
||||
}
|
||||
res.redirect('/logout');
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
// ── Хелпер: HTTP-запрос к IAM ────────────────────────────────────────────────
|
||||
async function iamFetch(token, url) {
|
||||
const https = require('https');
|
||||
const u = new URL(url);
|
||||
return new Promise((resolve, reject) => {
|
||||
https.get({
|
||||
hostname: u.hostname, port: 443, path: u.pathname,
|
||||
headers: { Authorization: 'Bearer ' + token, Accept: 'application/json' },
|
||||
}, res => {
|
||||
let data = '';
|
||||
res.on('data', c => data += c);
|
||||
res.on('end', () => {
|
||||
if (res.statusCode !== 200) return reject(new Error(res.statusCode + ': ' + data.slice(0, 200)));
|
||||
try { resolve(JSON.parse(data)); } catch (e) { reject(e); }
|
||||
});
|
||||
}).on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function rawPage(title, data) {
|
||||
return '<!DOCTYPE html>\n<html><head><meta charset="utf-8"><title>' + title + '</title>'
|
||||
+ '<style>body{font-family:monospace;background:#111;color:#eee;padding:20px}'
|
||||
+ 'pre{background:#1a1a2e;padding:15px;border-radius:8px;overflow-x:auto;font-size:13px}'
|
||||
+ 'h2{color:#4fc3f7}a{color:#80cbc4}</style></head><body>'
|
||||
+ '<h2>Сырой ответ ' + title + '</h2>'
|
||||
+ '<pre>' + JSON.stringify(data, null, 2).replace(/</g, '<') + '</pre>'
|
||||
+ '<p><a href="/v2/iam">← Сессия</a> | <a href="/v2/app">CRUD</a></p>'
|
||||
+ '</body></html>';
|
||||
}
|
||||
|
||||
function debugPage(u, version) {
|
||||
return `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>V2 — IAM</title>
|
||||
@@ -92,4 +215,63 @@ function debugPage(u, version) {
|
||||
</body></html>`;
|
||||
}
|
||||
|
||||
function iamComparePage(results) {
|
||||
function fmt(data, depth) {
|
||||
if (data === null || data === undefined) return '<span style="color:#888">null</span>';
|
||||
if (typeof data === 'string') return '<span style="color:#ce93d8">"' + data.replace(/</g, '<') + '"</span>';
|
||||
if (typeof data === 'number' || typeof data === 'boolean') return '<span style="color:#81c784">' + data + '</span>';
|
||||
if (Array.isArray(data)) {
|
||||
if (data.length === 0) return '<span style="color:#888">[]</span>';
|
||||
let html = '<span style="color:#888">[</span><div style="padding-left:20px">';
|
||||
for (const item of data) html += '<div>' + fmt(item, depth + 1) + ',</div>';
|
||||
html += '</div><span style="color:#888">]</span>';
|
||||
return html;
|
||||
}
|
||||
if (typeof data === 'object') {
|
||||
let html = '<span style="color:#888">{</span><div style="padding-left:20px">';
|
||||
for (const [k, v] of Object.entries(data)) {
|
||||
html += '<div><span style="color:#82aaff">"' + k + '"</span>: ' + fmt(v, depth + 1) + '</div>';
|
||||
}
|
||||
html += '</div><span style="color:#888">}</span>';
|
||||
return html;
|
||||
}
|
||||
return String(data).replace(/</g, '<');
|
||||
}
|
||||
|
||||
let html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>IAM Impersonation</title>';
|
||||
html += '<style>body{font-family:monospace;background:#111;color:#eee;padding:20px;font-size:14px}';
|
||||
html += 'h2{color:#4fc3f7}.ok{color:#81c784}.err{color:#ef5350}';
|
||||
html += '.card{background:#1a1a2e;border-radius:8px;padding:15px;margin-bottom:15px;overflow-x:auto}';
|
||||
html += '.card-title{color:#b39ddb;font-size:18px;font-weight:bold;margin-bottom:10px}';
|
||||
html += 'a{color:#80cbc4;text-decoration:none}a:hover{text-decoration:underline}';
|
||||
html += '.nav{display:flex;gap:15px;margin-bottom:20px;flex-wrap:wrap}';
|
||||
html += '.nav a{background:#1a1a2e;padding:8px 16px;border-radius:6px;font-size:14px}';
|
||||
html += '</style></head><body>';
|
||||
html += '<h2>🧪 IAM Impersonation — GET эндпоинты</h2>';
|
||||
html += '<div class="nav">';
|
||||
html += '<a href="/v2/iam">← Сессия</a>';
|
||||
html += '<a href="/v2/app">CRUD</a>';
|
||||
html += '<a href="/v2/admin">Админка</a>';
|
||||
html += '<a href="/v2/iam_response">IAM PROD</a>';
|
||||
html += '<a href="/v2/iam_response_test">IAM TEST</a>';
|
||||
html += '<a href="/v2/iam_response_dev">IAM DEV</a>';
|
||||
html += '</div>';
|
||||
|
||||
for (const [name, r] of Object.entries(results)) {
|
||||
html += '<div class="card">';
|
||||
html += '<div class="card-title">GET /impersonation/' + name + '</div>';
|
||||
if (r.ok) {
|
||||
html += '<div style="font-family:monospace;white-space:pre-wrap;tab-size:2">';
|
||||
html += fmt(r.data, 0);
|
||||
html += '</div>';
|
||||
} else {
|
||||
html += '<div class="err">❌ ' + r.error.replace(/</g, '<') + '</div>';
|
||||
}
|
||||
html += '</div>';
|
||||
}
|
||||
|
||||
html += '</body></html>';
|
||||
return html;
|
||||
}
|
||||
|
||||
module.exports = { createV2Router };
|
||||
|
||||
@@ -4,18 +4,18 @@
|
||||
// ЭТО: все настройки в одном месте.
|
||||
// ЗАЧЕМ: всё что может поменяться между средами — здесь, не размазано по коду.
|
||||
//
|
||||
// ПРИОРИТЕТ: process.env (V2_*) → хардкод-умолчания.
|
||||
// Умолчания — для тестовой среды (VM KC на italo.kube5s.ru:8080).
|
||||
// ПРИОРИТЕТ: process.env → хардкод-умолчания.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
module.exports = {
|
||||
version: '0.5.143',
|
||||
version: '0.5.149',
|
||||
|
||||
// ── IAM ──────────────────────────────────────────────────────────────────
|
||||
iamUrl: process.env.V2_IAM_URL || 'https://auth-api.ngcloud.ru/api/v1/auth/user',
|
||||
iamApiBase: process.env.IAM_API_BASE || 'https://auth-api.ngcloud.ru/api/v1',
|
||||
|
||||
// ── OIDC (Keycloak) ──────────────────────────────────────────────────────
|
||||
kcBaseUrl: process.env.V2_KC_BASE_URL || 'https://italo.kube5s.ru:8080/realms/ipwhitelist',
|
||||
kcBaseUrl: process.env.V2_KC_BASE_URL || 'https://login.ngcloud.ru/realms/ipwhitelist',
|
||||
kcClientId: process.env.V2_KC_CLIENT_ID || 'ipwhitelist-app',
|
||||
kcClientSecret: process.env.V2_KC_CLIENT_SECRET || '',
|
||||
appUrl: process.env.V2_APP_URL || 'https://whitelist.nodejsk8s.services.ngcloud.ru',
|
||||
|
||||
Reference in New Issue
Block a user