This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
)
|
||||
|
||||
var ErrControlPlaneUnavailable = errors.New("delegated control-plane authority unavailable")
|
||||
|
||||
type controlPlaneAuthority struct {
|
||||
baseURL string
|
||||
client *http.Client
|
||||
credential func() (string, error)
|
||||
}
|
||||
|
||||
func (a controlPlaneAuthority) authorize(ctx context.Context, request authority.DelegatedControlPlaneRequest) error {
|
||||
return a.post(ctx, "/v1/internal/control-plane/authorize", request)
|
||||
}
|
||||
|
||||
func (a controlPlaneAuthority) completed(ctx context.Context, request authority.DelegatedControlPlaneRequest, success bool) {
|
||||
outcome := "FAILED"
|
||||
if success {
|
||||
outcome = "COMPLETED"
|
||||
}
|
||||
_ = a.post(ctx, "/v1/internal/control-plane/completions", authority.DelegatedControlPlaneCompletion{Request: request, Outcome: outcome})
|
||||
}
|
||||
|
||||
func (a controlPlaneAuthority) revoke(ctx context.Context, creatorAuthorization string, grantID authority.GrantID) error {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(a.baseURL, "/")+"/v1/creator/control-plane/grants/"+string(grantID)+"/revoke", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Authorization", creatorAuthorization)
|
||||
response, err := a.client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusNoContent {
|
||||
return fmt.Errorf("delegated grant revoke status %d", response.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a controlPlaneAuthority) post(ctx context.Context, path string, value any) error {
|
||||
credential, err := a.credential()
|
||||
if err != nil || credential == "" {
|
||||
return ErrControlPlaneUnavailable
|
||||
}
|
||||
body, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, strings.TrimRight(a.baseURL, "/")+path, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Authorization", "Bearer "+credential)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response, err := a.client.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode < 200 || response.StatusCode >= 300 {
|
||||
return fmt.Errorf("delegated control-plane status %d", response.StatusCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
)
|
||||
|
||||
func TestControlPlaneClientSendsOnlyServiceCredentialToAuthorityRuntime(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/internal/control-plane/authorize" || r.Header.Get("Authorization") != "Bearer service-token" {
|
||||
t.Fatalf("unexpected delegated request: %s %q", r.URL.Path, r.Header.Get("Authorization"))
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer server.Close()
|
||||
client := controlPlaneAuthority{baseURL: server.URL, client: server.Client(), credential: func() (string, error) { return "service-token", nil }}
|
||||
request := authority.DelegatedControlPlaneRequest{GrantID: "grant", TaskID: "task", TaskRevision: 1, Operation: authority.DelegatedOperationCanaryCognitiveBinding, Resource: authority.CognitiveBindingResource{BindingID: "binding", ProviderInstanceID: "provider", ModelDescriptorID: "model"}}
|
||||
if err := client.authorize(context.Background(), request); err != nil {
|
||||
t.Fatalf("authorize: %v", err)
|
||||
}
|
||||
}
|
||||
+133
-7
@@ -39,12 +39,13 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
creatorPasswordPath = "/run/secrets/creator_password"
|
||||
creatorBootstrapTokenPath = "/run/secrets/creator_bootstrap_token"
|
||||
creatorSessionKeyPath = "/run/secrets/creator_session_signing_key"
|
||||
epistemicsDBPasswordPath = "/run/secrets/epistemics_db_password"
|
||||
interactionDBPasswordPath = "/run/secrets/interaction_db_password"
|
||||
selfDBPasswordPath = "/run/secrets/self_db_password"
|
||||
creatorPasswordPath = "/run/secrets/creator_password"
|
||||
creatorBootstrapTokenPath = "/run/secrets/creator_bootstrap_token"
|
||||
creatorSessionKeyPath = "/run/secrets/creator_session_signing_key"
|
||||
epistemicsDBPasswordPath = "/run/secrets/epistemics_db_password"
|
||||
interactionDBPasswordPath = "/run/secrets/interaction_db_password"
|
||||
selfDBPasswordPath = "/run/secrets/self_db_password"
|
||||
controlPlaneServiceTokenPath = "/run/secrets/control_plane_service_token"
|
||||
)
|
||||
|
||||
const maxCreatorCredentialsBytes = 4 << 10
|
||||
@@ -137,6 +138,14 @@ func main() {
|
||||
} else if selfUser == "" || os.Getenv("SELF_POSTGRES_CREDENTIAL_REF") == "" {
|
||||
log.Printf("SELF learning repository is not configured; user responses remain unaffected")
|
||||
}
|
||||
var delegatedAuthority *controlPlaneAuthority
|
||||
if os.Getenv("CONTROL_PLANE_SERVICE_CREDENTIAL_REF") != "" {
|
||||
delegatedAuthority = &controlPlaneAuthority{baseURL: envOr("COMMIT_RUNTIME_URL", "http://commit-runtime:8082"), client: &http.Client{Timeout: 5 * time.Second}, credential: func() (string, error) {
|
||||
return readCredentialRefSecretPurpose("CONTROL_PLANE_SERVICE_TOKEN", "CONTROL_PLANE_SERVICE_CREDENTIAL_REF", controlPlaneServiceTokenPath, secretcontracts.SecretPurposeServiceAuthentication)
|
||||
}}
|
||||
} else {
|
||||
log.Printf("delegated control-plane authority is not configured; existing human control remains available")
|
||||
}
|
||||
reminderClient, err := newContinuityReminderClient(envOr("CONTINUITY_RUNTIME_URL", "http://continuity-runtime:8081"), &http.Client{Timeout: 5 * time.Second})
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
@@ -1669,6 +1678,119 @@ func main() {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(promotion)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/control-plane/cognitive-canary", func(w http.ResponseWriter, r *http.Request) {
|
||||
if delegatedAuthority == nil {
|
||||
http.Error(w, "delegated control-plane authority unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var value struct {
|
||||
Delegation authority.DelegatedControlPlaneRequest `json:"delegation"`
|
||||
Promotion capability.CognitiveCanaryPromotionRequest `json:"promotion"`
|
||||
}
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 16<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&value); err != nil || value.Delegation.Operation != authority.DelegatedOperationCanaryCognitiveBinding {
|
||||
http.Error(w, "invalid delegated canary request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
current, err := capabilityRepository.LoadCognitiveCandidate(r.Context(), value.Promotion.BindingID, value.Promotion.ExpectedBindingRevision)
|
||||
if err != nil {
|
||||
http.Error(w, "cognitive registry unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
resource := authority.CognitiveBindingResource{BindingID: string(current.Binding.ID), ProviderInstanceID: string(current.Provider.ID), ModelDescriptorID: string(current.Model.ID)}
|
||||
if value.Delegation.Resource != resource {
|
||||
http.Error(w, "delegated resource denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
err = delegatedAuthority.authorize(r.Context(), value.Delegation)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrControlPlaneUnavailable) {
|
||||
http.Error(w, "delegated control-plane authority unavailable", http.StatusServiceUnavailable)
|
||||
} else {
|
||||
http.Error(w, "delegated control-plane authority denied", http.StatusForbidden)
|
||||
}
|
||||
return
|
||||
}
|
||||
value.Promotion.RequestedByPrincipalID = current.Binding.OwnerPrincipalID
|
||||
value.Promotion.CapabilityID = current.Binding.CapabilityID
|
||||
promotion, err := capabilitydomain.BuildCanaryPromotion(value.Promotion, current)
|
||||
if err == nil {
|
||||
err = capabilityRepository.SaveCognitiveCanaryPromotion(r.Context(), promotion)
|
||||
}
|
||||
delegatedAuthority.completed(r.Context(), value.Delegation, err == nil)
|
||||
if err != nil {
|
||||
http.Error(w, "canary promotion precondition failed", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(promotion)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/control-plane/cognitive-activate", func(w http.ResponseWriter, r *http.Request) {
|
||||
if delegatedAuthority == nil {
|
||||
http.Error(w, "delegated control-plane authority unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
var value struct {
|
||||
Delegation authority.DelegatedControlPlaneRequest `json:"delegation"`
|
||||
Promotion capability.CognitiveActivationPromotionRequest `json:"promotion"`
|
||||
}
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 16<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&value); err != nil || value.Delegation.Operation != authority.DelegatedOperationActivateCognitiveBinding {
|
||||
http.Error(w, "invalid delegated activation request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
current, err := capabilityRepository.LoadCognitiveCandidate(r.Context(), value.Promotion.BindingID, value.Promotion.ExpectedBindingRevision)
|
||||
if err != nil {
|
||||
http.Error(w, "cognitive registry unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
resource := authority.CognitiveBindingResource{BindingID: string(current.Binding.ID), ProviderInstanceID: string(current.Provider.ID), ModelDescriptorID: string(current.Model.ID)}
|
||||
if value.Delegation.Resource != resource {
|
||||
http.Error(w, "delegated resource denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
err = delegatedAuthority.authorize(r.Context(), value.Delegation)
|
||||
if err != nil {
|
||||
if errors.Is(err, ErrControlPlaneUnavailable) {
|
||||
http.Error(w, "delegated control-plane authority unavailable", http.StatusServiceUnavailable)
|
||||
} else {
|
||||
http.Error(w, "delegated control-plane authority denied", http.StatusForbidden)
|
||||
}
|
||||
return
|
||||
}
|
||||
value.Promotion.RequestedByPrincipalID = current.Binding.OwnerPrincipalID
|
||||
value.Promotion.CapabilityID = current.Binding.CapabilityID
|
||||
promotion, err := capabilitydomain.BuildActivationPromotion(value.Promotion, current)
|
||||
if err == nil {
|
||||
err = capabilityRepository.SaveCognitiveActivationPromotion(r.Context(), promotion)
|
||||
}
|
||||
delegatedAuthority.completed(r.Context(), value.Delegation, err == nil)
|
||||
if err != nil {
|
||||
http.Error(w, "cognitive activation precondition failed", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
_ = json.NewEncoder(w).Encode(promotion)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/creator/control-plane/grants/{grant}/revoke", func(w http.ResponseWriter, r *http.Request) {
|
||||
if delegatedAuthority == nil {
|
||||
http.Error(w, "delegated control-plane authority unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
_, ok := authenticateCreator(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := delegatedAuthority.revoke(r.Context(), r.Header.Get("Authorization"), authority.GrantID(r.PathValue("grant"))); err != nil {
|
||||
http.Error(w, "delegated grant revoke denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("POST /v1/cognitive-registry/performance-evidence", func(w http.ResponseWriter, r *http.Request) {
|
||||
var value capability.PerformanceEvidence
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 64<<10))
|
||||
@@ -1963,6 +2085,10 @@ func normalizeSecretFile(name string, contents []byte) (string, error) {
|
||||
}
|
||||
|
||||
func readCredentialRefSecret(name, refName, fileName string) (string, error) {
|
||||
return readCredentialRefSecretPurpose(name, refName, fileName, secretcontracts.SecretPurposeDatabasePassword)
|
||||
}
|
||||
|
||||
func readCredentialRefSecretPurpose(name, refName, fileName string, purpose secretcontracts.SecretPurpose) (string, error) {
|
||||
if _, directSet := os.LookupEnv(name); directSet {
|
||||
return "", fmt.Errorf("%s direct environment secret is forbidden; use the standard secret file", name)
|
||||
}
|
||||
@@ -1980,7 +2106,7 @@ func readCredentialRefSecret(name, refName, fileName string) (string, error) {
|
||||
}
|
||||
return resolver.ResolveFile(secretcontracts.SecretFileRef{
|
||||
CredentialRef: secretcontracts.CredentialRef(ref),
|
||||
Purpose: secretcontracts.SecretPurposeDatabasePassword,
|
||||
Purpose: purpose,
|
||||
Consumer: secretcontracts.RuntimeConsumerCore,
|
||||
Path: fileName,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user