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.
145 lines
5.2 KiB
Go
145 lines
5.2 KiB
Go
package agent
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/tls"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"mime"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.luoli.live/root/virt/gateway/internal/protocol"
|
|
)
|
|
|
|
const completionEndpointPath = "/api/internal/cloud/operation-completion"
|
|
|
|
var terminalCompletionDispositions = map[string]struct{}{
|
|
"applied": {}, "late": {}, "rejected": {},
|
|
}
|
|
|
|
type completionAcceptance struct {
|
|
Accepted bool `json:"accepted"`
|
|
Disposition string `json:"disposition"`
|
|
}
|
|
|
|
// HTTPCompletionSink performs exactly one bounded delivery attempt. Retry
|
|
// policy belongs to the Agent's durable, ACK-driven outbox.
|
|
type HTTPCompletionSink struct {
|
|
endpoint string
|
|
secret []byte
|
|
client *http.Client
|
|
now func() time.Time
|
|
}
|
|
|
|
func NewHTTPCompletionSink(agentAuthEndpoint string, secret []byte, timeout time.Duration) (*HTTPCompletionSink, error) {
|
|
if err := validateLoopbackPanelURL(agentAuthEndpoint, "/api/internal/cloud/agent-auth"); err != nil {
|
|
return nil, err
|
|
}
|
|
if len(secret) < 32 || timeout <= 0 || timeout > 30*time.Second {
|
|
return nil, errors.New("invalid completion sink settings")
|
|
}
|
|
parsed, _ := url.Parse(agentAuthEndpoint)
|
|
parsed.Path = completionEndpointPath
|
|
if err := validateLoopbackPanelURL(parsed.String(), completionEndpointPath); err != nil {
|
|
return nil, err
|
|
}
|
|
dialer := &net.Dialer{Timeout: timeout, KeepAlive: 30 * time.Second}
|
|
transport := &http.Transport{
|
|
Proxy: nil, DialContext: dialer.DialContext, ForceAttemptHTTP2: false,
|
|
TLSClientConfig: &tls.Config{MinVersion: tls.VersionTLS12}, TLSHandshakeTimeout: timeout,
|
|
}
|
|
return &HTTPCompletionSink{
|
|
endpoint: parsed.String(), secret: append([]byte(nil), secret...), now: time.Now,
|
|
client: &http.Client{
|
|
Transport: transport, Timeout: timeout,
|
|
CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse },
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func (s *HTTPCompletionSink) Deliver(ctx context.Context, agentID string, completion Completion) error {
|
|
if !agentIDPattern.MatchString(agentID) || validateCompletion(completion) != nil {
|
|
return errors.New("invalid completion delivery")
|
|
}
|
|
body, err := json.Marshal(struct {
|
|
Type string `json:"type"`
|
|
ID string `json:"id"`
|
|
AgentID string `json:"agent_id"`
|
|
OperationID string `json:"operation_id"`
|
|
Action string `json:"action"`
|
|
ResourceID string `json:"resource_id"`
|
|
RequestFingerprint string `json:"request_fingerprint"`
|
|
Status string `json:"status"`
|
|
EffectMayHaveApplied bool `json:"effect_may_have_applied"`
|
|
SafeToResubmit bool `json:"safe_to_resubmit"`
|
|
ErrorCode string `json:"error_code"`
|
|
CauseCode string `json:"cause_code,omitempty"`
|
|
Result json.RawMessage `json:"result"`
|
|
}{
|
|
Type: "completion", ID: completion.ID, AgentID: agentID, OperationID: completion.OperationID,
|
|
Action: completion.Action, ResourceID: completion.ResourceID,
|
|
RequestFingerprint: completion.RequestFingerprint,
|
|
Status: completion.Status, EffectMayHaveApplied: completion.EffectMayHaveApplied,
|
|
SafeToResubmit: completion.SafeToResubmit, ErrorCode: completion.ErrorCode,
|
|
CauseCode: completion.CauseCode,
|
|
Result: completion.Result,
|
|
})
|
|
if err != nil || len(body) > maxControlFrame {
|
|
return errors.New("encode completion delivery")
|
|
}
|
|
request, err := http.NewRequestWithContext(ctx, http.MethodPost, s.endpoint, bytes.NewReader(body))
|
|
if err != nil {
|
|
return errors.New("create completion delivery")
|
|
}
|
|
request.Header.Set("Accept", "application/json")
|
|
request.Header.Set("Content-Type", "application/json")
|
|
nonce, err := protocol.RandomNonce()
|
|
if err != nil {
|
|
return errors.New("create completion nonce")
|
|
}
|
|
if err := protocol.Sign(request, body, protocol.Actor{Service: "agent-gateway"}, s.secret, s.now(), nonce); err != nil {
|
|
return errors.New("sign completion delivery")
|
|
}
|
|
response, err := s.client.Do(request)
|
|
if err != nil {
|
|
return errors.New("panel completion endpoint unavailable")
|
|
}
|
|
defer response.Body.Close()
|
|
raw, readErr := io.ReadAll(io.LimitReader(response.Body, maxPanelResponseBytes+1))
|
|
if readErr != nil || len(raw) == 0 || len(raw) > maxPanelResponseBytes ||
|
|
response.StatusCode < 200 || response.StatusCode >= 300 || !completionJSONContentType(response.Header) {
|
|
return errors.New("panel rejected operation completion")
|
|
}
|
|
var accepted completionAcceptance
|
|
if decodeStrict(raw, &accepted) != nil || !accepted.Accepted {
|
|
return errors.New("panel rejected operation completion")
|
|
}
|
|
if _, terminal := terminalCompletionDispositions[accepted.Disposition]; !terminal {
|
|
return errors.New("panel did not terminally accept operation completion")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func completionJSONContentType(header http.Header) bool {
|
|
values := header.Values("Content-Type")
|
|
if len(values) != 1 {
|
|
return false
|
|
}
|
|
mediaType, parameters, err := mime.ParseMediaType(values[0])
|
|
if err != nil || mediaType != "application/json" || len(parameters) > 1 {
|
|
return false
|
|
}
|
|
for name, value := range parameters {
|
|
if name != "charset" || !strings.EqualFold(value, "utf-8") {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|