63 lines
2.1 KiB
Go
63 lines
2.1 KiB
Go
package sessionapi
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/itworx/pulse/internal/auth"
|
|
)
|
|
|
|
func TestHandlerReturnsCurrentCapabilities(t *testing.T) {
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/session", nil)
|
|
request = request.WithContext(auth.WithPrincipal(context.Background(), auth.Principal{Subject: "operator-42", Role: auth.RoleEditor}))
|
|
response := httptest.NewRecorder()
|
|
|
|
Handler{Environment: "development"}.ServeHTTP(response, request)
|
|
|
|
if response.Code != http.StatusOK {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
|
|
}
|
|
if got := response.Header().Get("Cache-Control"); got != "private, no-store" {
|
|
t.Fatalf("Cache-Control = %q", got)
|
|
}
|
|
var payload Response
|
|
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if payload.Subject != "operator-42" || payload.Role != auth.RoleEditor {
|
|
t.Fatalf("unexpected identity: %#v", payload)
|
|
}
|
|
if payload.Environment != "development" {
|
|
t.Fatalf("environment = %q, want development", payload.Environment)
|
|
}
|
|
if !payload.Permissions.View || !payload.Permissions.Operate || !payload.Permissions.Edit || payload.Permissions.Admin {
|
|
t.Fatalf("unexpected permissions: %#v", payload.Permissions)
|
|
}
|
|
}
|
|
|
|
func TestHandlerFailsClosedWithoutPrincipal(t *testing.T) {
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/session", nil)
|
|
response := httptest.NewRecorder()
|
|
|
|
Handler{}.ServeHTTP(response, request)
|
|
|
|
if response.Code != http.StatusUnauthorized {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusUnauthorized)
|
|
}
|
|
}
|
|
|
|
func TestHandlerRejectsMutationMethods(t *testing.T) {
|
|
request := httptest.NewRequest(http.MethodPost, "/api/v1/session", nil)
|
|
request = request.WithContext(auth.WithPrincipal(context.Background(), auth.Principal{Subject: "admin-1", Role: auth.RoleAdministrator}))
|
|
response := httptest.NewRecorder()
|
|
|
|
Handler{}.ServeHTTP(response, request)
|
|
|
|
if response.Code != http.StatusMethodNotAllowed {
|
|
t.Fatalf("status = %d, want %d", response.Code, http.StatusMethodNotAllowed)
|
|
}
|
|
}
|