Files
ssw-mvp/scard/code/server/api/handler.go
T
admin 3247e9fd15 init: ssw-mvp initial commit
- boot/ (Java/Maven, JNPF 7.0) — 移除旧的 boot/.git,源码直接纳入仓库
- web/ (Vue 3 + Vite + Ant Design Vue, pnpm)
- docs/, scard/, nax/
- refs/INDEX.md + refs/国标/(其余 refs/* 开源子仓库不纳入)
- 已忽略: connector_data/, jweb/, log/, web/{dist,node_modules,.pnpm}, boot/*/target/, .DS_Store, .idea, .vscode
2026-08-05 18:29:12 +08:00

606 lines
18 KiB
Go

package api
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"path"
"strconv"
"strings"
"time"
"security-connector/common/crypto"
"security-connector/common/proto"
"security-connector/common/types"
"security-connector/server/attest"
"security-connector/server/audit"
"security-connector/server/auth"
"security-connector/server/easytier"
"security-connector/server/keyring"
"security-connector/server/policy"
)
// Server is the REST API server
type Server struct {
mux *http.ServeMux
auth *auth.DeviceAuthenticator
keyRing *keyring.KeyRing
policyEngine *policy.PolicyEngine
auditLog *audit.Logger
easytier *easytier.Coordinator
}
// NewServer creates a new API server
func NewServer(a *auth.DeviceAuthenticator, kr *keyring.KeyRing, pe *policy.PolicyEngine, al *audit.Logger, et *easytier.Coordinator) *Server {
s := &Server{
mux: http.NewServeMux(),
auth: a,
keyRing: kr,
policyEngine: pe,
auditLog: al,
easytier: et,
}
s.setupRoutes()
return s
}
// setupRoutes configures the API routes
func (s *Server) setupRoutes() {
// Device registration and auth
s.mux.HandleFunc("/api/v1/device/enroll-nonce", s.handleEnrollNonce)
s.mux.HandleFunc("/api/v1/device/register", s.handleDeviceRegister)
s.mux.HandleFunc("/api/v1/device/challenge", s.handleChallenge)
s.mux.HandleFunc("/api/v1/device/auth", s.handleAuth)
// status is a *prefix* route so /api/v1/device/status and
// /api/v1/device/status/{id} both work. handleDeviceStatus decides.
s.mux.HandleFunc("/api/v1/device/status/", s.handleDeviceStatus)
s.mux.HandleFunc("/api/v1/device/status", s.handleDeviceStatus)
// Operator / management plane (consumed by SSWFlow TDS)
s.mux.HandleFunc("/api/v1/device/revoke", s.handleDeviceRevoke)
s.mux.HandleFunc("/api/v1/audit/query", s.handleAuditQuery)
s.mux.HandleFunc("/api/v1/audit/stats", s.handleAuditStats)
s.mux.HandleFunc("/api/v1/attestation/policy", s.handleAttestationPolicy)
s.mux.HandleFunc("/api/v1/health/plane", s.handlePlaneHealth)
// Key management
s.mux.HandleFunc("/api/v1/key/incremental-update", s.handleKeyIncrementalUpdate)
// EasyTier
s.mux.HandleFunc("/api/v1/easytier/join", s.handleEasytierJoin)
// K3s
s.mux.HandleFunc("/api/v1/k3s/join", s.handleK3sJoin)
// Health check
s.mux.HandleFunc("/health", s.handleHealth)
}
// handleEnrollNonce issues the attestation challenge a device must quote over
// before it is allowed to register.
func (s *Server) handleEnrollNonce(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeEnrollNonceRequest, proto.ErrInternalError, "Failed to read request body")
return
}
var req proto.EnrollNonceRequest
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeEnrollNonceRequest, proto.ErrInvalidRequest, "Invalid JSON")
return
}
deviceID := req.DeviceID
if deviceID == "" {
deviceID = req.APIRequest.DeviceID
}
if deviceID == "" {
s.writeError(w, proto.TypeEnrollNonceRequest, proto.ErrInvalidRequest, "device_id required")
return
}
resp, err := s.auth.IssueEnrollmentNonce(deviceID)
if err != nil {
s.writeError(w, proto.TypeEnrollNonceRequest, proto.ErrInternalError, err.Error())
return
}
s.writeJSON(w, resp)
}
// handleDeviceRegister handles device registration
func (s *Server) handleDeviceRegister(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeRegisterRequest, proto.ErrInternalError, "Failed to read request body")
return
}
var req proto.RegisterRequest
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeRegisterRequest, proto.ErrInvalidRequest, "Invalid JSON")
return
}
resp, err := s.auth.RegisterDevice(&req)
if err != nil {
// Attestation rejections are their own error class: they mean the
// device could not prove its boot state, not that the server broke.
code := proto.ErrInternalError
reason := "registration_failed"
if isAttestationFailure(err) {
code = proto.ErrAttestationFailed
reason = "attestation_failed"
}
s.auditLog.LogDeviceRegister(req.DeviceID, "failure", reason, s.getClientIP(r))
fmt.Printf("[REGISTER] rejected device=%s reason=%s err=%v\n", req.DeviceID, reason, err)
s.writeError(w, proto.TypeRegisterRequest, code, err.Error())
return
}
s.auditLog.LogDeviceRegister(req.DeviceID, "success", "", s.getClientIP(r))
fmt.Printf("[REGISTER] admitted device=%s attestation=%s pcr_digest=%s\n",
req.DeviceID, resp.AttestationStatus, resp.PCRDigest)
s.writeJSON(w, resp)
}
// isAttestationFailure reports whether err came from the attestation verifier.
func isAttestationFailure(err error) bool {
for _, target := range []error{
attest.ErrNonceMissing, attest.ErrNonceUnknown, attest.ErrNonceExpired,
attest.ErrNonceReplay, attest.ErrNonceDeviceMismatch, attest.ErrNonceTooShort,
attest.ErrQuoteMalformed, attest.ErrQuoteSignature, attest.ErrPCRMaskInsufficient,
attest.ErrMeasurementMismatch, attest.ErrFirmwareNotAllowed, attest.ErrUnknownDevice,
} {
if errors.Is(err, target) {
return true
}
}
return false
}
// handleChallenge handles challenge request
func (s *Server) handleChallenge(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeChallengeRequest, proto.ErrInternalError, "Failed to read request body")
return
}
var baseReq proto.APIRequest
if err := json.Unmarshal(body, &baseReq); err != nil {
s.writeError(w, proto.TypeChallengeRequest, proto.ErrInvalidRequest, "Invalid JSON")
return
}
deviceID := baseReq.DeviceID
if deviceID == "" {
// Extract from URL path
deviceID = strings.TrimPrefix(r.URL.Path, "/api/v1/device/challenge/")
}
resp, err := s.auth.CreateChallenge(deviceID)
if err != nil {
s.writeError(w, proto.TypeChallengeRequest, proto.ErrDeviceNotFound, err.Error())
return
}
s.writeJSON(w, resp)
}
// handleAuth handles challenge response authentication
func (s *Server) handleAuth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeAuthRequest, proto.ErrInternalError, "Failed to read request body")
return
}
var resp proto.ChallengeResponse
if err := json.Unmarshal(body, &resp); err != nil {
s.writeError(w, proto.TypeAuthRequest, proto.ErrInvalidRequest, "Invalid JSON")
return
}
authResp, err := s.auth.VerifyChallengeResponse(resp.DeviceID, &resp)
if err != nil {
s.auditLog.LogDeviceAuth(resp.DeviceID, "failure", "auth_failed", s.getClientIP(r))
s.writeError(w, proto.TypeAuthRequest, proto.ErrAuthFailed, err.Error())
return
}
s.auditLog.LogDeviceAuth(resp.DeviceID, "success", "", s.getClientIP(r))
s.writeJSON(w, authResp)
}
// handleDeviceStatus returns device status. GET /api/v1/device/status lists
// all devices, GET /api/v1/device/status/{id} returns one device plus its
// attestation footprint.
func (s *Server) handleDeviceStatus(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
trimmed := strings.TrimPrefix(r.URL.Path, "/api/v1/device/status")
trimmed = strings.Trim(trimmed, "/")
if trimmed == "" {
devices := s.auth.ListDevices()
s.writeJSON(w, devices)
return
}
status, err := s.auth.GetDeviceStatus(trimmed)
if err != nil {
s.writeError(w, proto.TypeDeviceStatus, proto.ErrDeviceNotFound, err.Error())
return
}
s.writeJSON(w, status)
}
// handleDeviceRevoke revokes a device. POST body is JSON
// {"device_id":"...", "operator":"...", "reason":"..."}; operator/reason are
// optional but recommended for the audit trail.
func (s *Server) handleDeviceRevoke(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeRevokeRequest, proto.ErrInternalError, "Failed to read request body")
return
}
var req struct {
DeviceID string `json:"device_id"`
Operator string `json:"operator"`
Reason string `json:"reason"`
}
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeRevokeRequest, proto.ErrInvalidRequest, "Invalid JSON")
return
}
if req.DeviceID == "" {
s.writeError(w, proto.TypeRevokeRequest, proto.ErrInvalidRequest, "device_id required")
return
}
device, err := s.auth.RevokeDevice(req.DeviceID, req.Operator, req.Reason)
if err != nil {
s.writeError(w, proto.TypeRevokeRequest, proto.ErrDeviceNotFound, err.Error())
return
}
s.writeJSON(w, map[string]interface{}{
"success": true,
"device": device,
"revoked": device.Status,
"operator": req.Operator,
"reason": req.Reason,
})
}
// handleAuditQuery exposes the audit log to the management plane.
//
// GET /api/v1/audit/query?device_id=...&event_type=...&result=...
// &since=RFC3339&until=RFC3339&limit=200
//
// Limit defaults to audit.DefaultQueryLimit (200) and is clamped to
// audit.MaxQueryLimit (2000) regardless of what the caller asks for.
func (s *Server) handleAuditQuery(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
q := r.URL.Query()
filter := audit.QueryFilter{
DeviceID: q.Get("device_id"),
EventType: types.AuditEventType(q.Get("event_type")),
Result: q.Get("result"),
}
if s := q.Get("since"); s != "" {
if t, err := parseFlexibleTime(s); err == nil {
filter.Since = t
}
}
if u := q.Get("until"); u != "" {
if t, err := parseFlexibleTime(u); err == nil {
filter.Until = t
}
}
if l := q.Get("limit"); l != "" {
if n, err := strconv.Atoi(l); err == nil {
filter.Limit = n
}
}
res, err := s.auditLog.Query(filter)
if err != nil {
http.Error(w, "query failed: "+err.Error(), http.StatusInternalServerError)
return
}
s.writeJSON(w, res)
}
// handleAuditStats returns aggregate counters for the management dashboard.
func (s *Server) handleAuditStats(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
stats, err := s.auditLog.Stats()
if err != nil {
http.Error(w, "stats failed: "+err.Error(), http.StatusInternalServerError)
return
}
s.writeJSON(w, stats)
}
// handleAttestationPolicy exposes the active attestation configuration
// (mode, PCR masks, TOFU policy, golden measurements per device) so the
// management plane can render the same view the server is enforcing.
func (s *Server) handleAttestationPolicy(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
verifier := s.auth.Attestor()
if verifier == nil {
http.Error(w, "attestation not configured", http.StatusServiceUnavailable)
return
}
s.writeJSON(w, verifier.PolicySnapshot())
}
// handlePlaneHealth is the liveness/readiness probe consumed by the
// management plane (SSWFlow TDS SecurityPlaneClient).
func (s *Server) handlePlaneHealth(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodGet {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
resp := map[string]interface{}{
"status": "ok",
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
"devices": len(s.auth.ListDevices()),
"audit_dir": s.auditLog.LogDir(),
}
if v := s.auth.Attestor(); v != nil {
resp["attestation"] = v.PolicySnapshot()
}
s.writeJSON(w, resp)
}
// parseFlexibleTime accepts either an RFC3339 timestamp (full) or a date
// (YYYY-MM-DD). Anything else is rejected so a typo doesn't silently widen
// the time window to "always".
func parseFlexibleTime(s string) (time.Time, error) {
if t, err := time.Parse(time.RFC3339, s); err == nil {
return t, nil
}
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return t, nil
}
if t, err := time.Parse("2006-01-02", s); err == nil {
return t, nil
}
return time.Time{}, fmt.Errorf("unrecognised time format: %s", s)
}
// handleKeyIncrementalUpdate handles incremental key updates
func (s *Server) handleKeyIncrementalUpdate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeKeyIncremental, proto.ErrInternalError, "Failed to read request body")
return
}
var req proto.KeyIncrementalUpdate
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeKeyIncremental, proto.ErrInvalidRequest, "Invalid JSON")
return
}
if err := s.keyRing.IncrementalKeyUpdate(&req); err != nil {
s.auditLog.LogKeyUpdate(req.DeviceID, req.KeyID, req.KeyVersion, "failure", "key_update_failed")
s.writeError(w, proto.TypeKeyIncremental, proto.ErrKeyNotFound, err.Error())
return
}
s.auditLog.LogKeyUpdate(req.DeviceID, req.KeyID, req.KeyVersion, "success", "")
s.writeJSON(w, proto.NewSuccessResponse(proto.TypeKeyIncremental))
}
// handleEasytierJoin handles EasyTier join request
func (s *Server) handleEasytierJoin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeEasytierJoin, proto.ErrInternalError, "Failed to read request body")
return
}
var req proto.EasyTierJoinRequest
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeEasytierJoin, proto.ErrInvalidRequest, "Invalid JSON")
return
}
// Evaluate policy
allowed, err := s.policyEngine.Evaluate(req.DeviceID, "easytier_join", req.NetworkID, nil)
if err != nil || !allowed {
s.auditLog.LogPolicyDeny(req.DeviceID, req.DeviceID, "easytier_join", req.NetworkID)
s.writeError(w, proto.TypeEasytierJoin, proto.ErrPolicyDenied, "Policy denied")
return
}
resp, err := s.easytier.AuthorizeDevice(req.NetworkID, req.DeviceID)
if err != nil {
s.auditLog.LogEasytierJoin(req.DeviceID, req.NodeID, req.NetworkID, "failure", "easytier_error")
s.writeError(w, proto.TypeEasytierJoin, proto.ErrEasytierError, err.Error())
return
}
s.auditLog.LogEasytierJoin(req.DeviceID, req.NodeID, req.NetworkID, "success", "")
s.writeJSON(w, resp)
}
// handleK3sJoin handles k3s join request
func (s *Server) handleK3sJoin(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
s.writeError(w, proto.TypeK3sJoin, proto.ErrInternalError, "Failed to read request body")
return
}
var req proto.K3sJoinRequest
if err := json.Unmarshal(body, &req); err != nil {
s.writeError(w, proto.TypeK3sJoin, proto.ErrInvalidRequest, "Invalid JSON")
return
}
// Evaluate policy
allowed, err := s.policyEngine.Evaluate(req.DeviceID, "k3s_join", req.ClusterID, nil)
if err != nil || !allowed {
s.auditLog.LogPolicyDeny(req.DeviceID, req.DeviceID, "k3s_join", req.ClusterID)
s.writeError(w, proto.TypeK3sJoin, proto.ErrPolicyDenied, "Policy denied")
return
}
// Generate node credentials (simplified for Phase 1)
resp := &proto.K3sJoinResponse{
APIResponse: *proto.NewSuccessResponse(proto.TypeK3sJoin),
NodeToken: generateToken(),
NodePassword: generatePassword(),
ServerURL: fmt.Sprintf("https://k3s-server:6443"),
CACert: "", // Would be real CA cert in production
}
s.auditLog.LogK3sJoin(req.DeviceID, req.NodeName, req.ClusterID, "success", "")
s.writeJSON(w, resp)
}
// handleHealth handles health check
func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
}
// writeJSON writes a JSON response
func (s *Server) writeJSON(w http.ResponseWriter, data interface{}) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(data)
}
// writeError writes an error response
func (s *Server) writeError(w http.ResponseWriter, msgType proto.MessageType, code proto.ErrorCode, message string) {
resp := proto.NewErrorResponse(msgType, code, message)
s.writeJSON(w, resp)
}
// getClientIP extracts the client IP from the request
func (s *Server) getClientIP(r *http.Request) string {
// Check X-Forwarded-For header
xff := r.Header.Get("X-Forwarded-For")
if xff != "" {
return strings.Split(xff, ",")[0]
}
// Check X-Real-IP header
xri := r.Header.Get("X-Real-IP")
if xri != "" {
return xri
}
// Fall back to RemoteAddr
addr := r.RemoteAddr
if idx := strings.LastIndex(addr, ":"); idx != -1 {
return addr[:idx]
}
return addr
}
// ServeHTTP implements http.Handler
func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// Sanitize path
r.URL.Path = path.Clean(r.URL.Path)
// Log request
fmt.Printf("[%s] %s %s\n", r.Method, r.URL.Path, s.getClientIP(r))
// Add CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
s.mux.ServeHTTP(w, r)
}
// generateToken generates a cryptographically random 256-bit token.
// It panics if the system CSPRNG is unavailable: silently returning a
// predictable token would hand out a valid k3s join credential.
func generateToken() string {
b, err := crypto.GenerateNonce(32)
if err != nil {
panic(fmt.Sprintf("csprng unavailable while generating token: %v", err))
}
return base64.RawURLEncoding.EncodeToString(b)
}
// generatePassword generates a cryptographically random 128-bit password.
func generatePassword() string {
b, err := crypto.GenerateNonce(16)
if err != nil {
panic(fmt.Sprintf("csprng unavailable while generating password: %v", err))
}
return base64.RawURLEncoding.EncodeToString(b)
}