Files
Prism/internal/api/handlers_apikeys_test.go
T
renjue 2780eaf30c
CI / test (push) Successful in 1m55s
CI / docker (push) Failing after 24s
feat: Prism HTTP/SOCKS5 代理网关及管理台
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-23 15:11:50 +08:00

67 lines
1.7 KiB
Go

package api
import (
"context"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/gin-gonic/gin"
"github.com/prism/proxy/internal/auth"
"github.com/prism/proxy/internal/service"
"github.com/prism/proxy/internal/store"
)
func TestAuthorizeRequestWithAPIKey(t *testing.T) {
gin.SetMode(gin.TestMode)
dir := t.TempDir()
st, err := store.Open(filepath.Join(dir, "test.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { st.Close() })
ctx := context.Background()
if err := st.SetSettings(ctx, map[string]string{
"auth_enabled": "true",
"admin_password": "secret",
}); err != nil {
t.Fatal(err)
}
raw, err := auth.GenerateAPIKey()
if err != nil {
t.Fatal(err)
}
if _, err := st.CreateAPIKey(ctx, "test", auth.APIKeyDisplayPrefix(raw), auth.HashAPIKey(raw)); err != nil {
t.Fatal(err)
}
s := &Server{app: &service.App{Store: st}}
settings, _ := st.GetSettings(ctx)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
c.Request.Header.Set("X-API-Key", raw)
if !s.authorizeRequest(c, settings) {
t.Fatal("expected api key to authorize")
}
w2 := httptest.NewRecorder()
c2, _ := gin.CreateTestContext(w2)
c2.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
c2.Request.Header.Set("Authorization", "Bearer "+raw)
if !s.authorizeRequest(c2, settings) {
t.Fatal("expected bearer api key to authorize")
}
w3 := httptest.NewRecorder()
c3, _ := gin.CreateTestContext(w3)
c3.Request = httptest.NewRequest("GET", "/api/v1/dashboard", nil)
c3.Request.Header.Set("Authorization", "Bearer prism_invalid")
if s.authorizeRequest(c3, settings) {
t.Fatal("expected invalid key to fail")
}
}