You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
312 lines
10 KiB
Go
312 lines
10 KiB
Go
package update
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.luoli.live/root/virt/gateway/internal/protocol"
|
|
)
|
|
|
|
const maxAPIRequestBody = 64 << 10
|
|
|
|
var jobIDPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{32}$`)
|
|
|
|
type Server struct {
|
|
manager *Manager
|
|
state *StateStore
|
|
authenticator *protocol.Authenticator
|
|
}
|
|
|
|
type jobResponse struct {
|
|
JobID string `json:"job_id"`
|
|
Status string `json:"status"`
|
|
Phase string `json:"phase"`
|
|
Error string `json:"error,omitempty"`
|
|
ErrorCode string `json:"error_code,omitempty"`
|
|
NewCommit string `json:"new_commit,omitempty"`
|
|
RollbackRef string `json:"rollback_ref,omitempty"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
UpdatedAt time.Time `json:"updated_at"`
|
|
}
|
|
|
|
func NewServer(manager *Manager, state *StateStore, secret []byte) (*Server, error) {
|
|
if manager == nil || state == nil {
|
|
return nil, errors.New("update manager and state are required")
|
|
}
|
|
authenticator, err := protocol.NewAuthenticator(secret, 60*time.Second, 2*time.Minute, state)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &Server{manager: manager, state: state, authenticator: authenticator}, nil
|
|
}
|
|
|
|
func (s *Server) ServeHTTP(response http.ResponseWriter, request *http.Request) {
|
|
response.Header().Set("Content-Type", "application/json; charset=utf-8")
|
|
response.Header().Set("Cache-Control", "no-store")
|
|
response.Header().Set("X-Content-Type-Options", "nosniff")
|
|
body, err := readRequestBody(response, request)
|
|
if err != nil {
|
|
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
|
return
|
|
}
|
|
actor, err := s.authenticator.Authenticate(request, body)
|
|
if err != nil {
|
|
if errors.Is(err, protocol.ErrNonceStore) {
|
|
writeAPIError(response, http.StatusServiceUnavailable, "authentication_state_unavailable")
|
|
return
|
|
}
|
|
writeAPIError(response, http.StatusUnauthorized, "authentication_failed")
|
|
return
|
|
}
|
|
if !actor.IsAdmin || !actor.IsSuperAdmin || !actor.CanManage || actor.UserID <= 0 || actor.Service != "" {
|
|
writeAPIError(response, http.StatusForbidden, "super_admin_required")
|
|
return
|
|
}
|
|
s.route(response, request, body)
|
|
}
|
|
|
|
func (s *Server) route(response http.ResponseWriter, request *http.Request, body []byte) {
|
|
if request.URL.RawQuery != "" {
|
|
writeAPIError(response, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
switch {
|
|
case request.URL.Path == "/v1/health" && request.Method == http.MethodGet:
|
|
writeJSON(response, http.StatusOK, map[string]any{"status": "ok", "maintenance_lock": s.state.MaintenanceLocked()})
|
|
case request.URL.Path == "/v1/settings" && request.Method == http.MethodGet:
|
|
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
|
case request.URL.Path == "/v1/settings" && request.Method == http.MethodPut:
|
|
s.updateSettings(response, request, body)
|
|
case request.URL.Path == "/v1/settings/token" && request.Method == http.MethodDelete:
|
|
if len(bytes.TrimSpace(body)) != 0 {
|
|
writeAPIError(response, http.StatusBadRequest, "body_not_allowed")
|
|
return
|
|
}
|
|
if err := s.state.SetAccessToken(""); err != nil {
|
|
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
|
return
|
|
}
|
|
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
|
case request.URL.Path == "/v1/check" && request.Method == http.MethodPost:
|
|
if !emptyJSONObject(body) {
|
|
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
|
return
|
|
}
|
|
result, err := s.manager.Check(request.Context())
|
|
if err != nil {
|
|
writeAPIError(response, http.StatusConflict, "update_check_failed")
|
|
return
|
|
}
|
|
writeJSON(response, http.StatusOK, result)
|
|
case request.URL.Path == "/v1/apply" && request.Method == http.MethodPost:
|
|
s.apply(response, body)
|
|
case request.URL.Path == "/v1/jobs" && request.Method == http.MethodGet:
|
|
jobs := s.state.Jobs()
|
|
result := make([]jobResponse, 0, len(jobs))
|
|
for _, job := range jobs {
|
|
result = append(result, publicJob(job))
|
|
}
|
|
writeJSON(response, http.StatusOK, map[string]any{"jobs": result, "maintenance_lock": s.state.MaintenanceLocked()})
|
|
case strings.HasPrefix(request.URL.Path, "/v1/jobs/"):
|
|
s.job(response, request, body)
|
|
default:
|
|
writeAPIError(response, http.StatusNotFound, "not_found")
|
|
}
|
|
}
|
|
|
|
func (s *Server) updateSettings(response http.ResponseWriter, request *http.Request, body []byte) {
|
|
var input struct {
|
|
AccessToken *string `json:"access_token"`
|
|
ClearToken *bool `json:"clear_token"`
|
|
}
|
|
if err := decodeJSONObject(body, &input); err != nil || (input.AccessToken == nil && input.ClearToken == nil) ||
|
|
(input.ClearToken != nil && *input.ClearToken && input.AccessToken != nil && *input.AccessToken != "") {
|
|
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
|
return
|
|
}
|
|
if input.ClearToken != nil && *input.ClearToken {
|
|
if err := s.state.SetAccessToken(""); err != nil {
|
|
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
|
return
|
|
}
|
|
} else if input.AccessToken != nil && *input.AccessToken != "" {
|
|
if !validAccessToken(*input.AccessToken) {
|
|
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
|
return
|
|
}
|
|
if err := s.state.SetAccessToken(*input.AccessToken); err != nil {
|
|
writeAPIError(response, http.StatusServiceUnavailable, "state_unavailable")
|
|
return
|
|
}
|
|
} else if input.AccessToken == nil {
|
|
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
|
return
|
|
}
|
|
if input.ClearToken != nil && !*input.ClearToken && input.AccessToken == nil {
|
|
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_access_token")
|
|
return
|
|
}
|
|
writeJSON(response, http.StatusOK, s.manager.Settings(request.Context()))
|
|
}
|
|
|
|
func (s *Server) apply(response http.ResponseWriter, body []byte) {
|
|
var input struct {
|
|
ExpectedCurrentCommit string `json:"expected_current_commit"`
|
|
ExpectedRemoteCommit string `json:"expected_remote_commit"`
|
|
}
|
|
if err := decodeJSONObject(body, &input); err != nil {
|
|
writeAPIError(response, http.StatusBadRequest, "invalid_request")
|
|
return
|
|
}
|
|
job, err := s.manager.StartApply(input.ExpectedCurrentCommit, input.ExpectedRemoteCommit)
|
|
if err != nil {
|
|
writeAPIError(response, http.StatusConflict, "update_precondition_failed")
|
|
return
|
|
}
|
|
writeJSON(response, http.StatusAccepted, publicJob(job))
|
|
}
|
|
|
|
func (s *Server) job(response http.ResponseWriter, request *http.Request, body []byte) {
|
|
remainder := strings.TrimPrefix(request.URL.Path, "/v1/jobs/")
|
|
parts := strings.Split(remainder, "/")
|
|
if len(parts) == 1 && request.Method == http.MethodGet && jobIDPattern.MatchString(parts[0]) {
|
|
job, ok := s.state.Job(parts[0])
|
|
if !ok {
|
|
writeAPIError(response, http.StatusNotFound, "job_not_found")
|
|
return
|
|
}
|
|
writeJSON(response, http.StatusOK, publicJob(job))
|
|
return
|
|
}
|
|
if len(parts) == 2 && parts[1] == "resolve" && request.Method == http.MethodPost && jobIDPattern.MatchString(parts[0]) {
|
|
var input struct {
|
|
Resolution string `json:"resolution"`
|
|
Evidence string `json:"evidence"`
|
|
}
|
|
if err := decodeJSONObject(body, &input); err != nil ||
|
|
(input.Resolution != "completed" && input.Resolution != "rolled_back") ||
|
|
!validEvidence(input.Evidence) {
|
|
writeAPIError(response, http.StatusUnprocessableEntity, "invalid_resolution")
|
|
return
|
|
}
|
|
if err := s.state.ResolveJob(parts[0], input.Resolution, input.Evidence); err != nil {
|
|
if errors.Is(err, os.ErrNotExist) {
|
|
writeAPIError(response, http.StatusNotFound, "job_not_found")
|
|
} else {
|
|
writeAPIError(response, http.StatusConflict, "job_not_reconcilable")
|
|
}
|
|
return
|
|
}
|
|
job, _ := s.state.Job(parts[0])
|
|
writeJSON(response, http.StatusOK, publicJob(job))
|
|
return
|
|
}
|
|
writeAPIError(response, http.StatusNotFound, "not_found")
|
|
}
|
|
|
|
func publicJob(job Job) jobResponse {
|
|
status := job.Status
|
|
if status == "manual_intervention" {
|
|
status = "blocked"
|
|
} else if status == "resolved" {
|
|
if job.Resolution == "completed" {
|
|
status = "succeeded"
|
|
} else {
|
|
status = "failed"
|
|
}
|
|
}
|
|
result := jobResponse{JobID: job.ID, Status: status, Phase: job.Checkpoint,
|
|
ErrorCode: job.ErrorCode, NewCommit: job.AppliedCommit, RollbackRef: job.PreviousCommit,
|
|
CreatedAt: job.CreatedAt, UpdatedAt: job.UpdatedAt}
|
|
if job.Status == "manual_intervention" {
|
|
result.Error = "更新状态不确定,必须通过 SSH 核对后再处理"
|
|
} else if job.Status == "failed" {
|
|
result.Error = "更新已在主机变更前安全终止"
|
|
}
|
|
return result
|
|
}
|
|
|
|
func readRequestBody(response http.ResponseWriter, request *http.Request) ([]byte, error) {
|
|
request.Body = http.MaxBytesReader(response, request.Body, maxAPIRequestBody)
|
|
body, err := io.ReadAll(request.Body)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return body, nil
|
|
}
|
|
|
|
func decodeJSONObject(body []byte, destination any) error {
|
|
if len(bytes.TrimSpace(body)) == 0 {
|
|
return errors.New("JSON object required")
|
|
}
|
|
decoder := json.NewDecoder(bytes.NewReader(body))
|
|
decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(destination); err != nil {
|
|
return err
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
|
return errors.New("trailing JSON data")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func emptyJSONObject(body []byte) bool {
|
|
if len(bytes.TrimSpace(body)) == 0 {
|
|
return true
|
|
}
|
|
var value map[string]any
|
|
return decodeJSONObject(body, &value) == nil && len(value) == 0
|
|
}
|
|
|
|
func validAccessToken(value string) bool {
|
|
if len(value) < 8 || len(value) > 4096 {
|
|
return false
|
|
}
|
|
for _, character := range value {
|
|
if character < 0x21 || character == 0x7f {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func validEvidence(value string) bool {
|
|
value = strings.TrimSpace(value)
|
|
if len(value) < 8 || len(value) > 500 || !strings.Contains(value, ":") {
|
|
return false
|
|
}
|
|
for _, character := range value {
|
|
if character < 0x20 || character == 0x7f {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
func randomID() (string, error) {
|
|
random := make([]byte, 24)
|
|
if _, err := rand.Read(random); err != nil {
|
|
return "", err
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(random), nil
|
|
}
|
|
|
|
func writeAPIError(response http.ResponseWriter, status int, code string) {
|
|
writeJSON(response, status, map[string]any{"error": map[string]string{"code": code}})
|
|
}
|
|
|
|
func writeJSON(response http.ResponseWriter, status int, value any) {
|
|
response.WriteHeader(status)
|
|
_ = json.NewEncoder(response).Encode(value)
|
|
}
|