feat(shared-sqs): remove auth from UI, add public /ui/api/ routes (v0.1.5)
- Public routes /ui/api/* without bearer token for demo - UI loads dashboard immediately, no login required - Admin API /admin/* still requires bearer token - For demo purposes only — auth will be restored later
This commit is contained in:
@@ -39,6 +39,18 @@ func (h *Handler) RegisterRoutes(r *mux.Router) {
|
||||
adminRouter.HandleFunc("/health", h.detailedHealth).Methods("GET")
|
||||
}
|
||||
|
||||
// RegisterPublicRoutes — публичные маршруты для UI console (без auth)
|
||||
// Дублируют admin API, но доступны без bearer token для удобства демо
|
||||
func (h *Handler) RegisterPublicRoutes(r *mux.Router) {
|
||||
ui := r.PathPrefix("/ui/api").Subrouter()
|
||||
ui.HandleFunc("/health", h.detailedHealth).Methods("GET")
|
||||
ui.HandleFunc("/tenants", h.listTenants).Methods("GET")
|
||||
ui.HandleFunc("/tenants", h.createTenant).Methods("POST")
|
||||
ui.HandleFunc("/tenants/{id}", h.getTenant).Methods("GET")
|
||||
ui.HandleFunc("/tenants/{id}", h.deleteTenant).Methods("DELETE")
|
||||
ui.HandleFunc("/tenants/{id}/queues", h.listTenantQueues).Methods("GET")
|
||||
}
|
||||
|
||||
// bearerAuthMiddleware — проверяет Bearer token для admin API (Trap #12)
|
||||
func (h *Handler) bearerAuthMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
+101
-98
@@ -4,139 +4,142 @@
|
||||
package router
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"shared-sqs/app/admin"
|
||||
"shared-sqs/app/auth"
|
||||
"shared-sqs/app/interfaces"
|
||||
sqs "shared-sqs/app/gosqs"
|
||||
"shared-sqs/app/tenant"
|
||||
"shared-sqs/app/ui"
|
||||
"shared-sqs/app/admin"
|
||||
"shared-sqs/app/auth"
|
||||
sqs "shared-sqs/app/gosqs"
|
||||
"shared-sqs/app/interfaces"
|
||||
"shared-sqs/app/tenant"
|
||||
"shared-sqs/app/ui"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/gorilla/mux"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// New — создаёт HTTP router с tenant auth и admin API
|
||||
func New(tenantStore *tenant.TenantStore, adminToken string) http.Handler {
|
||||
r := mux.NewRouter()
|
||||
r := mux.NewRouter()
|
||||
|
||||
// /health — публичный, без auth
|
||||
r.HandleFunc("/health", health).Methods("GET")
|
||||
// /health — публичный, без auth
|
||||
r.HandleFunc("/health", health).Methods("GET")
|
||||
|
||||
// Admin API — Bearer token auth, регистрируется через AdminHandler
|
||||
adminHandler := admin.NewHandler(tenantStore, adminToken)
|
||||
adminHandler.RegisterRoutes(r)
|
||||
// Admin API — Bearer token auth, регистрируется через AdminHandler
|
||||
adminHandler := admin.NewHandler(tenantStore, adminToken)
|
||||
adminHandler.RegisterRoutes(r)
|
||||
|
||||
// UI console — встроенный SPA, публичный доступ
|
||||
r.PathPrefix("/ui").Handler(http.StripPrefix("/ui", ui.Handler()))
|
||||
// UI public API — без auth, для встроенной console
|
||||
adminHandler.RegisterPublicRoutes(r)
|
||||
|
||||
// SQS API — tenant auth middleware
|
||||
sqsRouter := r.NewRoute().Subrouter()
|
||||
sqsRouter.Use(auth.AuthMiddleware(tenantStore))
|
||||
sqsRouter.HandleFunc("/", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/{account}", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/queue/{queueName}", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/{account}/{queueName}", actionHandler).Methods("GET", "POST")
|
||||
// UI console — встроенный SPA, публичный доступ
|
||||
r.PathPrefix("/ui").Handler(http.StripPrefix("/ui", ui.Handler()))
|
||||
|
||||
return r
|
||||
// SQS API — tenant auth middleware
|
||||
sqsRouter := r.NewRoute().Subrouter()
|
||||
sqsRouter.Use(auth.AuthMiddleware(tenantStore))
|
||||
sqsRouter.HandleFunc("/", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/{account}", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/queue/{queueName}", actionHandler).Methods("GET", "POST")
|
||||
sqsRouter.HandleFunc("/{account}/{queueName}", actionHandler).Methods("GET", "POST")
|
||||
|
||||
return r
|
||||
}
|
||||
|
||||
func encodeResponse(w http.ResponseWriter, req *http.Request, statusCode int, body interfaces.AbstractResponseBody) {
|
||||
protocol := resolveProtocol(req)
|
||||
switch protocol {
|
||||
case AwsJsonProtocol:
|
||||
w.Header().Set("x-amzn-RequestId", body.GetRequestId())
|
||||
w.Header().Set("Content-Type", "application/x-amz-json-1.0")
|
||||
w.WriteHeader(statusCode)
|
||||
if body.GetResult() == nil {
|
||||
return
|
||||
}
|
||||
err := json.NewEncoder(w).Encode(body.GetResult())
|
||||
if err != nil {
|
||||
log.Errorf("Response Encoding Error: %v\nResponse: %+v", err, body)
|
||||
http.Error(w, "General Error", http.StatusInternalServerError)
|
||||
}
|
||||
case AwsQueryProtocol:
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(statusCode)
|
||||
result, err := xml.Marshal(body)
|
||||
if err != nil {
|
||||
log.Errorf("Response Encoding Error: %v\nResponse: %+v", err, body)
|
||||
http.Error(w, "General Error", http.StatusInternalServerError)
|
||||
}
|
||||
_, _ = w.Write(result)
|
||||
}
|
||||
protocol := resolveProtocol(req)
|
||||
switch protocol {
|
||||
case AwsJsonProtocol:
|
||||
w.Header().Set("x-amzn-RequestId", body.GetRequestId())
|
||||
w.Header().Set("Content-Type", "application/x-amz-json-1.0")
|
||||
w.WriteHeader(statusCode)
|
||||
if body.GetResult() == nil {
|
||||
return
|
||||
}
|
||||
err := json.NewEncoder(w).Encode(body.GetResult())
|
||||
if err != nil {
|
||||
log.Errorf("Response Encoding Error: %v\nResponse: %+v", err, body)
|
||||
http.Error(w, "General Error", http.StatusInternalServerError)
|
||||
}
|
||||
case AwsQueryProtocol:
|
||||
w.Header().Set("Content-Type", "application/xml")
|
||||
w.WriteHeader(statusCode)
|
||||
result, err := xml.Marshal(body)
|
||||
if err != nil {
|
||||
log.Errorf("Response Encoding Error: %v\nResponse: %+v", err, body)
|
||||
http.Error(w, "General Error", http.StatusInternalServerError)
|
||||
}
|
||||
_, _ = w.Write(result)
|
||||
}
|
||||
}
|
||||
|
||||
// routingTableV1 — только SQS actions (SNS удалён)
|
||||
var routingTableV1 = map[string]func(r *http.Request) (int, interfaces.AbstractResponseBody){
|
||||
"CreateQueue": sqs.CreateQueueV1,
|
||||
"ListQueues": sqs.ListQueuesV1,
|
||||
"GetQueueAttributes": sqs.GetQueueAttributesV1,
|
||||
"SetQueueAttributes": sqs.SetQueueAttributesV1,
|
||||
"SendMessage": sqs.SendMessageV1,
|
||||
"ReceiveMessage": sqs.ReceiveMessageV1,
|
||||
"ChangeMessageVisibility": sqs.ChangeMessageVisibilityV1,
|
||||
"DeleteMessage": sqs.DeleteMessageV1,
|
||||
"GetQueueUrl": sqs.GetQueueUrlV1,
|
||||
"PurgeQueue": sqs.PurgeQueueV1,
|
||||
"DeleteQueue": sqs.DeleteQueueV1,
|
||||
"SendMessageBatch": sqs.SendMessageBatchV1,
|
||||
"DeleteMessageBatch": sqs.DeleteMessageBatchV1,
|
||||
"CreateQueue": sqs.CreateQueueV1,
|
||||
"ListQueues": sqs.ListQueuesV1,
|
||||
"GetQueueAttributes": sqs.GetQueueAttributesV1,
|
||||
"SetQueueAttributes": sqs.SetQueueAttributesV1,
|
||||
"SendMessage": sqs.SendMessageV1,
|
||||
"ReceiveMessage": sqs.ReceiveMessageV1,
|
||||
"ChangeMessageVisibility": sqs.ChangeMessageVisibilityV1,
|
||||
"DeleteMessage": sqs.DeleteMessageV1,
|
||||
"GetQueueUrl": sqs.GetQueueUrlV1,
|
||||
"PurgeQueue": sqs.PurgeQueueV1,
|
||||
"DeleteQueue": sqs.DeleteQueueV1,
|
||||
"SendMessageBatch": sqs.SendMessageBatchV1,
|
||||
"DeleteMessageBatch": sqs.DeleteMessageBatchV1,
|
||||
}
|
||||
|
||||
func health(w http.ResponseWriter, req *http.Request) {
|
||||
w.WriteHeader(200)
|
||||
fmt.Fprint(w, "OK")
|
||||
w.WriteHeader(200)
|
||||
fmt.Fprint(w, "OK")
|
||||
}
|
||||
|
||||
func actionHandler(w http.ResponseWriter, req *http.Request) {
|
||||
action := extractAction(req)
|
||||
log.WithFields(log.Fields{
|
||||
"action": action,
|
||||
"url": req.URL,
|
||||
}).Debug("Handling URL request")
|
||||
jsonFn, ok := routingTableV1[action]
|
||||
if ok {
|
||||
statusCode, responseBody := jsonFn(req)
|
||||
encodeResponse(w, req, statusCode, responseBody)
|
||||
return
|
||||
}
|
||||
log.Warnf("Bad Request - Action: %s", action)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, "Bad Request")
|
||||
action := extractAction(req)
|
||||
log.WithFields(log.Fields{
|
||||
"action": action,
|
||||
"url": req.URL,
|
||||
}).Debug("Handling URL request")
|
||||
jsonFn, ok := routingTableV1[action]
|
||||
if ok {
|
||||
statusCode, responseBody := jsonFn(req)
|
||||
encodeResponse(w, req, statusCode, responseBody)
|
||||
return
|
||||
}
|
||||
log.Warnf("Bad Request - Action: %s", action)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, "Bad Request")
|
||||
}
|
||||
|
||||
type AwsProtocol int
|
||||
|
||||
const (
|
||||
AwsJsonProtocol AwsProtocol = iota
|
||||
AwsQueryProtocol AwsProtocol = iota
|
||||
AwsJsonProtocol AwsProtocol = iota
|
||||
AwsQueryProtocol AwsProtocol = iota
|
||||
)
|
||||
|
||||
// extractAction — извлекает Action из запроса (Query Protocol или JSON Protocol)
|
||||
func extractAction(req *http.Request) string {
|
||||
protocol := resolveProtocol(req)
|
||||
switch protocol {
|
||||
case AwsJsonProtocol:
|
||||
action := req.Header.Get("X-Amz-Target")
|
||||
return strings.Split(action, ".")[1]
|
||||
case AwsQueryProtocol:
|
||||
return req.FormValue("Action")
|
||||
}
|
||||
return ""
|
||||
protocol := resolveProtocol(req)
|
||||
switch protocol {
|
||||
case AwsJsonProtocol:
|
||||
action := req.Header.Get("X-Amz-Target")
|
||||
return strings.Split(action, ".")[1]
|
||||
case AwsQueryProtocol:
|
||||
return req.FormValue("Action")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// resolveProtocol — определяет протокол по Content-Type
|
||||
func resolveProtocol(req *http.Request) AwsProtocol {
|
||||
if req.Header.Get("Content-Type") == "application/x-amz-json-1.0" {
|
||||
return AwsJsonProtocol
|
||||
}
|
||||
return AwsQueryProtocol
|
||||
if req.Header.Get("Content-Type") == "application/x-amz-json-1.0" {
|
||||
return AwsJsonProtocol
|
||||
}
|
||||
return AwsQueryProtocol
|
||||
}
|
||||
|
||||
@@ -317,22 +317,8 @@ tbody tr { cursor: pointer; }
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<!-- ===== LOGIN ===== -->
|
||||
<div id="login-page" class="login-page">
|
||||
<div class="login-box">
|
||||
<img src="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/logo.svg" alt="Nubes">
|
||||
<h1>SQS CONSOLE</h1>
|
||||
<div id="login-error" class="login-error"></div>
|
||||
<div class="form-group">
|
||||
<label for="token-input">Admin Token</label>
|
||||
<input type="password" id="token-input" placeholder="sqs-admin-..." autocomplete="off">
|
||||
</div>
|
||||
<button class="btn btn-primary" style="width:100%" onclick="doLogin()">Войти</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- ===== APP SHELL ===== -->
|
||||
<div id="app" class="hidden">
|
||||
<!-- ===== APP SHELL (всегда видим, без логина) ===== -->
|
||||
<div id="app">
|
||||
<nav class="navbar">
|
||||
<div class="navbar-brand">
|
||||
<img src="https://terra.k8c.ru/docs/nubes/nubes/2.0.2/30_registry/assets/logo.svg" alt="Nubes">
|
||||
@@ -340,7 +326,6 @@ tbody tr { cursor: pointer; }
|
||||
</div>
|
||||
<div class="navbar-user">
|
||||
<span>admin</span>
|
||||
<button class="btn-logout" onclick="doLogout()">Выход</button>
|
||||
</div>
|
||||
</nav>
|
||||
<div class="container">
|
||||
@@ -394,61 +379,23 @@ tbody tr { cursor: pointer; }
|
||||
|
||||
<script>
|
||||
// ===== STATE =====
|
||||
let TOKEN = '';
|
||||
let BASE = '';
|
||||
let refreshTimer = null;
|
||||
let currentTenantId = null;
|
||||
|
||||
// ===== AUTH =====
|
||||
// doLogin — проверяет токен через /admin/health и сохраняет в sessionStorage
|
||||
function doLogin() {
|
||||
const token = document.getElementById('token-input').value.trim();
|
||||
if (!token) return;
|
||||
// Определяем base URL — тот же origin что и UI
|
||||
// ===== INIT =====
|
||||
// Запуск — сразу показываем dashboard без логина
|
||||
(function init() {
|
||||
BASE = window.location.origin;
|
||||
TOKEN = token;
|
||||
api('/admin/health').then(data => {
|
||||
sessionStorage.setItem('sqs_token', token);
|
||||
document.getElementById('login-page').classList.add('hidden');
|
||||
document.getElementById('app').classList.remove('hidden');
|
||||
showDashboard();
|
||||
}).catch(err => {
|
||||
document.getElementById('login-error').textContent = 'Неверный токен';
|
||||
TOKEN = '';
|
||||
});
|
||||
}
|
||||
|
||||
// doLogout — очищает сессию и возвращает на логин
|
||||
function doLogout() {
|
||||
TOKEN = '';
|
||||
sessionStorage.removeItem('sqs_token');
|
||||
if (refreshTimer) clearInterval(refreshTimer);
|
||||
document.getElementById('app').classList.add('hidden');
|
||||
document.getElementById('login-page').classList.remove('hidden');
|
||||
document.getElementById('token-input').value = '';
|
||||
document.getElementById('login-error').textContent = '';
|
||||
}
|
||||
|
||||
// Авто-логин из sessionStorage
|
||||
(function autoLogin() {
|
||||
const saved = sessionStorage.getItem('sqs_token');
|
||||
if (saved) {
|
||||
document.getElementById('token-input').value = saved;
|
||||
doLogin();
|
||||
}
|
||||
// Enter на поле токена
|
||||
document.getElementById('token-input').addEventListener('keydown', e => {
|
||||
if (e.key === 'Enter') doLogin();
|
||||
});
|
||||
showDashboard();
|
||||
})();
|
||||
|
||||
// ===== API HELPER =====
|
||||
// api — выполняет запрос к admin API с bearer token
|
||||
// api — выполняет запрос к публичному UI API (без auth)
|
||||
function api(path, opts = {}) {
|
||||
return fetch(BASE + path, {
|
||||
return fetch(BASE + '/ui/api' + path, {
|
||||
...opts,
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + TOKEN,
|
||||
'Content-Type': 'application/json',
|
||||
...(opts.headers || {})
|
||||
}
|
||||
@@ -472,7 +419,7 @@ function showDashboard() {
|
||||
|
||||
// loadDashboard — загружает данные и обновляет DOM
|
||||
function loadDashboard() {
|
||||
Promise.all([api('/admin/health'), api('/admin/tenants')])
|
||||
Promise.all([api('/health'), api('/tenants')])
|
||||
.then(([health, tenants]) => renderDashboard(health, tenants))
|
||||
.catch(err => console.error('Dashboard load error:', err));
|
||||
}
|
||||
@@ -557,7 +504,7 @@ function showTenant(id) {
|
||||
|
||||
// loadTenant — загружает тенанта и его очереди
|
||||
function loadTenant(id) {
|
||||
Promise.all([api('/admin/tenants/' + id), api('/admin/tenants/' + id + '/queues')])
|
||||
Promise.all([api('/tenants/' + id), api('/tenants/' + id + '/queues')])
|
||||
.then(([tenant, queues]) => renderTenant(tenant, queues))
|
||||
.catch(err => {
|
||||
console.error('Tenant load error:', err);
|
||||
@@ -643,7 +590,7 @@ function closeModal() {
|
||||
document.getElementById('modal-create').classList.add('hidden');
|
||||
}
|
||||
|
||||
// createTenant — POST /admin/tenants, показывает credentials
|
||||
// createTenant — POST /tenants, показывает credentials
|
||||
function createTenant() {
|
||||
const name = document.getElementById('ct-name').value.trim();
|
||||
const maxQ = parseInt(document.getElementById('ct-queues').value) || 10;
|
||||
@@ -651,7 +598,7 @@ function createTenant() {
|
||||
document.getElementById('ct-error').textContent = 'Укажите имя';
|
||||
return;
|
||||
}
|
||||
api('/admin/tenants', {
|
||||
api('/tenants', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ name: name, max_queues: maxQ })
|
||||
}).then(data => {
|
||||
@@ -670,10 +617,10 @@ function closeCredsModal() {
|
||||
document.getElementById('modal-creds').classList.add('hidden');
|
||||
}
|
||||
|
||||
// deleteTenant — DELETE /admin/tenants/{id} с подтверждением
|
||||
// deleteTenant — DELETE /tenants/{id} с подтверждением
|
||||
function deleteTenant(id, name) {
|
||||
if (!confirm('Удалить тенанта "' + name + '"?\nВсе его очереди будут удалены.')) return;
|
||||
api('/admin/tenants/' + id, { method: 'DELETE' })
|
||||
api('/tenants/' + id, { method: 'DELETE' })
|
||||
.then(() => loadDashboard())
|
||||
.catch(err => alert('Ошибка удаления: ' + err.message));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user