Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a1708e682 | ||
|
|
579bf97e17 |
+91
-7
@@ -40,6 +40,12 @@ var (
|
||||
|
||||
const defaultSATokenPath = "/var/run/secrets/kubernetes.io/serviceaccount/token"
|
||||
|
||||
var deckAPIs = map[string]string{
|
||||
"prod": "https://deck-api.ngcloud.ru/api/v1",
|
||||
"dev": "https://deck-api-dev.ngcloud.ru/api/v1",
|
||||
"test": "https://deck-api-test.ngcloud.ru/api/v1",
|
||||
}
|
||||
|
||||
type server struct {
|
||||
dyn dynamic.Interface
|
||||
ns string
|
||||
@@ -54,6 +60,7 @@ type server struct {
|
||||
tokenMu sync.Mutex
|
||||
cachedJWT string
|
||||
tokenExpAt time.Time
|
||||
tokenCache sync.Map
|
||||
}
|
||||
|
||||
type createFunctionRequest struct {
|
||||
@@ -138,12 +145,32 @@ func main() {
|
||||
mux.HandleFunc("/api/httptriggers", s.handleList(httpTrigGVR))
|
||||
mux.HandleFunc("/api/timetriggers", s.handleList(timeTrigGVR))
|
||||
|
||||
mux.HandleFunc("/console/api/environments", s.handleList(environmentGVR))
|
||||
mux.HandleFunc("/console/api/packages", s.handleList(packageGVR))
|
||||
mux.HandleFunc("/console/api/functions", s.handleFunctionsRoot)
|
||||
mux.HandleFunc("/console/api/functions/", s.handleFunctionsAction)
|
||||
mux.HandleFunc("/console/api/httptriggers", s.handleList(httpTrigGVR))
|
||||
mux.HandleFunc("/console/api/timetriggers", s.handleList(timeTrigGVR))
|
||||
auth := func(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
token := strings.TrimSpace(r.Header.Get("X-Auth-Token"))
|
||||
env := strings.TrimSpace(strings.ToLower(r.Header.Get("X-Auth-Env")))
|
||||
if _, ok := deckAPIs[env]; !ok {
|
||||
env = "test"
|
||||
}
|
||||
if token == "" {
|
||||
writeJSONError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
if err := s.validateDeckToken(token, env); err != nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, "unauthorized")
|
||||
return
|
||||
}
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
mux.HandleFunc("/console/api/auth", s.handleAuth)
|
||||
mux.HandleFunc("/console/api/environments", auth(s.handleList(environmentGVR)))
|
||||
mux.HandleFunc("/console/api/packages", auth(s.handleList(packageGVR)))
|
||||
mux.HandleFunc("/console/api/functions", auth(s.handleFunctionsRoot))
|
||||
mux.HandleFunc("/console/api/functions/", auth(s.handleFunctionsAction))
|
||||
mux.HandleFunc("/console/api/httptriggers", auth(s.handleList(httpTrigGVR)))
|
||||
mux.HandleFunc("/console/api/timetriggers", auth(s.handleList(timeTrigGVR)))
|
||||
|
||||
httpServer := &http.Server{
|
||||
Addr: ":" + port,
|
||||
@@ -714,6 +741,63 @@ func (s *server) getRouterToken() string {
|
||||
return s.cachedJWT
|
||||
}
|
||||
|
||||
func (s *server) validateDeckToken(token, env string) error {
|
||||
cacheKey := env + ":" + token
|
||||
if v, ok := s.tokenCache.Load(cacheKey); ok {
|
||||
if time.Now().Before(v.(time.Time)) {
|
||||
return nil
|
||||
}
|
||||
s.tokenCache.Delete(cacheKey)
|
||||
}
|
||||
apiBase, ok := deckAPIs[env]
|
||||
if !ok {
|
||||
return fmt.Errorf("unknown env: %s", env)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, apiBase+"/index.cfm/instances", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := s.http.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
_, _ = io.ReadAll(resp.Body)
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
return fmt.Errorf("invalid token")
|
||||
}
|
||||
s.tokenCache.Store(cacheKey, time.Now().Add(5*time.Minute))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *server) handleAuth(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPost {
|
||||
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Token string `json:"token"`
|
||||
Env string `json:"env"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil || strings.TrimSpace(body.Token) == "" {
|
||||
writeJSONError(w, http.StatusBadRequest, "token required")
|
||||
return
|
||||
}
|
||||
env := strings.TrimSpace(strings.ToLower(body.Env))
|
||||
if _, ok := deckAPIs[env]; !ok {
|
||||
env = "test"
|
||||
}
|
||||
if err := s.validateDeckToken(body.Token, env); err != nil {
|
||||
writeJSONError(w, http.StatusUnauthorized, "invalid token")
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"ok": true, "env": env})
|
||||
}
|
||||
|
||||
func (s *server) handleDeleteFunction(w http.ResponseWriter, r *http.Request, name string) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
@@ -817,7 +901,7 @@ func withCORS(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
w.Header().Set("Access-Control-Allow-Methods", "GET,POST,PUT,PATCH,DELETE,OPTIONS")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Auth-Token, X-Auth-Env")
|
||||
if r.Method == http.MethodOptions {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
|
||||
+92
-3
@@ -287,6 +287,31 @@
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="login-overlay" style="display:none; position:fixed; inset:0; background:rgba(0,0,0,.85); z-index:999; align-items:center; justify-content:center; padding:16px;">
|
||||
<div class="panel" style="width:min(440px,100%);">
|
||||
<div class="brand" style="margin-bottom:24px;">
|
||||
<div class="brand-mark">N</div>
|
||||
<div class="brand-text">
|
||||
<div class="nubes">NUBES</div>
|
||||
<div class="product">FISSION CONSOLE</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="row" style="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||
<label style="font-size:12px; color:#999;">Стенд</label>
|
||||
<select id="l-env" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px;">
|
||||
<option value="dev">Dev</option>
|
||||
<option value="test" selected>Test</option>
|
||||
<option value="prod">Prod</option>
|
||||
</select>
|
||||
</div>
|
||||
<div class="row" style="flex-direction:column; gap:6px; margin-bottom:12px;">
|
||||
<label style="font-size:12px; color:#999;">Токен</label>
|
||||
<textarea id="l-token" rows="5" style="background:var(--bg-base); border:1px solid var(--border); color:var(--fg); padding:8px 10px; border-radius:6px; font-family:monospace; font-size:12px; resize:vertical; width:100%; box-sizing:border-box;" placeholder="Введите токен..."></textarea>
|
||||
</div>
|
||||
<div id="l-error" style="display:none; color:#ff6b6b; font-size:13px; margin-bottom:10px;"></div>
|
||||
<button id="l-btn" class="btn" style="width:100%;" onclick="doLogin()">Войти</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="navbar">
|
||||
<div class="brand">
|
||||
<div class="brand-mark">N</div>
|
||||
@@ -298,6 +323,7 @@
|
||||
<div class="row" style="margin:0;">
|
||||
<button class="btn ghost" onclick="reloadAll()">Refresh</button>
|
||||
<button class="btn" onclick="openCreate()">+ Создать функцию</button>
|
||||
<button class="btn ghost" onclick="doLogout()" style="margin-left:8px;">Выход</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -430,8 +456,16 @@
|
||||
currentInvoke: null
|
||||
};
|
||||
|
||||
function authHeaders() {
|
||||
return {
|
||||
'X-Auth-Token': localStorage.getItem('auth_token') || '',
|
||||
'X-Auth-Env': localStorage.getItem('auth_env') || 'test'
|
||||
};
|
||||
}
|
||||
|
||||
async function getJSON(url) {
|
||||
const r = await fetch(url);
|
||||
const r = await fetch(url, {headers: authHeaders()});
|
||||
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||
if (!r.ok) {
|
||||
let msg = '';
|
||||
try {
|
||||
@@ -448,9 +482,10 @@
|
||||
async function requestJSON(url, method, body) {
|
||||
const r = await fetch(url, {
|
||||
method: method,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: Object.assign({'Content-Type': 'application/json'}, authHeaders()),
|
||||
body: body ? JSON.stringify(body) : undefined
|
||||
});
|
||||
if (r.status === 401) { doLogout(); throw new Error('Сессия истекла'); }
|
||||
let data = {};
|
||||
try { data = await r.json(); } catch (_) {}
|
||||
if (!r.ok) {
|
||||
@@ -712,7 +747,61 @@
|
||||
}
|
||||
}
|
||||
|
||||
reloadAll();
|
||||
function showLoginOverlay() {
|
||||
document.getElementById('login-overlay').style.display = 'flex';
|
||||
}
|
||||
|
||||
function hideLoginOverlay() {
|
||||
document.getElementById('login-overlay').style.display = 'none';
|
||||
}
|
||||
|
||||
async function doLogin() {
|
||||
var btn = document.getElementById('l-btn');
|
||||
var errEl = document.getElementById('l-error');
|
||||
var token = (document.getElementById('l-token').value || '').trim();
|
||||
var env = document.getElementById('l-env').value;
|
||||
if (!token) { errEl.textContent = 'Введите токен'; errEl.style.display = 'block'; return; }
|
||||
btn.disabled = true;
|
||||
errEl.style.display = 'none';
|
||||
try {
|
||||
const res = await fetch(API_BASE + '/auth', {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({token: token, env: env})
|
||||
});
|
||||
if (!res.ok) {
|
||||
const d = await res.json().catch(function() { return {}; });
|
||||
throw new Error(d.error || 'Ошибка входа');
|
||||
}
|
||||
localStorage.setItem('auth_token', token);
|
||||
localStorage.setItem('auth_env', env);
|
||||
hideLoginOverlay();
|
||||
reloadAll();
|
||||
} catch(e) {
|
||||
errEl.textContent = e.message;
|
||||
errEl.style.display = 'block';
|
||||
} finally {
|
||||
btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function doLogout() {
|
||||
localStorage.removeItem('auth_token');
|
||||
localStorage.removeItem('auth_env');
|
||||
try { document.getElementById('l-token').value = ''; } catch(_) {}
|
||||
showLoginOverlay();
|
||||
}
|
||||
|
||||
function checkAuth() {
|
||||
if (!localStorage.getItem('auth_token')) {
|
||||
showLoginOverlay();
|
||||
return;
|
||||
}
|
||||
hideLoginOverlay();
|
||||
reloadAll();
|
||||
}
|
||||
|
||||
checkAuth();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Тест auth v0.5.0 — 2026-04-19
|
||||
|
||||
## Что проверено
|
||||
|
||||
| Тест | Ожидание | Результат |
|
||||
|------|----------|-----------|
|
||||
| GET /console/ | 200 | ✅ 200 |
|
||||
| POST /console/api/auth {token: "badtoken"} | {"error":"invalid token"} | ✅ |
|
||||
| GET /console/api/functions без токена | 401 | ✅ 401 |
|
||||
| Логин с реальным YC IAM токеном | {"ok":true,"env":"test"} | ⏳ не проверено — нет токена |
|
||||
|
||||
## Что не проверено
|
||||
|
||||
- Полный flow: логин → появление UI → CRUD функций
|
||||
- Logout → блокировка доступа
|
||||
- Проверка `env` (dev/prod)
|
||||
|
||||
## Итог
|
||||
|
||||
Защита работает: без токена — 401, плохой токен — ошибка. Полный flow нужно проверить вручную в браузере после получения YC IAM токена.
|
||||
Reference in New Issue
Block a user