Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1710907ec | ||
|
|
2f085858db | ||
|
|
a8be998cee | ||
|
|
f42a94ee7a | ||
|
|
35666c9923 | ||
|
|
da83248ac9 | ||
|
|
db139e6800 | ||
|
|
b4335d6735 | ||
|
|
44541b1ba3 | ||
|
|
9c42b18850 | ||
|
|
3a8c6d4827 | ||
|
|
8b1d75f337 | ||
|
|
1c05619899 |
@@ -3,6 +3,7 @@ package postgres
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
@@ -27,3 +28,28 @@ func (r *AuthorityRepository) LoadGrant(ctx context.Context, id authority.GrantI
|
||||
}
|
||||
return grant, scope, nil
|
||||
}
|
||||
|
||||
func (r *AuthorityRepository) LoadDelegatedControlPlaneGrant(ctx context.Context, id authority.GrantID) (authority.DelegatedControlPlaneGrant, error) {
|
||||
var grant authority.DelegatedControlPlaneGrant
|
||||
err := r.pool.QueryRow(ctx, `SELECT grant_id,service_actor_id,service_principal_id,issuer_principal_id,task_id,task_revision,operations,binding_id,provider_instance_id,model_descriptor_id,issued_at_unix_millis,expires_at_unix_millis,architecture_revision,nonce,revision,status FROM authority.delegated_control_plane_grants WHERE grant_id=$1`, id).Scan(&grant.ID, &grant.ServiceActorID, &grant.ServicePrincipalID, &grant.IssuerPrincipalID, &grant.TaskID, &grant.TaskRevision, &grant.Operations, &grant.Resource.BindingID, &grant.Resource.ProviderInstanceID, &grant.Resource.ModelDescriptorID, &grant.IssuedAtUnixMillis, &grant.ExpiresAtUnixMillis, &grant.ArchitectureRevision, &grant.Nonce, &grant.Revision, &grant.Status)
|
||||
if err != nil {
|
||||
return authority.DelegatedControlPlaneGrant{}, fmt.Errorf("load delegated control-plane grant: %w", err)
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
|
||||
func (r *AuthorityRepository) RecordDelegatedControlPlaneAudit(ctx context.Context, audit authority.DelegatedControlPlaneAudit) error {
|
||||
_, err := r.pool.Exec(ctx, `INSERT INTO authority.delegated_control_plane_audit (audit_id,grant_id,service_actor_id,service_principal_id,task_id,task_revision,operation,binding_id,provider_instance_id,model_descriptor_id,decision,outcome,recorded_at_unix_millis) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13)`, audit.AuditID, audit.GrantID, audit.ServiceActorID, audit.ServicePrincipalID, audit.TaskID, audit.TaskRevision, audit.Operation, audit.Resource.BindingID, audit.Resource.ProviderInstanceID, audit.Resource.ModelDescriptorID, audit.Decision, audit.Outcome, audit.RecordedAtUnixMillis)
|
||||
if err != nil {
|
||||
return fmt.Errorf("record delegated control-plane audit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AuthorityRepository) RevokeDelegatedControlPlaneGrant(ctx context.Context, id authority.GrantID, issuer string) (bool, error) {
|
||||
result, err := r.pool.Exec(ctx, `UPDATE authority.delegated_control_plane_grants SET status='REVOKED',revision=revision+1,revoked_at_unix_millis=$3 WHERE grant_id=$1 AND issuer_principal_id=$2 AND status='ACTIVE'`, id, issuer, time.Now().UnixMilli())
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("revoke delegated control-plane grant: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
# ADR-0021 — Delegated Non-Interactive Control-Plane Authority
|
||||
|
||||
Status: Accepted
|
||||
Date: 2026-08-31
|
||||
Accepted under: owner decision for GEN2-AUTHORITY-001
|
||||
|
||||
## Context
|
||||
|
||||
The existing Creator session endpoints correctly require a human principal for
|
||||
governed Cognitive CANARY and ACTIVE transitions. A bounded background task
|
||||
cannot use those endpoints without either a browser session, impersonation, or
|
||||
a direct Capability write. All three alternatives are invalid.
|
||||
|
||||
## Decision
|
||||
|
||||
1. Identity remains the sole owner of Actors, Principals and their bindings. A
|
||||
service principal is a separately identified Actor/Principal binding; it is
|
||||
neither a Human Principal nor an impersonation of one.
|
||||
2. Authority remains the sole owner of delegated task grants, validation,
|
||||
revocation and safe action audit. This extends `AuthorityGrant`; it does not
|
||||
introduce a robot-authority owner or a second authorization registry.
|
||||
3. A delegated grant is typed and narrow: service principal, task id and
|
||||
revision, operation capability, exact Cognitive binding resource/revision,
|
||||
issuer, issue/expiry times, grant revision and lifecycle status. It is
|
||||
default-deny and cannot authorize grant creation, extension, policy change,
|
||||
or administration.
|
||||
4. A control-plane request is authorized in the existing `commit-runtime`, the
|
||||
runtime topology location of Authority. It must pass two independent checks: service credential
|
||||
authentication and a current delegated-grant authorization for its exact
|
||||
task/operation/resource. Credential possession never expands authority.
|
||||
5. Long-lived credential material remains only in the existing protected secret
|
||||
backend and is addressed by a `CredentialRef` plus bootstrap file reference.
|
||||
The runtime never logs, persists, or returns its token. Rotation changes the
|
||||
protected artifact; revocation of a grant blocks new actions immediately.
|
||||
6. Capability remains the only owner of Cognitive binding/evaluation lifecycle.
|
||||
The delegated path invokes the existing owner validation and promotion
|
||||
builders; it cannot synthesize an evaluation or mark a binding active.
|
||||
7. Control-plane actions receive durable Authority audit records containing
|
||||
identity, task, operation, resource, decision and safe result reference.
|
||||
Secret values, request payloads, user memory and hidden reasoning are never
|
||||
stored in that audit.
|
||||
8. External mutations continue to use Commit/Executor/Receipt/Outcome where
|
||||
the existing action is an external effect. Capability's owner-local binding
|
||||
lifecycle remains an owner-local governed state transition, not a shortcut
|
||||
around an external executor.
|
||||
|
||||
## Consequences
|
||||
|
||||
- Background work can execute only an explicitly delegated, time-bounded task.
|
||||
- Restart reconstructs authorization from Identity/Authority durable state; no
|
||||
process-local permission cache is authoritative.
|
||||
- Each later task must receive a new delegated grant. A grant for
|
||||
GEN2-COGNITIVE-003 cannot be reused for SELF development or code promotion.
|
||||
- The first implementation deliberately covers only the Cognitive lifecycle
|
||||
operations required by GEN2-COGNITIVE-003. Broader control-plane actions
|
||||
need their own task-scoped authority and acceptance evidence.
|
||||
|
||||
## Rollback
|
||||
|
||||
Disable or revoke the delegated grant and route no new non-interactive requests
|
||||
to the endpoint. Existing Authority audit and Capability history remain
|
||||
append-only evidence; no binding state is rolled back by deleting history.
|
||||
@@ -0,0 +1,170 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
secretcontracts "git.cin.su/m/Assistant/contracts/secrets"
|
||||
authoritydomain "git.cin.su/m/Assistant/modules/authority/domain"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
platformsecrets "git.cin.su/m/Assistant/platform/secrets"
|
||||
)
|
||||
|
||||
const (
|
||||
delegatedControlPlaneActor identity.ActorID = "domovoy-control-plane-actor"
|
||||
delegatedControlPlanePrincipal identity.PrincipalID = "domovoy-control-plane-principal"
|
||||
delegatedControlPlaneTokenFile = "control_plane_service_token"
|
||||
)
|
||||
|
||||
type delegatedControlPlaneAuthoritySource interface {
|
||||
LoadDelegatedControlPlaneGrant(context.Context, authority.GrantID) (authority.DelegatedControlPlaneGrant, error)
|
||||
RecordDelegatedControlPlaneAudit(context.Context, authority.DelegatedControlPlaneAudit) error
|
||||
RevokeDelegatedControlPlaneGrant(context.Context, authority.GrantID, string) (bool, error)
|
||||
}
|
||||
|
||||
type delegatedControlPlaneCore interface {
|
||||
Session(context.Context, string) (identity.CreatorSession, error)
|
||||
Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error)
|
||||
}
|
||||
|
||||
type delegatedControlPlaneHandler struct {
|
||||
authority delegatedControlPlaneAuthoritySource
|
||||
core delegatedControlPlaneCore
|
||||
credential func() (string, error)
|
||||
now func() time.Time
|
||||
newID func() (ids.ID, error)
|
||||
}
|
||||
|
||||
func registerDelegatedControlPlaneRoutes(mux *http.ServeMux, handler delegatedControlPlaneHandler) {
|
||||
mux.HandleFunc("POST /v1/internal/control-plane/authorize", handler.authorize)
|
||||
mux.HandleFunc("POST /v1/internal/control-plane/completions", handler.complete)
|
||||
mux.HandleFunc("POST /v1/creator/control-plane/grants/{grant}/revoke", handler.revoke)
|
||||
}
|
||||
|
||||
func (h delegatedControlPlaneHandler) authorize(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.serviceAuthenticated(r) {
|
||||
http.Error(w, "service principal denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var request authority.DelegatedControlPlaneRequest
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 8<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
http.Error(w, "invalid delegated control-plane request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
grant, err := h.authority.LoadDelegatedControlPlaneGrant(r.Context(), request.GrantID)
|
||||
if err != nil {
|
||||
http.Error(w, "delegated authority denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
binding, err := h.core.Binding(r.Context(), delegatedControlPlaneActor, delegatedControlPlanePrincipal)
|
||||
if err != nil || authoritydomain.ValidateDelegatedControlPlaneGrant(h.now().UnixMilli(), binding, grant, request) != nil {
|
||||
_ = h.audit(r.Context(), grant, request, "DENY", "FAILED")
|
||||
http.Error(w, "delegated authority denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := h.audit(r.Context(), grant, request, "ALLOW", "PENDING"); err != nil {
|
||||
http.Error(w, "delegated audit unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h delegatedControlPlaneHandler) complete(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.serviceAuthenticated(r) {
|
||||
http.Error(w, "service principal denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
var value authority.DelegatedControlPlaneCompletion
|
||||
decoder := json.NewDecoder(io.LimitReader(r.Body, 8<<10))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&value); err != nil || (value.Outcome != "COMPLETED" && value.Outcome != "FAILED") {
|
||||
http.Error(w, "invalid delegated completion", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
grant, err := h.authority.LoadDelegatedControlPlaneGrant(r.Context(), value.Request.GrantID)
|
||||
if err != nil {
|
||||
http.Error(w, "delegated authority unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if !authoritydomain.RequestMatchesDelegatedControlPlaneGrant(grant, value.Request) {
|
||||
http.Error(w, "delegated completion denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if err := h.audit(r.Context(), grant, value.Request, "ALLOW", value.Outcome); err != nil {
|
||||
http.Error(w, "delegated audit unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h delegatedControlPlaneHandler) revoke(w http.ResponseWriter, r *http.Request) {
|
||||
session, err := h.core.Session(r.Context(), r.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
http.Error(w, "creator session denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
grant, err := h.authority.LoadDelegatedControlPlaneGrant(r.Context(), authority.GrantID(r.PathValue("grant")))
|
||||
if err != nil || !authoritydomain.CanIssuerRevokeDelegatedGrant(session.PrincipalID, grant) {
|
||||
http.Error(w, "delegated grant revoke denied", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
ok, err := h.authority.RevokeDelegatedControlPlaneGrant(r.Context(), grant.ID, string(session.PrincipalID))
|
||||
if err != nil || !ok {
|
||||
http.Error(w, "delegated grant revoke denied", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
request := authority.DelegatedControlPlaneRequest{GrantID: grant.ID, TaskID: grant.TaskID, TaskRevision: grant.TaskRevision, Operation: authority.DelegatedOperationRevokeControlPlaneGrant, Resource: grant.Resource}
|
||||
if err := h.audit(r.Context(), grant, request, "REVOKE", "REVOKED"); err != nil {
|
||||
http.Error(w, "delegated audit unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h delegatedControlPlaneHandler) serviceAuthenticated(r *http.Request) bool {
|
||||
if h.credential == nil {
|
||||
return false
|
||||
}
|
||||
expected, err := h.credential()
|
||||
presented := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
return err == nil && expected != "" && presented != "" && subtle.ConstantTimeCompare([]byte(expected), []byte(presented)) == 1
|
||||
}
|
||||
|
||||
func (h delegatedControlPlaneHandler) audit(ctx context.Context, grant authority.DelegatedControlPlaneGrant, request authority.DelegatedControlPlaneRequest, decision, outcome string) error {
|
||||
if h.newID == nil {
|
||||
return errors.New("delegated audit id unavailable")
|
||||
}
|
||||
id, err := h.newID()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return h.authority.RecordDelegatedControlPlaneAudit(ctx, authority.DelegatedControlPlaneAudit{AuditID: id, GrantID: grant.ID, ServiceActorID: delegatedControlPlaneActor, ServicePrincipalID: delegatedControlPlanePrincipal, TaskID: request.TaskID, TaskRevision: request.TaskRevision, Operation: request.Operation, Resource: request.Resource, Decision: decision, Outcome: outcome, RecordedAtUnixMillis: h.now().UnixMilli()})
|
||||
}
|
||||
|
||||
func delegatedControlPlaneCredential() (string, error) {
|
||||
ref := os.Getenv("CONTROL_PLANE_SERVICE_CREDENTIAL_REF")
|
||||
if ref == "" {
|
||||
return "", errors.New("control-plane service credential ref is required")
|
||||
}
|
||||
root := os.Getenv("CONTROL_PLANE_SERVICE_SECRET_ROOT")
|
||||
if root == "" {
|
||||
root = "/run/control-plane-secrets"
|
||||
}
|
||||
resolver, err := platformsecrets.NewFileResolver(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resolver.ResolveFile(secretcontracts.SecretFileRef{CredentialRef: secretcontracts.CredentialRef(ref), Purpose: secretcontracts.SecretPurposeServiceAuthentication, Consumer: secretcontracts.RuntimeConsumerCommit, Path: filepath.Join(root, delegatedControlPlaneTokenFile)})
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
"git.cin.su/m/Assistant/platform/ids"
|
||||
)
|
||||
|
||||
type delegatedAuthorityFake struct {
|
||||
grant authority.DelegatedControlPlaneGrant
|
||||
audits []authority.DelegatedControlPlaneAudit
|
||||
revoked bool
|
||||
}
|
||||
|
||||
func TestDelegatedAuthorityCredentialRotationRejectsOldToken(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
tokenPath := filepath.Join(root, "control_plane_service_token")
|
||||
if err := os.WriteFile(tokenPath, []byte("old-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("CONTROL_PLANE_SERVICE_CREDENTIAL_REF", "credential://domovoy/control-plane/service-token/v1")
|
||||
t.Setenv("CONTROL_PLANE_SERVICE_SECRET_ROOT", root)
|
||||
h := delegatedControlPlaneHandler{credential: delegatedControlPlaneCredential}
|
||||
oldRequest := httptest.NewRequest(http.MethodPost, "/v1/internal/control-plane/authorize", nil)
|
||||
oldRequest.Header.Set("Authorization", "Bearer old-token")
|
||||
if !h.serviceAuthenticated(oldRequest) {
|
||||
t.Fatal("active credential was rejected before rotation")
|
||||
}
|
||||
if err := os.WriteFile(tokenPath, []byte("new-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if h.serviceAuthenticated(oldRequest) {
|
||||
t.Fatal("old credential remained valid after rotation")
|
||||
}
|
||||
newRequest := httptest.NewRequest(http.MethodPost, "/v1/internal/control-plane/authorize", nil)
|
||||
newRequest.Header.Set("Authorization", "Bearer new-token")
|
||||
if !h.serviceAuthenticated(newRequest) {
|
||||
t.Fatal("new credential was rejected after rotation")
|
||||
}
|
||||
}
|
||||
|
||||
func (f *delegatedAuthorityFake) LoadDelegatedControlPlaneGrant(context.Context, authority.GrantID) (authority.DelegatedControlPlaneGrant, error) {
|
||||
if f.grant.ID == "" {
|
||||
return authority.DelegatedControlPlaneGrant{}, errors.New("missing")
|
||||
}
|
||||
return f.grant, nil
|
||||
}
|
||||
func (f *delegatedAuthorityFake) RecordDelegatedControlPlaneAudit(_ context.Context, audit authority.DelegatedControlPlaneAudit) error {
|
||||
f.audits = append(f.audits, audit)
|
||||
return nil
|
||||
}
|
||||
func (f *delegatedAuthorityFake) RevokeDelegatedControlPlaneGrant(context.Context, authority.GrantID, string) (bool, error) {
|
||||
f.revoked = true
|
||||
f.grant.Status = authority.DelegatedGrantRevoked
|
||||
return true, nil
|
||||
}
|
||||
|
||||
type delegatedCoreFake struct{}
|
||||
|
||||
func (delegatedCoreFake) Binding(context.Context, identity.ActorID, identity.PrincipalID) (identity.PrincipalBinding, error) {
|
||||
return identity.PrincipalBinding{ActorID: delegatedControlPlaneActor, PrincipalID: delegatedControlPlanePrincipal, Active: true}, nil
|
||||
}
|
||||
func (delegatedCoreFake) Session(context.Context, string) (identity.CreatorSession, error) {
|
||||
return identity.CreatorSession{PrincipalID: "owner"}, nil
|
||||
}
|
||||
|
||||
func TestDelegatedAuthorityRejectsWrongResourceAndSurvivesRestart(t *testing.T) {
|
||||
resource := authority.CognitiveBindingResource{BindingID: "binding", ProviderInstanceID: "provider", ModelDescriptorID: "model"}
|
||||
fake := &delegatedAuthorityFake{grant: authority.DelegatedControlPlaneGrant{ID: "grant", ServiceActorID: delegatedControlPlaneActor, ServicePrincipalID: delegatedControlPlanePrincipal, IssuerPrincipalID: "owner", TaskID: "GEN2-COGNITIVE-003", TaskRevision: 4, Operations: []authority.DelegatedControlPlaneOperation{authority.DelegatedOperationCanaryCognitiveBinding}, Resource: resource, IssuedAtUnixMillis: 1, ExpiresAtUnixMillis: 100, ArchitectureRevision: "ADR-0021", Nonce: "nonce", Revision: 1, Status: authority.DelegatedGrantActive}}
|
||||
h := delegatedControlPlaneHandler{authority: fake, core: delegatedCoreFake{}, credential: func() (string, error) { return "service-token", nil }, now: func() time.Time { return time.UnixMilli(10) }, newID: func() (ids.ID, error) { return "audit", nil }}
|
||||
mux := http.NewServeMux()
|
||||
registerDelegatedControlPlaneRoutes(mux, h)
|
||||
valid := `{"GrantID":"grant","TaskID":"GEN2-COGNITIVE-003","TaskRevision":4,"Operation":"CANARY_COGNITIVE_BINDING","Resource":{"BindingID":"binding","ProviderInstanceID":"provider","ModelDescriptorID":"model"}}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/v1/internal/control-plane/authorize", strings.NewReader(valid))
|
||||
request.Header.Set("Authorization", "Bearer service-token")
|
||||
response := httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNoContent {
|
||||
t.Fatalf("valid delegation status=%d", response.Code)
|
||||
}
|
||||
wrong := strings.Replace(valid, `"binding"`, `"other"`, 1)
|
||||
request = httptest.NewRequest(http.MethodPost, "/v1/internal/control-plane/authorize", strings.NewReader(wrong))
|
||||
request.Header.Set("Authorization", "Bearer service-token")
|
||||
response = httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("wrong resource status=%d", response.Code)
|
||||
}
|
||||
// A fresh handler reads the same durable grant source; no process-local allow survives restart.
|
||||
request = httptest.NewRequest(http.MethodPost, "/v1/creator/control-plane/grants/grant/revoke", nil)
|
||||
request.Header.Set("Authorization", "Bearer creator-session")
|
||||
response = httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusNoContent || !fake.revoked {
|
||||
t.Fatalf("revoke status=%d revoked=%v", response.Code, fake.revoked)
|
||||
}
|
||||
restarted := delegatedControlPlaneHandler{authority: fake, core: delegatedCoreFake{}, credential: h.credential, now: h.now, newID: h.newID}
|
||||
mux = http.NewServeMux()
|
||||
registerDelegatedControlPlaneRoutes(mux, restarted)
|
||||
request = httptest.NewRequest(http.MethodPost, "/v1/internal/control-plane/authorize", strings.NewReader(valid))
|
||||
request.Header.Set("Authorization", "Bearer service-token")
|
||||
response = httptest.NewRecorder()
|
||||
mux.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusForbidden {
|
||||
t.Fatalf("revoked grant accepted after restart: %d", response.Code)
|
||||
}
|
||||
if len(fake.audits) < 3 {
|
||||
t.Fatalf("audit trail missing: %#v", fake.audits)
|
||||
}
|
||||
}
|
||||
@@ -100,6 +100,9 @@ func main() {
|
||||
core: creatorCore, continuity: creatorContinuity, authority: authorityRepository, repository: repository,
|
||||
executor: dispatcher, newID: ids.New, now: time.Now,
|
||||
}, executorToken)
|
||||
registerDelegatedControlPlaneRoutes(mux, delegatedControlPlaneHandler{
|
||||
authority: authorityRepository, core: creatorCore, credential: delegatedControlPlaneCredential, now: time.Now, newID: ids.New,
|
||||
})
|
||||
mux.HandleFunc("POST /v1/authorized-actions", func(w http.ResponseWriter, r *http.Request) {
|
||||
var request authorizationRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
|
||||
@@ -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,39 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
|
||||
func TestControlPlaneCredentialUsesDedicatedSecretRoot(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(root, controlPlaneServiceTokenFile), []byte("test-machine-token\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("CONTROL_PLANE_SERVICE_CREDENTIAL_REF", "credential://domovoy/control-plane/service-token/v1")
|
||||
t.Setenv("CONTROL_PLANE_SERVICE_SECRET_ROOT", root)
|
||||
if got, err := readControlPlaneServiceCredential(); err != nil || got != "test-machine-token" {
|
||||
t.Fatalf("control-plane credential resolution failed: %v", err)
|
||||
}
|
||||
}
|
||||
+147
-7
@@ -31,6 +31,7 @@ import (
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
@@ -39,12 +40,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"
|
||||
controlPlaneServiceTokenFile = "control_plane_service_token"
|
||||
)
|
||||
|
||||
const maxCreatorCredentialsBytes = 4 << 10
|
||||
@@ -137,6 +139,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 readControlPlaneServiceCredential()
|
||||
}}
|
||||
} 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 +1679,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 +2086,23 @@ func normalizeSecretFile(name string, contents []byte) (string, error) {
|
||||
}
|
||||
|
||||
func readCredentialRefSecret(name, refName, fileName string) (string, error) {
|
||||
return readCredentialRefSecretPurpose(name, refName, fileName, secretcontracts.SecretPurposeDatabasePassword)
|
||||
}
|
||||
|
||||
func readControlPlaneServiceCredential() (string, error) {
|
||||
ref := os.Getenv("CONTROL_PLANE_SERVICE_CREDENTIAL_REF")
|
||||
if ref == "" {
|
||||
return "", errors.New("CONTROL_PLANE_SERVICE_CREDENTIAL_REF is required")
|
||||
}
|
||||
root := envOr("CONTROL_PLANE_SERVICE_SECRET_ROOT", "/run/control-plane-secrets")
|
||||
resolver, err := platformsecrets.NewFileResolver(root)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return resolver.ResolveFile(secretcontracts.SecretFileRef{CredentialRef: secretcontracts.CredentialRef(ref), Purpose: secretcontracts.SecretPurposeServiceAuthentication, Consumer: secretcontracts.RuntimeConsumerCore, Path: filepath.Join(root, controlPlaneServiceTokenFile)})
|
||||
}
|
||||
|
||||
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 +2120,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,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
platformsecrets "git.cin.su/m/Assistant/platform/secrets"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultRoot = "/run/control-plane-secrets"
|
||||
defaultRuntimeUID = 100
|
||||
defaultRuntimeGID = 101
|
||||
)
|
||||
|
||||
func main() {
|
||||
reason := flag.String("reason", "", "rotation reason: owner-requested-rotation or exposure-detected")
|
||||
flag.Parse()
|
||||
if flag.NArg() != 1 {
|
||||
fail("usage: secret-control-plane [ensure|rotate]")
|
||||
}
|
||||
store, err := platformsecrets.NewLocalMachineCredentialStore(defaultRoot, defaultRuntimeUID, defaultRuntimeGID, nil)
|
||||
if err != nil {
|
||||
fail("control-plane credential store unavailable")
|
||||
}
|
||||
spec := platformsecrets.ControlPlaneServiceTokenSpec()
|
||||
switch strings.TrimSpace(flag.Arg(0)) {
|
||||
case "ensure":
|
||||
result, err := store.Ensure(spec)
|
||||
if err != nil {
|
||||
fail("control-plane credential provisioning failed")
|
||||
}
|
||||
if result.Created {
|
||||
fmt.Println("control-plane credential provisioned")
|
||||
return
|
||||
}
|
||||
fmt.Println("control-plane credential already active")
|
||||
case "rotate":
|
||||
if !validRotationReason(*reason) {
|
||||
fail("rotation reason is invalid")
|
||||
}
|
||||
if _, err := store.Rotate(spec, *reason); err != nil {
|
||||
fail("control-plane credential rotation failed")
|
||||
}
|
||||
fmt.Println("control-plane credential rotated")
|
||||
default:
|
||||
fail("unsupported control-plane credential operation")
|
||||
}
|
||||
}
|
||||
|
||||
func validRotationReason(reason string) bool {
|
||||
switch strings.TrimSpace(reason) {
|
||||
case "owner-requested-rotation", "exposure-detected":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func fail(message string) {
|
||||
fmt.Fprintln(os.Stderr, message)
|
||||
os.Exit(1)
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package main
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestSecretControlPlaneDefaultsUseDedicatedProtectedRoot(t *testing.T) {
|
||||
if defaultRoot != "/run/control-plane-secrets" || defaultRuntimeUID <= 0 || defaultRuntimeGID <= 0 {
|
||||
t.Fatal("unsafe control-plane defaults")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRotationReasonsAreBoundedAndNeverArbitraryDiagnosticText(t *testing.T) {
|
||||
if !validRotationReason("owner-requested-rotation") || !validRotationReason("exposure-detected") || validRotationReason("Bearer secret-value") {
|
||||
t.Fatal("unsafe rotation reason validation")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package authority
|
||||
|
||||
import "git.cin.su/m/Assistant/platform/ids"
|
||||
|
||||
// DelegatedControlPlaneAuthorization is the safe, payload-free decision that
|
||||
// the Authority runtime returns to an already bounded caller.
|
||||
type DelegatedControlPlaneAuthorization struct {
|
||||
AuditID ids.ID
|
||||
}
|
||||
|
||||
type DelegatedControlPlaneCompletion struct {
|
||||
Request DelegatedControlPlaneRequest
|
||||
Outcome string
|
||||
}
|
||||
@@ -13,6 +13,73 @@ type GrantClass string
|
||||
|
||||
const GrantClassCreator GrantClass = "CREATOR"
|
||||
|
||||
// DelegatedControlPlaneOperation is deliberately a closed, semantic operation
|
||||
// set. A service credential cannot turn into arbitrary control-plane access.
|
||||
type DelegatedControlPlaneOperation string
|
||||
|
||||
const (
|
||||
DelegatedOperationQualifyCognitiveBinding DelegatedControlPlaneOperation = "QUALIFY_COGNITIVE_BINDING"
|
||||
DelegatedOperationEvaluateCognitiveBinding DelegatedControlPlaneOperation = "EVALUATE_COGNITIVE_BINDING"
|
||||
DelegatedOperationCanaryCognitiveBinding DelegatedControlPlaneOperation = "CANARY_COGNITIVE_BINDING"
|
||||
DelegatedOperationActivateCognitiveBinding DelegatedControlPlaneOperation = "ACTIVATE_VALIDATED_COGNITIVE_BINDING"
|
||||
DelegatedOperationRevokeControlPlaneGrant DelegatedControlPlaneOperation = "REVOKE_DELEGATED_CONTROL_PLANE_GRANT"
|
||||
)
|
||||
|
||||
type DelegatedGrantStatus string
|
||||
|
||||
const (
|
||||
DelegatedGrantActive DelegatedGrantStatus = "ACTIVE"
|
||||
DelegatedGrantRevoked DelegatedGrantStatus = "REVOKED"
|
||||
)
|
||||
|
||||
// CognitiveBindingResource identifies the one governed Capability lifecycle
|
||||
// resource to which a task delegation applies. It is intentionally not a
|
||||
// general-purpose resource selector.
|
||||
type CognitiveBindingResource struct {
|
||||
BindingID string
|
||||
ProviderInstanceID string
|
||||
ModelDescriptorID string
|
||||
}
|
||||
|
||||
type DelegatedControlPlaneGrant struct {
|
||||
ID GrantID
|
||||
ServiceActorID identity.ActorID
|
||||
ServicePrincipalID identity.PrincipalID
|
||||
IssuerPrincipalID identity.PrincipalID
|
||||
TaskID string
|
||||
TaskRevision int64
|
||||
Operations []DelegatedControlPlaneOperation
|
||||
Resource CognitiveBindingResource
|
||||
IssuedAtUnixMillis int64
|
||||
ExpiresAtUnixMillis int64
|
||||
ArchitectureRevision string
|
||||
Nonce string
|
||||
Revision AuthorityRevision
|
||||
Status DelegatedGrantStatus
|
||||
}
|
||||
|
||||
type DelegatedControlPlaneRequest struct {
|
||||
GrantID GrantID
|
||||
TaskID string
|
||||
TaskRevision int64
|
||||
Operation DelegatedControlPlaneOperation
|
||||
Resource CognitiveBindingResource
|
||||
}
|
||||
|
||||
type DelegatedControlPlaneAudit struct {
|
||||
AuditID ids.ID
|
||||
GrantID GrantID
|
||||
ServiceActorID identity.ActorID
|
||||
ServicePrincipalID identity.PrincipalID
|
||||
TaskID string
|
||||
TaskRevision int64
|
||||
Operation DelegatedControlPlaneOperation
|
||||
Resource CognitiveBindingResource
|
||||
Decision string
|
||||
Outcome string
|
||||
RecordedAtUnixMillis int64
|
||||
}
|
||||
|
||||
type Scope struct {
|
||||
ID ScopeID
|
||||
Global bool
|
||||
|
||||
@@ -8,8 +8,9 @@ type CredentialRef string
|
||||
type SecretPurpose string
|
||||
|
||||
const (
|
||||
SecretPurposeDatabasePassword SecretPurpose = "DATABASE_PASSWORD"
|
||||
SecretPurposeProviderAPIKey SecretPurpose = "PROVIDER_API_KEY"
|
||||
SecretPurposeDatabasePassword SecretPurpose = "DATABASE_PASSWORD"
|
||||
SecretPurposeProviderAPIKey SecretPurpose = "PROVIDER_API_KEY"
|
||||
SecretPurposeServiceAuthentication SecretPurpose = "SERVICE_AUTHENTICATION"
|
||||
)
|
||||
|
||||
// RuntimeConsumer identifies a trusted runtime allowed to resolve a credential.
|
||||
@@ -17,6 +18,7 @@ type RuntimeConsumer string
|
||||
|
||||
const (
|
||||
RuntimeConsumerCore RuntimeConsumer = "core-runtime"
|
||||
RuntimeConsumerCommit RuntimeConsumer = "commit-runtime"
|
||||
RuntimeConsumerWorkWorker RuntimeConsumer = "agent-worker"
|
||||
RuntimeConsumerEpistemicsWorker RuntimeConsumer = "reflection-worker"
|
||||
RuntimeConsumerCognitive RuntimeConsumer = "cognitive-worker"
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
BEGIN;
|
||||
|
||||
SET ROLE identity_role;
|
||||
INSERT INTO identity.actors (actor_id, display_name) VALUES ('domovoy-control-plane-actor', 'Domovoy Control Plane') ON CONFLICT (actor_id) DO NOTHING;
|
||||
INSERT INTO identity.principals (principal_id, display_name) VALUES ('domovoy-control-plane-principal', 'Domovoy Control Plane Principal') ON CONFLICT (principal_id) DO NOTHING;
|
||||
INSERT INTO identity.principal_bindings (actor_id, principal_id, active) VALUES ('domovoy-control-plane-actor', 'domovoy-control-plane-principal', TRUE) ON CONFLICT (actor_id, principal_id) DO NOTHING;
|
||||
RESET ROLE;
|
||||
|
||||
SET ROLE authority_role;
|
||||
CREATE TABLE IF NOT EXISTS authority.delegated_control_plane_grants (
|
||||
grant_id TEXT PRIMARY KEY, service_actor_id TEXT NOT NULL, service_principal_id TEXT NOT NULL, issuer_principal_id TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL, task_revision BIGINT NOT NULL, operations TEXT[] NOT NULL,
|
||||
binding_id TEXT NOT NULL, provider_instance_id TEXT NOT NULL, model_descriptor_id TEXT NOT NULL,
|
||||
issued_at_unix_millis BIGINT NOT NULL, expires_at_unix_millis BIGINT NOT NULL, architecture_revision TEXT NOT NULL, nonce TEXT NOT NULL,
|
||||
revision BIGINT NOT NULL, status TEXT NOT NULL, revoked_at_unix_millis BIGINT NOT NULL DEFAULT 0,
|
||||
CHECK (task_revision > 0), CHECK (cardinality(operations) > 0),
|
||||
CHECK (operations <@ ARRAY['QUALIFY_COGNITIVE_BINDING','EVALUATE_COGNITIVE_BINDING','CANARY_COGNITIVE_BINDING','ACTIVATE_VALIDATED_COGNITIVE_BINDING']::TEXT[]),
|
||||
CHECK (issued_at_unix_millis > 0), CHECK (expires_at_unix_millis > issued_at_unix_millis), CHECK (revision > 0),
|
||||
CHECK (status IN ('ACTIVE','REVOKED')), CHECK (binding_id <> '' AND provider_instance_id <> '' AND model_descriptor_id <> ''),
|
||||
CHECK (nonce <> '' AND architecture_revision <> '')
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS authority.delegated_control_plane_audit (
|
||||
audit_id TEXT PRIMARY KEY, grant_id TEXT NOT NULL, service_actor_id TEXT NOT NULL, service_principal_id TEXT NOT NULL,
|
||||
task_id TEXT NOT NULL, task_revision BIGINT NOT NULL, operation TEXT NOT NULL,
|
||||
binding_id TEXT NOT NULL, provider_instance_id TEXT NOT NULL, model_descriptor_id TEXT NOT NULL,
|
||||
decision TEXT NOT NULL, outcome TEXT NOT NULL, recorded_at_unix_millis BIGINT NOT NULL,
|
||||
CHECK (task_revision > 0), CHECK (recorded_at_unix_millis > 0),
|
||||
CHECK (operation IN ('QUALIFY_COGNITIVE_BINDING','EVALUATE_COGNITIVE_BINDING','CANARY_COGNITIVE_BINDING','ACTIVATE_VALIDATED_COGNITIVE_BINDING','REVOKE_DELEGATED_CONTROL_PLANE_GRANT')),
|
||||
CHECK (decision IN ('ALLOW','DENY','REVOKE')), CHECK (outcome IN ('PENDING','COMPLETED','FAILED','REVOKED'))
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS delegated_control_plane_audit_grant_idx ON authority.delegated_control_plane_audit (grant_id, recorded_at_unix_millis);
|
||||
INSERT INTO authority.delegated_control_plane_grants (grant_id,service_actor_id,service_principal_id,issuer_principal_id,task_id,task_revision,operations,binding_id,provider_instance_id,model_descriptor_id,issued_at_unix_millis,expires_at_unix_millis,architecture_revision,nonce,revision,status)
|
||||
VALUES ('gen2-cognitive-003-control-plane-grant','domovoy-control-plane-actor','domovoy-control-plane-principal','domovoy-creator-principal','GEN2-COGNITIVE-003',4,ARRAY['QUALIFY_COGNITIVE_BINDING','EVALUATE_COGNITIVE_BINDING','CANARY_COGNITIVE_BINDING','ACTIVATE_VALIDATED_COGNITIVE_BINDING']::TEXT[],'binding-c1be4c9f85d8b4a19314f2b8','local-medium-primary','model-26d63a1102b49c5583ffca53',1788134400000,1789344000000,'ADR-0021','gen2-cognitive-003-local-medium-v1',1,'ACTIVE') ON CONFLICT (grant_id) DO NOTHING;
|
||||
GRANT SELECT, INSERT, UPDATE ON authority.delegated_control_plane_grants, authority.delegated_control_plane_audit TO authority_role;
|
||||
RESET ROLE;
|
||||
COMMIT;
|
||||
@@ -53,6 +53,8 @@ services:
|
||||
WORK_POSTGRES_PASSWORD: ${WORK_DB_PASSWORD}
|
||||
CAPABILITY_POSTGRES_USER: capability_role
|
||||
CAPABILITY_POSTGRES_PASSWORD: ${CAPABILITY_DB_PASSWORD}
|
||||
CONTROL_PLANE_SERVICE_CREDENTIAL_REF: credential://domovoy/control-plane/service-token/v1
|
||||
CONTROL_PLANE_SERVICE_SECRET_ROOT: /run/control-plane-secrets
|
||||
SELF_POSTGRES_USER: self_role
|
||||
SELF_POSTGRES_CREDENTIAL_REF: credential://domovoy/self/db-password/v1
|
||||
EPISTEMICS_POSTGRES_USER: epistemics_role
|
||||
@@ -69,6 +71,7 @@ services:
|
||||
RESEARCH_RUNTIME_URL: http://research-runtime-candidate:8087
|
||||
volumes:
|
||||
- assistant_core_secrets:/run/secrets:ro
|
||||
- assistant_control_plane_service_secrets:/run/control-plane-secrets:ro
|
||||
networks:
|
||||
shared:
|
||||
aliases: [core-runtime-candidate]
|
||||
@@ -138,6 +141,9 @@ services:
|
||||
volumes:
|
||||
assistant_core_secrets:
|
||||
external: true
|
||||
assistant_control_plane_service_secrets:
|
||||
name: assistant_control_plane_service_secrets
|
||||
external: true
|
||||
assistant_research_sources:
|
||||
name: assistant_research_sources
|
||||
external: true
|
||||
|
||||
@@ -70,6 +70,8 @@ services:
|
||||
WORK_POSTGRES_PASSWORD: ${WORK_DB_PASSWORD}
|
||||
CAPABILITY_POSTGRES_USER: capability_role
|
||||
CAPABILITY_POSTGRES_PASSWORD: ${CAPABILITY_DB_PASSWORD}
|
||||
CONTROL_PLANE_SERVICE_CREDENTIAL_REF: credential://domovoy/control-plane/service-token/v1
|
||||
CONTROL_PLANE_SERVICE_SECRET_ROOT: /run/control-plane-secrets
|
||||
SELF_POSTGRES_USER: self_role
|
||||
SELF_POSTGRES_CREDENTIAL_REF: credential://domovoy/self/db-password/v1
|
||||
EPISTEMICS_POSTGRES_USER: epistemics_role
|
||||
@@ -85,6 +87,7 @@ services:
|
||||
depends_on: { postgres: { condition: service_healthy } }
|
||||
volumes:
|
||||
- assistant_core_secrets:/run/secrets:ro
|
||||
- assistant_control_plane_service_secrets:/run/control-plane-secrets:ro
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:8080/healthz >/dev/null && wget -qO- http://localhost:8080/readyz >/dev/null"]
|
||||
interval: 10s
|
||||
@@ -239,6 +242,9 @@ services:
|
||||
POSTGRES_PASSWORD: ${COMMIT_DB_PASSWORD}
|
||||
AUTHORITY_POSTGRES_USER: authority_role
|
||||
AUTHORITY_POSTGRES_PASSWORD: ${AUTHORITY_DB_PASSWORD}
|
||||
CONTROL_PLANE_SERVICE_CREDENTIAL_REF: credential://domovoy/control-plane/service-token/v1
|
||||
CONTROL_PLANE_SERVICE_SECRET_ROOT: /run/control-plane-secrets
|
||||
SECRET_BACKEND_ROOT: /run/secrets
|
||||
CORE_RUNTIME_URL: http://core-runtime:8080
|
||||
CONTINUITY_RUNTIME_URL: http://continuity-runtime:8081
|
||||
COMMIT_EXECUTOR_TOKEN: ${COMMIT_EXECUTOR_TOKEN}
|
||||
@@ -247,8 +253,19 @@ services:
|
||||
# External mutation credentials belong here only via Portainer/Docker secrets/env injection.
|
||||
depends_on: [core-runtime, continuity-runtime, notification-receiver]
|
||||
volumes:
|
||||
- assistant_core_secrets:/run/secrets:ro
|
||||
- assistant_control_plane_service_secrets:/run/control-plane-secrets:ro
|
||||
- assistant_notification_writer_secret:/run/notification-writer:ro
|
||||
|
||||
secret-control-plane:
|
||||
profiles: ["secret-control-plane"]
|
||||
build: { context: .., dockerfile: deploy/images/runtime.Dockerfile, args: { TARGET: secret-control-plane, SOURCE_REVISION: "${ASSISTANT_SOURCE_REVISION:-unknown}" } }
|
||||
user: "0:0"
|
||||
restart: "no"
|
||||
command: ["ensure"]
|
||||
volumes:
|
||||
- assistant_control_plane_service_secrets:/run/control-plane-secrets
|
||||
|
||||
cognitive-worker:
|
||||
build: { context: .., dockerfile: deploy/images/runtime.Dockerfile, args: { TARGET: cognitive-worker, SOURCE_REVISION: "${ASSISTANT_SOURCE_REVISION:-unknown}" } }
|
||||
restart: unless-stopped
|
||||
@@ -363,6 +380,9 @@ volumes:
|
||||
assistant_nats:
|
||||
assistant_core_secrets:
|
||||
external: true
|
||||
assistant_control_plane_service_secrets:
|
||||
name: assistant_control_plane_service_secrets
|
||||
external: true
|
||||
assistant_notification_receipts:
|
||||
assistant_notification_writer_secret:
|
||||
external: true
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# This is the only production writer for the dedicated control-plane machine
|
||||
# credential volume. It never receives, prints, or exports a secret value.
|
||||
BASE_DIR="${BASE_DIR:-/home/m/assistant-deploy}"
|
||||
REPO_DIR="${REPO_DIR:-$BASE_DIR/repo}"
|
||||
ENV_FILE="${ENV_FILE:-$BASE_DIR/production-compose.env}"
|
||||
COMPOSE_FILE="$REPO_DIR/deploy/docker-compose.prod.yml"
|
||||
VOLUME="assistant_control_plane_service_secrets"
|
||||
ACTION="${1:-ensure}"
|
||||
|
||||
case "$ACTION" in
|
||||
ensure|rotate) ;;
|
||||
*) echo "unsupported machine credential action" >&2; exit 2 ;;
|
||||
esac
|
||||
|
||||
[[ -f "$ENV_FILE" ]] || { echo "production compose environment is missing" >&2; exit 1; }
|
||||
[[ -f "$COMPOSE_FILE" ]] || { echo "production compose file is missing" >&2; exit 1; }
|
||||
|
||||
compose() { docker compose --env-file "$ENV_FILE" -f "$COMPOSE_FILE" "$@"; }
|
||||
|
||||
# `docker volume create` is idempotent and does not inspect or expose content.
|
||||
docker volume create "$VOLUME" >/dev/null
|
||||
revision="$(git -C "$REPO_DIR" rev-parse HEAD)"
|
||||
ASSISTANT_SOURCE_REVISION="$revision" compose build --build-arg "SOURCE_REVISION=$revision" secret-control-plane >/dev/null
|
||||
|
||||
if [[ "$ACTION" == "rotate" ]]; then
|
||||
# Only bounded, non-secret rotation reasons can reach the audit trail.
|
||||
reason="${ROTATION_REASON:-owner-requested-rotation}"
|
||||
case "$reason" in
|
||||
owner-requested-rotation|exposure-detected) ;;
|
||||
*) echo "invalid rotation reason" >&2; exit 2 ;;
|
||||
esac
|
||||
ASSISTANT_SOURCE_REVISION="$revision" compose --profile secret-control-plane run --rm --no-deps secret-control-plane -reason "$reason" rotate
|
||||
else
|
||||
ASSISTANT_SOURCE_REVISION="$revision" compose --profile secret-control-plane run --rm --no-deps secret-control-plane ensure
|
||||
fi
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Regression: the wrapper accepts only an operation name and never places a
|
||||
# plaintext credential on a Docker/Compose command line.
|
||||
script="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)/provision-machine-credential.sh"
|
||||
tmp="$(mktemp -d)"
|
||||
trap 'rm -rf "$tmp"' EXIT
|
||||
mkdir -p "$tmp/bin" "$tmp/repo/deploy"
|
||||
cp "$script" "$tmp/repo/deploy/provision-machine-credential.sh"
|
||||
printf 'placeholder\n' > "$tmp/repo/deploy/docker-compose.prod.yml"
|
||||
printf 'placeholder\n' > "$tmp/env"
|
||||
cat > "$tmp/bin/docker" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
printf '%s\n' "$*" >> "${CAPTURE:?}"
|
||||
SH
|
||||
cat > "$tmp/bin/git" <<'SH'
|
||||
#!/usr/bin/env bash
|
||||
printf '0123456789abcdef0123456789abcdef01234567\n'
|
||||
SH
|
||||
chmod +x "$tmp/bin/docker" "$tmp/bin/git" "$tmp/repo/deploy/provision-machine-credential.sh"
|
||||
capture="$tmp/capture"
|
||||
PATH="$tmp/bin:$PATH" CAPTURE="$capture" REPO_DIR="$tmp/repo" ENV_FILE="$tmp/env" "$tmp/repo/deploy/provision-machine-credential.sh" ensure >/dev/null
|
||||
grep -qx 'volume create assistant_control_plane_service_secrets' "$capture"
|
||||
grep -q -- '--profile secret-control-plane run --rm --no-deps secret-control-plane ensure' "$capture"
|
||||
PATH="$tmp/bin:$PATH" CAPTURE="$capture" REPO_DIR="$tmp/repo" ENV_FILE="$tmp/env" ROTATION_REASON=owner-requested-rotation "$tmp/repo/deploy/provision-machine-credential.sh" rotate >/dev/null
|
||||
grep -q -- '--profile secret-control-plane run --rm --no-deps secret-control-plane -reason owner-requested-rotation rotate' "$capture"
|
||||
if grep -Eqi '(token=|password=|secret=|authorization:)' "$capture"; then
|
||||
echo "provisioning wrapper passed credential material" >&2
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# Safe diagnostics only: artifact existence/readability and mount topology.
|
||||
# This script never reads or prints credential content.
|
||||
TOKEN_PATH="/run/control-plane-secrets/control_plane_service_token"
|
||||
VOLUME="assistant_control_plane_service_secrets"
|
||||
authorized=(assistant-core-runtime-1 assistant-commit-runtime-1)
|
||||
unauthorized=(assistant-creator-web-1 assistant-cognitive-worker-1 assistant-research-runtime-1 assistant-continuity-runtime-1 assistant-agent-worker-1)
|
||||
|
||||
for container in "${authorized[@]}"; do
|
||||
docker inspect "$container" >/dev/null
|
||||
docker exec "$container" sh -c "test -r '$TOKEN_PATH'"
|
||||
docker inspect -f '{{range .Mounts}}{{if eq .Name "assistant_control_plane_service_secrets"}}{{.Destination}} {{.RW}}{{end}}{{end}}' "$container" | grep -qx '/run/control-plane-secrets false'
|
||||
done
|
||||
|
||||
for container in "${unauthorized[@]}"; do
|
||||
docker inspect "$container" >/dev/null
|
||||
if docker inspect -f '{{range .Mounts}}{{println .Name}}{{end}}' "$container" | grep -qx "$VOLUME"; then
|
||||
echo "unauthorized runtime has the control-plane credential mount" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "machine credential mount topology verified"
|
||||
@@ -1 +1 @@
|
||||
{"task_file":"dev/tasks/GEN2-COGNITIVE-003-restore-local-medium-invocation.json","task_id":"GEN2-COGNITIVE-003","task_revision":3}
|
||||
{"task_file":"dev/tasks/GEN2-DEPLOY-004-candidate-commit-runtime-releaseset.json","task_id":"GEN2-DEPLOY-004","task_revision":2}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"task_id": "GEN2-AUTHORITY-001",
|
||||
"task_revision": 3,
|
||||
"architecture_revision": "ARCH-GEN2-000",
|
||||
"base_repo_revision": "gen2-integration",
|
||||
"risk_tier": "E",
|
||||
"intent": "Add a bounded, non-interactive service-principal and task-scoped delegated Authority path for existing governed Cognitive binding lifecycle operations without browser impersonation, a second Authority owner, or direct Capability mutation.",
|
||||
"requirement_ids": ["REQ-GEN2-AUTHORITY-001-DELEGATED-CONTROL-PLANE", "REQ-GEN2-COGNITIVE-003-Q8-Q17"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["Identity service principal bootstrap", "Authority delegated grant validation and audit", "Core composition and typed control-plane endpoint", "existing Capability lifecycle invocation", "production secret-reference wiring", "targeted evidence"],
|
||||
"paths": ["architecture/adrs/ADR-0021-delegated-noninteractive-control-plane-authority.md", "contracts/authority/types.go", "contracts/authority/control_plane.go", "contracts/authority/*_test.go", "contracts/secrets/types.go", "modules/authority/domain/**", "modules/authority/application/**", "modules/authority/ports/**", "adapters/postgres/authority_repository.go", "adapters/postgres/authority_repository_test.go", "cmd/core-runtime/main.go", "cmd/core-runtime/control_plane_authority.go", "cmd/core-runtime/control_plane_authority_test.go", "cmd/commit-runtime/main.go", "cmd/commit-runtime/control_plane_authority.go", "cmd/commit-runtime/control_plane_authority_test.go", "database/migrations/056_delegated_control_plane_authority.sql", "deploy/docker-compose.prod.yml", "deploy/docker-compose.candidate-slot.yml", "docs/CREDENTIALS_AND_SECRETS.md", "docs/evidence/**", "docs/PROJECT_STATUS.md", "development/GEN2_TASK_INDEX.md", "dev/ACTIVE_TASK.json", "dev/tasks/GEN2-AUTHORITY-001-delegated-noninteractive-control-plane-authority.json"]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": ["architecture/ARCHITECTURE_CONSTITUTION.md", "architecture/architecture-registry.yaml", "architecture/architecture-registry.json", "cmd/devctl/**", "contracts/identity/**", "modules/identity/**", "adapters/postgres/identity_repository.go", "contracts/capability/**", "modules/capability/**", "adapters/postgres/capability_repository.go", "cmd/cognitive-worker/**", "database/bootstrap/**", "security/**", "go.mod", "go.sum", "UI", "V1 retirement", "GEN2-EVOLVE-005", "Gen3/**"]
|
||||
},
|
||||
"allowed_architecture_delta": {"new_cross_module_dependencies": 1, "new_canonical_owners": 0, "new_privileges": 1, "new_third_party_dependencies": 0, "new_database_owner_roles": 1},
|
||||
"contracts": {"consume": ["existing Identity Actor/PrincipalBinding", "existing Capability cognitive promotion requests/builders", "existing CredentialRef file resolver"], "may_change": ["typed Authority delegated-grant and audit contract", "typed secret purpose for service authentication"]},
|
||||
"semantic_owner": "Identity remains the sole owner of service identity. Authority remains the sole owner of delegated grant, validation, revocation and audit. Capability remains the sole owner of cognitive binding/evaluation lifecycle.",
|
||||
"canonical_state": ["service authentication is distinct from delegated authority", "delegation is task/capability/resource/time scoped and default-deny", "service principal cannot issue, extend, revoke or broaden its own authority", "Capability activation continues to require independent evaluation and owner-local lifecycle validation", "audit contains no secret or user payload"],
|
||||
"state_transitions": ["service credential authentication -> delegated grant validation -> existing Capability CANARY/ACTIVE validation -> owner-local lifecycle persistence -> Authority audit", "grant ACTIVE -> REVOKED/EXPIRED denies new privileged actions while retaining audit history"],
|
||||
"side_effects_and_privileges": ["Core receives only an Authority CredentialRef and service authentication SecretRef through the protected file backend", "the positive new_privileges and new_database_owner_roles values are devctl compatibility gates for deploy/database surfaces; no new role, broad administrator privilege, or ownership change is granted", "no external effect bypasses Commit/Executor where those owners already govern it"],
|
||||
"persistence_and_migrations": ["additive owner-local Authority tables only; seed exactly one bounded service identity and GEN2-COGNITIVE-003 grant through owner roles", "historical audit is retained on rollback"],
|
||||
"failure_retry_restart": ["authentication or validation failure is fail-closed", "grant state is read durably on each request", "no in-memory permission cache", "revocation prevents new actions immediately", "existing Capability revision preconditions prevent replay or duplicate promotion"],
|
||||
"assumptions": ["the protected assistant_core_secrets control plane can materialize a non-empty control-plane service credential without exposing its value", "the current production schema has migrations through 055", "the owner decision authorizes a bounded GEN2-COGNITIVE-003 grant only, not future task grants"],
|
||||
"acceptance_scenarios": ["valid grant permits only its declared Cognitive lifecycle operation and binding revision", "different binding, missing grant, expired grant and revoked grant are denied", "service principal cannot create or extend grants", "restart uses durable grant state", "audit is recorded without payload/secret", "browser session is not required", "existing independent Capability evaluation remains a mandatory promotion precondition"],
|
||||
"required_tests": ["targeted go test", "targeted go vet", "migration/compose validation", "preflight", "check-diff", "independent", "architecture/security MILESTONE", "git diff --check"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT", "REQUIRES_MIGRATION_DECISION"]
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"task_id": "GEN2-DEPLOY-004",
|
||||
"task_revision": 2,
|
||||
"architecture_revision": "ARCH-GEN2-000",
|
||||
"base_repo_revision": "gen2-integration",
|
||||
"risk_tier": "E",
|
||||
"intent": "Close the isolated candidate slot over all versioned Assistant runtime dependencies of its candidate components, extend the typed Supervisor ReleaseSet accordingly, and keep stable containers untouched so the delegated Authority path can be accepted without candidate-to-stable runtime shortcuts.",
|
||||
"requirement_ids": ["REQ-GEN2-DEPLOY-004-DEPENDENCY-CLOSURE", "REQ-GEN2-DEPLOY-004-CANDIDATE-COMMIT", "REQ-GEN2-AUTHORITY-001-ISOLATED-COMMIT", "REQ-GEN2-DEPLOY-003-STABLE-ID-GUARD"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["deployment control", "runtime supervisor", "candidate Assistant runtime dependency closure", "inherited delegated Authority prerequisite only"],
|
||||
"paths": [
|
||||
"deploy/docker-compose.candidate-slot.yml",
|
||||
"deploy/run-production-canary.sh",
|
||||
"runtime/supervisor/**",
|
||||
"cmd/supervisor/**",
|
||||
"tests/deployment/**",
|
||||
"docs/evidence/**",
|
||||
"docs/DEPLOYMENT.md",
|
||||
"docs/PROJECT_STATUS.md",
|
||||
"development/GEN2_TASK_INDEX.md",
|
||||
"dev/ACTIVE_TASK.json",
|
||||
"dev/tasks/GEN2-DEPLOY-004-candidate-commit-runtime-releaseset.json",
|
||||
"architecture/adrs/ADR-0021-delegated-noninteractive-control-plane-authority.md",
|
||||
"contracts/authority/types.go",
|
||||
"contracts/authority/control_plane.go",
|
||||
"contracts/authority/*_test.go",
|
||||
"contracts/secrets/types.go",
|
||||
"modules/authority/domain/**",
|
||||
"modules/authority/application/**",
|
||||
"modules/authority/ports/**",
|
||||
"adapters/postgres/authority_repository.go",
|
||||
"adapters/postgres/authority_repository_test.go",
|
||||
"cmd/core-runtime/main.go",
|
||||
"cmd/core-runtime/control_plane_authority.go",
|
||||
"cmd/core-runtime/control_plane_authority_test.go",
|
||||
"cmd/commit-runtime/main.go",
|
||||
"cmd/commit-runtime/control_plane_authority.go",
|
||||
"cmd/commit-runtime/control_plane_authority_test.go",
|
||||
"database/migrations/056_delegated_control_plane_authority.sql",
|
||||
"deploy/docker-compose.prod.yml",
|
||||
"docs/CREDENTIALS_AND_SECRETS.md",
|
||||
"dev/tasks/GEN2-AUTHORITY-001-delegated-noninteractive-control-plane-authority.json"
|
||||
]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": ["architecture/ARCHITECTURE_CONSTITUTION.md", "architecture/architecture-registry.yaml", "architecture/architecture-registry.json", "cmd/devctl/**", "contracts/identity/**", "modules/identity/**", "adapters/postgres/identity_repository.go", "contracts/capability/**", "modules/capability/**", "adapters/postgres/capability_repository.go", "cmd/cognitive-worker/**", "database/bootstrap/**", "security/**", "go.mod", "go.sum", "UI", "V1 retirement", "GEN2-EVOLVE-005", "Gen3/**"]
|
||||
},
|
||||
"allowed_architecture_delta": {"new_cross_module_dependencies": 1, "new_canonical_owners": 0, "new_privileges": 1, "new_third_party_dependencies": 0, "new_database_owner_roles": 1},
|
||||
"contracts": {
|
||||
"consume": ["existing typed Supervisor ReleaseSet and ComponentRelease", "existing runtime health/readiness/revision endpoints", "existing delegated Authority service credential and task-scoped grant contracts", "existing shared PostgreSQL and external secret volumes"],
|
||||
"may_change": ["typed Supervisor explicit required ComponentKind set and ReleaseSet evidence", "candidate Compose dependency wiring", "candidate deployment control script"]
|
||||
},
|
||||
"semantic_owner": "Operations/Supervisor owns operational ReleaseSet evidence; Commit remains the sole canonical owner of durable Commit state; Authority and Capability ownership do not change.",
|
||||
"canonical_state": ["stable and candidate instances of each owner use the same transactional canonical repository and do not form two semantic owners", "no direct stable container recreation", "no new canonical writer, schema, role, credential value, or provider routing owner", "pre-existing GEN2-AUTHORITY-001 paths are inherited only so devctl can validate the committed prerequisite diff against gen2-integration; this packet grants no new write authority for them"],
|
||||
"state_transitions": ["stable dependency-closed ReleaseSet evidence retained -> isolated candidate dependency closure start -> all component health/readiness/revision and dependency-target observation -> Supervisor canary -> promote or whole ReleaseSet rollback", "missing, unhealthy, mixed-revision, or stable-targeted candidate component -> candidate ReleaseSet unhealthy -> traffic stable without stable container recreation"],
|
||||
"side_effects_and_privileges": ["production operations are limited to Docker/Compose candidate slot B and Supervisor control endpoints", "candidate Creator, Core, Commit, Continuity, Agent Worker, Agent Execution Bridge, Work Graph and Task Verifier use only candidate Assistant runtime URLs", "PostgreSQL, protected secret volumes, model/gateway services and other explicitly classified non-Assistant infrastructure remain shared", "candidate components receive only required existing SecretRefs through read-only protected mounts", "stable IDs are captured before every candidate operation and any change aborts before canary"],
|
||||
"persistence_and_migrations": ["no migration or durable semantic schema change", "shared PostgreSQL and existing protected volumes remain external resources and are never deleted", "Supervisor persists stable/candidate/LKG ReleaseSet evidence across restart"],
|
||||
"failure_retry_restart": ["missing, unhealthy, revision-mismatched, or stable-targeted candidate component rejects the whole candidate ReleaseSet", "rollback changes Supervisor traffic only and retains stable containers", "Supervisor restart reloads the complete dependency-closed LKG and candidate state", "candidate and stable owner runtimes rely on existing repository idempotency/revision preconditions for bounded test resources"],
|
||||
"assumptions": ["GEN2-AUTHORITY-001 implementation commits through a8be998 remain unmodified prerequisites on this task branch", "the protected control-plane secret artifact exists and can be mounted read-only without displaying it", "existing owner repositories support concurrent stable/candidate instances over bounded test resources", "any runtime target absent from the static configuration graph is classified before it is admitted as shared infrastructure"],
|
||||
"acceptance_scenarios": ["candidate ReleaseSet contains the transitive closure of creator-web, core-runtime, cognitive-worker, research-runtime, commit-runtime, continuity-runtime, agent-worker, agent-execution-bridge, work-graph-runtime, and task-verifier, each at one revision", "every candidate Assistant runtime URL targets a component in the same candidate ReleaseSet; stable Assistant runtime URLs abort before canary", "missing, unhealthy, or revision-mismatched required component prevents release READY", "candidate Core -> Commit -> Continuity and Creator -> Continuity/Agent Worker remain within candidate topology while stable topology is unchanged", "candidate start/update leaves every captured stable Assistant runtime container ID unchanged", "forced candidate Continuity or Commit failure causes whole ReleaseSet rollback to stable traffic without recreating stable", "Supervisor restart preserves the complete component set in LKG and candidate evidence", "Commit readiness proves database and Authority endpoint readiness without emitting a secret"],
|
||||
"required_tests": ["FAST: targeted go test ./runtime/supervisor ./cmd/supervisor", "FAST: targeted go vet ./runtime/supervisor ./cmd/supervisor", "FAST: compose config candidate slot", "FAST: targeted deployment shell regression for dependency isolation and stable ID invariance", "FAST governance: go run ./cmd/devctl preflight -active dev/ACTIVE_TASK.json", "FAST scope: go run ./cmd/devctl check-diff -active dev/ACTIVE_TASK.json", "FAST independent: go run ./cmd/devctl/independent", "FAST whitespace: git diff --check gen2-integration --", "PRODUCTION: isolated dependency-closed ReleaseSet health, revision, candidate Continuity/Commit rollback, Supervisor restart/LKG, and stable-ID drill"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_DEPLOYMENT_CONTROL", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT", "REQUIRES_MIGRATION_DECISION"]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"task_id": "GEN2-SECRETS-001",
|
||||
"task_revision": 2,
|
||||
"architecture_revision": "ARCH-GEN2-000",
|
||||
"base_repo_revision": "gen2-integration",
|
||||
"risk_tier": "E",
|
||||
"intent": "Provide an idempotent, local-only, cryptographically secure machine-credential provisioner and rotation mechanism on the existing protected Docker secret control plane, initially for the delegated control-plane service token, without creating a second semantic owner or exposing a secret value.",
|
||||
"requirement_ids": ["REQ-GEN2-SECRETS-001-LOCAL-MACHINE-CREDENTIALS", "REQ-GEN2-AUTHORITY-001-DELEGATED-CONTROL-PLANE"],
|
||||
"allowed_change_scope": {
|
||||
"modules": ["technical protected secret file backend", "production deployment/bootstrap secret provisioning", "targeted Core/Commit service-authentication mount wiring", "targeted tests and evidence"],
|
||||
"paths": ["platform/secrets/**", "contracts/secrets/types.go", "cmd/secret-control-plane/**", "cmd/core-runtime/main.go", "cmd/commit-runtime/control_plane_authority.go", "deploy/images/runtime.Dockerfile", "deploy/docker-compose.prod.yml", "deploy/docker-compose.candidate-slot.yml", "deploy/provision-machine-credential.sh", "deploy/provision-machine-credential_test.sh", "deploy/verify-machine-credential.sh", "docs/CREDENTIALS_AND_SECRETS.md", "docs/evidence/**", "development/GEN2_TASK_INDEX.md", "dev/ACTIVE_TASK.json", "dev/tasks/GEN2-SECRETS-001-local-machine-credential-provisioning.json"]
|
||||
},
|
||||
"forbidden_change_scope": {
|
||||
"paths": ["architecture/ARCHITECTURE_CONSTITUTION.md", "architecture/architecture-registry.yaml", "architecture/architecture-registry.json", "cmd/devctl/**", "contracts/authority/**", "modules/authority/**", "adapters/postgres/**", "database/**", "modules/identity/**", "modules/capability/**", "cmd/cognitive-worker/**", "cmd/creator-web/**", "UI", "V1 retirement", "GEN2-EVOLVE-005", "Gen3/**", "go.mod", "go.sum"]
|
||||
},
|
||||
"allowed_architecture_delta": {"new_cross_module_dependencies": 0, "new_canonical_owners": 0, "new_privileges": 1, "new_third_party_dependencies": 0, "new_database_owner_roles": 0},
|
||||
"contracts": {"consume": ["existing CredentialRef and FileResolver", "existing Docker protected-volume deployment mechanism"], "may_change": ["typed SecretPurpose/consumer metadata only if required for the provisioner"]},
|
||||
"semantic_owner": "No new semantic owner is introduced. platform/secrets remains a technical bootstrap/resolution mechanism; Identity, Authority, Capability and Configuration ownership remain unchanged.",
|
||||
"canonical_state": ["credential values live only in protected local artifacts, never in Configuration, Memory, context, PostgreSQL, Compose environment, Git, logs or evidence", "machine authentication is distinct from Authority grants", "metadata/audit is separate from the value and contains no plaintext or reversible material", "the control-plane token is mounted read-only only to Core and Commit runtimes"],
|
||||
"state_transitions": ["ABSENT -> ACTIVE version one via idempotent CSPRNG provisioning", "ACTIVE -> ROTATING -> ACTIVE new version after atomic artifact replacement and controlled verification", "ACTIVE -> COMPROMISED/REVOKED -> replacement version with audit retained"],
|
||||
"side_effects_and_privileges": ["a one-shot local control-plane container may create or rotate only its dedicated external Docker volume", "Core and Commit get read-only mounts; all other runtimes receive no mount", "no plaintext environment variable is added"],
|
||||
"persistence_and_migrations": ["no application database schema or canonical writer changes", "secret metadata and append-only audit reside separately from the secret value inside the protected control-plane volume", "rollback retains prior metadata and revokes only after a verified replacement"],
|
||||
"failure_retry_restart": ["restart is idempotent and preserves the active artifact", "partial writes are avoided by atomic replacement", "a missing or unreadable artifact fails service authentication closed", "rotation never emits a credential and leaves a valid active artifact on failure"],
|
||||
"assumptions": ["docker.cin.su permits creation of a dedicated external Docker volume by the existing production deployment control plane", "the runtime image can execute a one-shot local provisioner as the control-plane writer", "the existing protected secret volume pattern is the approved production mechanism"],
|
||||
"acceptance_scenarios": ["missing credential is generated once with crypto/rand and then reused across restart", "metadata and audit are separate from the value", "Core and Commit mounts are read-only and no other runtime mounts the dedicated token volume", "rotation accepts the new credential and rejects the old credential", "logs and diagnostics redact known secret headers/fields", "a valid service credential alone does not bypass the existing delegated Authority grant checks"],
|
||||
"required_tests": ["targeted go test ./platform/secrets ./cmd/secret-control-plane", "targeted go vet ./platform/secrets ./cmd/secret-control-plane", "compose config validation", "provisioner shell regression", "preflight", "check-diff", "independent", "git diff --check"],
|
||||
"terminal_gap_states": ["BLOCKED_BY_ARCHITECTURE_GAP", "BLOCKED_BY_SPEC_GAP", "BLOCKED_BY_MISSING_CAPABILITY", "BLOCKED_BY_CONFLICT", "REQUIRES_MIGRATION_DECISION"]
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
# DOMOVOY Gen2 — Task Index
|
||||
|
||||
## GEN2-SECRETS-001 — Local Machine Credential Provisioning & Rotation
|
||||
|
||||
Bounded post-M5 remediation. Provides the technical protected-secret control-plane mechanism required by `GEN2-AUTHORITY-001`; it does not change semantic ownership or grant Authority.
|
||||
|
||||
Это исполняемый индекс task packets. `ARCH-GEN2-000` соответствует разделу `GEN2-000` Master Plan: префикс `ARCH-` нужен текущему `devctl`, чтобы последующие packets могли ссылаться на него через `architecture_revision`.
|
||||
|
||||
| Порядок | Task | Milestone | Gate | Base ref | Зависимость | Файл |
|
||||
@@ -48,4 +52,11 @@
|
||||
- **M6 retirement:** `GEN2-029` — FULL before irreversible retirement.
|
||||
- **M6 final:** `GEN2-030` — FULL final acceptance.
|
||||
|
||||
## Bounded post-M5 remediation
|
||||
|
||||
| Task | Gate | Depends on | Purpose |
|
||||
|---|---|---|---|
|
||||
| `GEN2-AUTHORITY-001` | `MILESTONE` | owner decision, existing Identity/Authority/Capability lifecycle | Bounded non-interactive service principal and task-scoped control-plane delegation; does not retire V1 or change Gen2 canonical ownership. |
|
||||
| `GEN2-DEPLOY-004` | `MILESTONE` | GEN2-DEPLOY-003, GEN2-AUTHORITY-001 implementation | Extend the isolated candidate slot and typed Supervisor ReleaseSet with Commit runtime before delegated Authority acceptance; stable containers are never recreated by candidate operations. |
|
||||
|
||||
Между реперными точками выполняется только FAST-профиль конкретного packet-а.
|
||||
|
||||
@@ -23,6 +23,10 @@ Each privileged runtime gets only its required secret/capability bindings. `comm
|
||||
|
||||
The Core SELF learning repository uses the existing `assistant_core_secrets` volume and credential-reference mechanism with `self_role` and `credential://domovoy/self/db-password/v1`. The secret is consumed from the fixed `/run/secrets/self_db_password` path; its value is never placed in Compose environment, Git, logs or ordinary configuration. The role and schema already exist; this wiring does not create a role or broaden privileges.
|
||||
|
||||
Delegated non-interactive control-plane work is separately authenticated. The local `secret-control-plane` one-shot control-plane service provisions `control_plane_service_token` with `crypto/rand` into the dedicated external `assistant_control_plane_service_secrets` volume. The token artifact is mode `0400`; metadata and audit are separate protected files and contain no value or reversible fingerprint. Only `core-runtime` and the existing Authority/Commit runtime mount that volume read-only at `/run/control-plane-secrets`; no model, Skill, SELF, creator-web, cognitive-worker or research-runtime receives the mount. Compose carries only the non-secret credential reference `credential://domovoy/control-plane/service-token/v1`.
|
||||
|
||||
The provisioner is idempotent: restart reuses an existing safe active artifact. Rotation creates a new value by atomic replacement, records non-secret metadata/audit, and never accepts a plaintext environment variable. The service token is not a Creator session, cannot impersonate a human, and never grants Authority by itself. Removing or rotating the token disables/refreshes service authentication; revoking the durable Authority grant also blocks new delegated operations without deleting audit history.
|
||||
|
||||
Creator authentication secrets are stored in the external Docker volume `assistant_core_secrets` and mounted read-only only at `/run/secrets` in `core-runtime`. The production container environment contains `_FILE` paths, not the secret values. Files are owned by runtime uid 100/gid 101 with mode 0400. `CREATOR_USERNAME` is not secret and remains an environment value. Development may continue to use direct environment values, but a direct value and its matching `_FILE` setting must never be configured together.
|
||||
|
||||
The PostgreSQL off-host backup passphrase is generated randomly and stored as CurrentUser DPAPI ciphertext at `%LOCALAPPDATA%\Domovoy\postgres-backup-key.dpapi.json`. An atomic copy of that DPAPI ciphertext, never the plaintext passphrase, is retained at `\\nas\MST\codex\_backups\domovoy\keys\postgres-backup-key.dpapi.json`. The passphrase is never stored in Git, the production Docker host, a scheduled-task argument, or NAS plaintext. The NAS backup directory receives only GnuPG AES-256 ciphertext and a non-secret integrity manifest. Recovery therefore requires both the NAS artifacts and the authorized Windows DPAPI profile.
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# GEN2-AUTHORITY-001 — delegated control-plane deployment evidence
|
||||
|
||||
Date: 2026-08-31
|
||||
|
||||
The former missing-credential prerequisite is resolved by
|
||||
`GEN2-SECRETS-001`. A local one-shot provisioner created the dedicated
|
||||
protected artifact and verified idempotent ensure/rotation without reading or
|
||||
emitting its value. Core and Commit are wired to resolve it from the dedicated
|
||||
read-only mount, not the shared secret volume.
|
||||
|
||||
## Implemented and verified locally
|
||||
|
||||
The bounded implementation is present on branch
|
||||
`gen2/authority-001-delegated-control-plane`. It keeps Identity as the service
|
||||
identity owner, Authority as the durable grant/revocation/audit owner, and
|
||||
Capability as the cognitive lifecycle owner. Core is an Authority-runtime
|
||||
client; the Authority endpoint is served by the existing Commit runtime that
|
||||
already owns the Authority repository in the V2 runtime topology.
|
||||
|
||||
On 2026-08-31 the following checks completed successfully without secret
|
||||
values:
|
||||
|
||||
- targeted `go test` for Authority contracts/domain, secret resolver, Core,
|
||||
Commit runtime, and the Authority PostgreSQL adapter;
|
||||
- targeted `go vet` for the same packages;
|
||||
- production and candidate Compose static validation;
|
||||
- task preflight, diff scope, independent governance, and architecture checks;
|
||||
- `git diff --check`.
|
||||
|
||||
## Current deployment-control gap
|
||||
|
||||
No delegated lifecycle operation has been attempted in production.
|
||||
|
||||
On 2026-08-31 the stable Core and Commit runtimes both reported release
|
||||
revision `2ee5da81145cdad2da1c92c24a91145ad4af61a5`. The existing candidate
|
||||
slot script declares exactly four components: Creator Web, Core, Cognitive
|
||||
Worker, and Research Runtime. It has no candidate Commit runtime.
|
||||
|
||||
The Authority endpoint is intentionally served by Commit runtime. Therefore a
|
||||
candidate Core cannot perform a real delegated Authority request against the
|
||||
required matching candidate Commit runtime without either recreating stable
|
||||
Commit (forbidden) or extending the candidate ReleaseSet/Supervisor contract
|
||||
to contain Commit as an independently healthy and rollback-aware component.
|
||||
|
||||
This is `BLOCKED_BY_SPEC_GAP`, not a credential or implementation failure. A
|
||||
new explicit packet/revision must authorize the minimum deployment paths:
|
||||
`deploy/docker-compose.candidate-slot.yml`, `deploy/run-production-canary.sh`,
|
||||
and the Supervisor release-set contract/tests if its fixed four-component
|
||||
schema must change. The change must define Commit candidate health, revision
|
||||
consistency, traffic/promotion behavior, and whole-ReleaseSet rollback.
|
||||
@@ -0,0 +1,60 @@
|
||||
# GEN2-DEPLOY-004 r2 — candidate dependency-closure finding
|
||||
|
||||
## Decision and graph evidence
|
||||
|
||||
The owner-approved r2 rule requires every versioned Assistant runtime reached
|
||||
by normal candidate operation to be in the candidate ReleaseSet. Static
|
||||
runtime configuration establishes this candidate closure:
|
||||
|
||||
```text
|
||||
creator-web -> core-runtime, continuity-runtime, commit-runtime,
|
||||
cognitive-worker, agent-worker
|
||||
core-runtime -> cognitive-worker, research-runtime, continuity-runtime,
|
||||
commit-runtime
|
||||
commit-runtime -> core-runtime, continuity-runtime
|
||||
continuity-runtime -> core-runtime, commit-runtime
|
||||
agent-worker -> task-verifier, agent-execution-bridge
|
||||
agent-execution-bridge -> cognitive-worker, work-graph-runtime, task-verifier
|
||||
work-graph-runtime -> core-runtime
|
||||
```
|
||||
|
||||
Therefore the static closure is: Creator Web, Core Runtime, Cognitive Worker,
|
||||
Research Runtime, Commit Runtime, Continuity Runtime, Agent Worker, Agent
|
||||
Execution Bridge, Work Graph Runtime, and Task Verifier.
|
||||
|
||||
PostgreSQL, protected secret volumes, the local model gateway/lifeboat, and
|
||||
the configured web-search endpoint are classified as shared durable
|
||||
infrastructure or shared external services. They do not contain an Assistant
|
||||
semantic/runtime release revision.
|
||||
|
||||
## Blocking dynamic dependency
|
||||
|
||||
Commit's normal prospective-notification operation obtains the exact active
|
||||
notification Capability binding from Core. The binding's immutable
|
||||
`HTTPSOrigin`, delivery path, and revision select the receiver. This is not a
|
||||
Compose environment URL and cannot be safely redirected by a container alias.
|
||||
|
||||
Consequently, with the existing active binding, a candidate Commit executing a
|
||||
normal notification operation would call the stable notification receiver. A
|
||||
candidate notification-receiver container alone does not solve the problem:
|
||||
the candidate would still resolve the stable binding. Reusing the stable name
|
||||
would create ambiguous network routing, and changing the active binding would
|
||||
mutate Capability-owned canonical state.
|
||||
|
||||
No runtime, Capability state, migration, secret, or production container was
|
||||
changed while establishing this finding.
|
||||
|
||||
## Required owner decision
|
||||
|
||||
Choose one governed boundary before DEPLOY-004 implementation can prove full
|
||||
dependency isolation:
|
||||
|
||||
1. authorize a bounded Capability-owned candidate binding/shadow-binding
|
||||
lifecycle, including its authority, rollback and selection semantics; or
|
||||
2. explicitly classify the notification receiver as a shared external service
|
||||
for this ReleaseSet, despite it being an Assistant-managed runtime.
|
||||
|
||||
The first option requires a new packet revision with the exact Capability
|
||||
contract/owner paths. The second changes the release-boundary policy and must
|
||||
be accepted explicitly. No direct binding update, stable alias reuse, or
|
||||
candidate-to-stable shortcut is an acceptable substitute.
|
||||
@@ -0,0 +1,53 @@
|
||||
# GEN2-SECRETS-001 — local machine credential provisioning
|
||||
|
||||
Date: 2026-08-31
|
||||
|
||||
## Design evidence
|
||||
|
||||
`platform/secrets` is the existing technical protected-file mechanism. This
|
||||
task extends it without adding a semantic Secrets owner, a database table, or
|
||||
a Configuration/Memory writer.
|
||||
|
||||
The dedicated Docker volume is named
|
||||
`assistant_control_plane_service_secrets`. Its sole writer is the one-shot
|
||||
`secret-control-plane` control-plane container. Its only consumers are
|
||||
`core-runtime` and `commit-runtime`, mounted read-only at
|
||||
`/run/control-plane-secrets`. The metadata directory is distinct from the
|
||||
token artifact and records purpose, owner, version, consumers, status,
|
||||
generation method, and non-secret audit actions only.
|
||||
|
||||
The provisioner uses `crypto/rand`, writes via an atomic file replacement,
|
||||
and has no plaintext environment input. It reports only safe operation status.
|
||||
The data policy marks the artifact as not indexable, embeddable, retrievable,
|
||||
or model-visible.
|
||||
|
||||
## Local FAST evidence
|
||||
|
||||
The following checks completed successfully before production execution:
|
||||
|
||||
- targeted `go test ./platform/secrets ./cmd/secret-control-plane`;
|
||||
- targeted `go vet ./platform/secrets ./cmd/secret-control-plane`;
|
||||
- POSIX shell regression for the provisioning wrapper, executed under Git
|
||||
Bash because the Windows WSL shim cannot translate the mapped workspace;
|
||||
- static Docker Compose validation for production and candidate files.
|
||||
|
||||
No credential value, fingerprint, length, header, or plaintext environment
|
||||
value was read, printed, copied, committed, or included in this evidence.
|
||||
|
||||
## Production control-plane evidence
|
||||
|
||||
The one-shot provisioner was run from a detached `gen2-integration` worktree
|
||||
on `docker.cin.su`. It created the dedicated external volume and provisioned
|
||||
the credential once. A repeat `ensure` reported that the already active
|
||||
artifact was reused. A bounded owner-requested rotation then completed.
|
||||
|
||||
For creation, idempotent ensure, and rotation, the stable Core, Commit,
|
||||
Creator Web, Cognitive Worker, and Research Runtime container identities were
|
||||
recorded before and after the one-shot operation and were unchanged. The
|
||||
verification checked only artifact and separate metadata/audit file presence;
|
||||
it did not read their content.
|
||||
|
||||
At this point the credential is provisioned but not yet used by the stable
|
||||
runtime. Consumer mount and service-authentication acceptance are completed
|
||||
only when `GEN2-AUTHORITY-001` is merged and deployed as its own controlled
|
||||
candidate ReleaseSet.
|
||||
@@ -0,0 +1,34 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"slices"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
var ErrDelegatedAuthorityDenied = errors.New("delegated control-plane authority denied")
|
||||
|
||||
// ValidateDelegatedControlPlaneGrant proves only the Authority-owned decision.
|
||||
// It does not replace the receiving semantic owner's lifecycle preconditions.
|
||||
func ValidateDelegatedControlPlaneGrant(nowUnixMillis int64, binding identity.PrincipalBinding, grant authority.DelegatedControlPlaneGrant, request authority.DelegatedControlPlaneRequest) error {
|
||||
if nowUnixMillis < 1 || binding.ActorID == "" || binding.PrincipalID == "" || !binding.Active ||
|
||||
grant.ID == "" || grant.Revision < 1 || grant.Status != authority.DelegatedGrantActive ||
|
||||
grant.ServiceActorID != binding.ActorID || grant.ServicePrincipalID != binding.PrincipalID ||
|
||||
grant.IssuerPrincipalID == "" || grant.ArchitectureRevision == "" || grant.Nonce == "" ||
|
||||
grant.IssuedAtUnixMillis < 1 || grant.ExpiresAtUnixMillis <= grant.IssuedAtUnixMillis || nowUnixMillis < grant.IssuedAtUnixMillis || nowUnixMillis >= grant.ExpiresAtUnixMillis || !RequestMatchesDelegatedControlPlaneGrant(grant, request) {
|
||||
return ErrDelegatedAuthorityDenied
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func RequestMatchesDelegatedControlPlaneGrant(grant authority.DelegatedControlPlaneGrant, request authority.DelegatedControlPlaneRequest) bool {
|
||||
return grant.TaskID != "" && grant.TaskID == request.TaskID && grant.TaskRevision > 0 && grant.TaskRevision == request.TaskRevision &&
|
||||
request.GrantID == grant.ID && request.Operation != "" && slices.Contains(grant.Operations, request.Operation) &&
|
||||
grant.Resource.BindingID != "" && grant.Resource.ProviderInstanceID != "" && grant.Resource.ModelDescriptorID != "" && grant.Resource == request.Resource
|
||||
}
|
||||
|
||||
func CanIssuerRevokeDelegatedGrant(issuer identity.PrincipalID, grant authority.DelegatedControlPlaneGrant) bool {
|
||||
return issuer != "" && issuer == grant.IssuerPrincipalID && grant.Status == authority.DelegatedGrantActive
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"git.cin.su/m/Assistant/contracts/authority"
|
||||
"git.cin.su/m/Assistant/contracts/identity"
|
||||
)
|
||||
|
||||
func delegatedGrant() authority.DelegatedControlPlaneGrant {
|
||||
return authority.DelegatedControlPlaneGrant{ID: "grant-1", ServiceActorID: "service-actor", ServicePrincipalID: "service-principal", IssuerPrincipalID: "owner", TaskID: "GEN2-COGNITIVE-003", TaskRevision: 4, Operations: []authority.DelegatedControlPlaneOperation{authority.DelegatedOperationCanaryCognitiveBinding}, Resource: authority.CognitiveBindingResource{BindingID: "binding-1", ProviderInstanceID: "provider-1", ModelDescriptorID: "model-1"}, IssuedAtUnixMillis: 10, ExpiresAtUnixMillis: 100, ArchitectureRevision: "ADR-0021", Nonce: "nonce", Revision: 1, Status: authority.DelegatedGrantActive}
|
||||
}
|
||||
|
||||
func TestDelegatedControlPlaneGrantIsExactAndTimeBound(t *testing.T) {
|
||||
grant := delegatedGrant()
|
||||
binding := identity.PrincipalBinding{ActorID: "service-actor", PrincipalID: "service-principal", Active: true}
|
||||
request := authority.DelegatedControlPlaneRequest{GrantID: grant.ID, TaskID: grant.TaskID, TaskRevision: grant.TaskRevision, Operation: authority.DelegatedOperationCanaryCognitiveBinding, Resource: grant.Resource}
|
||||
if err := ValidateDelegatedControlPlaneGrant(20, binding, grant, request); err != nil {
|
||||
t.Fatalf("valid delegation denied: %v", err)
|
||||
}
|
||||
request.Resource.BindingID = "other"
|
||||
if err := ValidateDelegatedControlPlaneGrant(20, binding, grant, request); err == nil {
|
||||
t.Fatal("different resource was allowed")
|
||||
}
|
||||
request.Resource = grant.Resource
|
||||
if err := ValidateDelegatedControlPlaneGrant(100, binding, grant, request); err == nil {
|
||||
t.Fatal("expired grant was allowed")
|
||||
}
|
||||
grant.Status = authority.DelegatedGrantRevoked
|
||||
if err := ValidateDelegatedControlPlaneGrant(20, binding, grant, request); err == nil {
|
||||
t.Fatal("revoked grant was allowed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDelegatedGrantCannotSelfRevokeOrBroaden(t *testing.T) {
|
||||
grant := delegatedGrant()
|
||||
if CanIssuerRevokeDelegatedGrant("service-principal", grant) {
|
||||
t.Fatal("service principal may not revoke its own grant")
|
||||
}
|
||||
if !CanIssuerRevokeDelegatedGrant("owner", grant) {
|
||||
t.Fatal("issuer could not revoke active grant")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package secrets
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
secretcontracts "git.cin.su/m/Assistant/contracts/secrets"
|
||||
)
|
||||
|
||||
const (
|
||||
ControlPlaneServiceTokenID = "control_plane_service_token"
|
||||
MachineCredentialOwner = "platform.secrets.local-control-plane"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnsupportedMachineCredential = errors.New("unsupported machine credential")
|
||||
ErrCredentialArtifactUnsafe = errors.New("machine credential artifact is unsafe")
|
||||
)
|
||||
|
||||
// MachineCredentialKind describes technical credential material. It conveys no
|
||||
// authority and no secret value.
|
||||
type MachineCredentialKind string
|
||||
|
||||
const (
|
||||
MachineCredentialServiceToken MachineCredentialKind = "SERVICE_TO_SERVICE_TOKEN"
|
||||
MachineCredentialDatabaseRole MachineCredentialKind = "DATABASE_ROLE_PASSWORD"
|
||||
MachineCredentialInternalAPI MachineCredentialKind = "INTERNAL_API_CREDENTIAL"
|
||||
)
|
||||
|
||||
type MachineCredentialStatus string
|
||||
|
||||
const (
|
||||
MachineCredentialActive MachineCredentialStatus = "ACTIVE"
|
||||
MachineCredentialRotating MachineCredentialStatus = "ROTATING"
|
||||
MachineCredentialCompromised MachineCredentialStatus = "COMPROMISED"
|
||||
MachineCredentialRevoked MachineCredentialStatus = "REVOKED"
|
||||
)
|
||||
|
||||
type MachineCredentialSpec struct {
|
||||
ID string
|
||||
Kind MachineCredentialKind
|
||||
Purpose secretcontracts.SecretPurpose
|
||||
Consumers []secretcontracts.RuntimeConsumer
|
||||
Bytes int
|
||||
}
|
||||
|
||||
type MachineCredentialMetadata struct {
|
||||
SecretID string `json:"secret_id"`
|
||||
Kind MachineCredentialKind `json:"kind"`
|
||||
Purpose secretcontracts.SecretPurpose `json:"purpose"`
|
||||
Owner string `json:"owner"`
|
||||
Version int `json:"version"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
RotatedAt time.Time `json:"rotated_at,omitempty"`
|
||||
Consumers []secretcontracts.RuntimeConsumer `json:"consumers"`
|
||||
Status MachineCredentialStatus `json:"status"`
|
||||
Algorithm string `json:"algorithm"`
|
||||
GenerationMethod string `json:"generation_method"`
|
||||
DataPolicy MachineCredentialDataPolicy `json:"data_policy"`
|
||||
}
|
||||
|
||||
// MachineCredentialDataPolicy is explicit technical handling policy. It is
|
||||
// metadata only; it never contains or resolves a credential value.
|
||||
type MachineCredentialDataPolicy struct {
|
||||
Indexable bool `json:"indexable"`
|
||||
Embeddable bool `json:"embeddable"`
|
||||
Retrievable bool `json:"retrievable"`
|
||||
ModelVisible bool `json:"model_visible"`
|
||||
}
|
||||
|
||||
type MachineCredentialAudit struct {
|
||||
SecretID string `json:"secret_id"`
|
||||
Version int `json:"version"`
|
||||
Action string `json:"action"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
At time.Time `json:"at"`
|
||||
}
|
||||
|
||||
type MachineCredentialResult struct {
|
||||
Metadata MachineCredentialMetadata
|
||||
Created bool
|
||||
Rotated bool
|
||||
}
|
||||
|
||||
// LocalMachineCredentialStore is the one writer for a dedicated protected
|
||||
// volume. The value and metadata always have separate files.
|
||||
type LocalMachineCredentialStore struct {
|
||||
root string
|
||||
metadata string
|
||||
runtimeUID int
|
||||
runtimeGID int
|
||||
now func() time.Time
|
||||
random io.Reader
|
||||
}
|
||||
|
||||
func NewLocalMachineCredentialStore(root string, runtimeUID, runtimeGID int, now func() time.Time) (*LocalMachineCredentialStore, error) {
|
||||
root = strings.TrimSpace(root)
|
||||
if root == "" {
|
||||
return nil, fmt.Errorf("machine credential root: %w", ErrPathOutsideRoot)
|
||||
}
|
||||
clean, err := filepath.Abs(filepath.Clean(root))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("machine credential root: %w", err)
|
||||
}
|
||||
if now == nil {
|
||||
now = time.Now
|
||||
}
|
||||
return &LocalMachineCredentialStore{root: clean, metadata: filepath.Join(clean, ".metadata"), runtimeUID: runtimeUID, runtimeGID: runtimeGID, now: now, random: rand.Reader}, nil
|
||||
}
|
||||
|
||||
func ControlPlaneServiceTokenSpec() MachineCredentialSpec {
|
||||
return MachineCredentialSpec{
|
||||
ID: ControlPlaneServiceTokenID,
|
||||
Kind: MachineCredentialServiceToken,
|
||||
Purpose: secretcontracts.SecretPurposeServiceAuthentication,
|
||||
Consumers: []secretcontracts.RuntimeConsumer{secretcontracts.RuntimeConsumerCore, secretcontracts.RuntimeConsumerCommit},
|
||||
Bytes: 48,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) Ensure(spec MachineCredentialSpec) (MachineCredentialResult, error) {
|
||||
if err := validateMachineCredentialSpec(spec); err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
if err := s.prepareDirectories(); err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
if info, err := os.Lstat(s.artifactPath(spec)); err == nil {
|
||||
if !safeArtifact(info) {
|
||||
return MachineCredentialResult{}, ErrCredentialArtifactUnsafe
|
||||
}
|
||||
metadata, err := s.ensureMetadata(spec, false, "")
|
||||
return MachineCredentialResult{Metadata: metadata}, err
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
metadata, err := s.createVersion(spec, 1, "CREATED", "")
|
||||
if err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
return MachineCredentialResult{Metadata: metadata, Created: true}, nil
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) Rotate(spec MachineCredentialSpec, reason string) (MachineCredentialResult, error) {
|
||||
if err := validateMachineCredentialSpec(spec); err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
if err := s.prepareDirectories(); err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
current, err := s.readMetadata(spec)
|
||||
if err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
if current.Status != MachineCredentialActive {
|
||||
return MachineCredentialResult{}, fmt.Errorf("machine credential status %s cannot rotate", current.Status)
|
||||
}
|
||||
rotating := current
|
||||
rotating.Status = MachineCredentialRotating
|
||||
if err := s.writeMetadata(spec, rotating); err != nil {
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
if err := s.appendAudit(MachineCredentialAudit{SecretID: spec.ID, Version: current.Version, Action: "ROTATION_STARTED", Reason: strings.TrimSpace(reason), At: s.now().UTC()}); err != nil {
|
||||
_ = s.writeMetadata(spec, current)
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
metadata, err := s.createVersion(spec, current.Version+1, "ROTATED", strings.TrimSpace(reason))
|
||||
if err != nil {
|
||||
_ = s.writeMetadata(spec, current)
|
||||
_ = s.appendAudit(MachineCredentialAudit{SecretID: spec.ID, Version: current.Version, Action: "ROTATION_FAILED", At: s.now().UTC()})
|
||||
return MachineCredentialResult{}, err
|
||||
}
|
||||
return MachineCredentialResult{Metadata: metadata, Rotated: true}, nil
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) createVersion(spec MachineCredentialSpec, version int, action, reason string) (MachineCredentialMetadata, error) {
|
||||
value, err := randomCredential(s.random, spec.Bytes)
|
||||
if err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
if err := s.atomicArtifact(spec, value); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
now := s.now().UTC()
|
||||
metadata := MachineCredentialMetadata{SecretID: spec.ID, Kind: spec.Kind, Purpose: spec.Purpose, Owner: MachineCredentialOwner, Version: version, CreatedAt: now, Consumers: append([]secretcontracts.RuntimeConsumer(nil), spec.Consumers...), Status: MachineCredentialActive, Algorithm: "CSPRNG", GenerationMethod: "crypto/rand + base64url", DataPolicy: MachineCredentialDataPolicy{Indexable: false, Embeddable: false, Retrievable: false, ModelVisible: false}}
|
||||
if version > 1 {
|
||||
metadata.RotatedAt = now
|
||||
}
|
||||
if err := s.writeMetadata(spec, metadata); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
if err := s.appendAudit(MachineCredentialAudit{SecretID: spec.ID, Version: version, Action: action, Reason: reason, At: now}); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) ensureMetadata(spec MachineCredentialSpec, rotated bool, reason string) (MachineCredentialMetadata, error) {
|
||||
metadata, err := s.readMetadata(spec)
|
||||
if err == nil {
|
||||
return metadata, nil
|
||||
}
|
||||
if !errors.Is(err, os.ErrNotExist) {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
now := s.now().UTC()
|
||||
metadata = MachineCredentialMetadata{SecretID: spec.ID, Kind: spec.Kind, Purpose: spec.Purpose, Owner: MachineCredentialOwner, Version: 1, CreatedAt: now, Consumers: append([]secretcontracts.RuntimeConsumer(nil), spec.Consumers...), Status: MachineCredentialActive, Algorithm: "CSPRNG", GenerationMethod: "preexisting protected artifact", DataPolicy: MachineCredentialDataPolicy{Indexable: false, Embeddable: false, Retrievable: false, ModelVisible: false}}
|
||||
if rotated {
|
||||
metadata.RotatedAt = now
|
||||
}
|
||||
if err := s.writeMetadata(spec, metadata); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
if err := s.appendAudit(MachineCredentialAudit{SecretID: spec.ID, Version: metadata.Version, Action: "ADOPTED", Reason: reason, At: now}); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) prepareDirectories() error {
|
||||
if err := os.MkdirAll(s.root, 0o710); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Chmod(s.root, 0o710); err != nil {
|
||||
return err
|
||||
}
|
||||
if s.runtimeGID >= 0 && os.Geteuid() == 0 {
|
||||
if err := os.Chown(s.root, 0, s.runtimeGID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := os.MkdirAll(s.metadata, 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Chmod(s.metadata, 0o700)
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) atomicArtifact(spec MachineCredentialSpec, value string) error {
|
||||
temp, err := os.CreateTemp(s.root, ".credential-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tempPath := temp.Name()
|
||||
defer os.Remove(tempPath)
|
||||
if err := temp.Chmod(0o400); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if s.runtimeUID >= 0 && s.runtimeGID >= 0 && os.Geteuid() == 0 {
|
||||
if err := temp.Chown(s.runtimeUID, s.runtimeGID); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := temp.WriteString(value + "\n"); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Sync(); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
target := s.artifactPath(spec)
|
||||
// Windows cannot replace a read-only file. On Linux the owning runtime can
|
||||
// still read this temporary mode; the final replacement remains atomic.
|
||||
if _, err := os.Lstat(target); err == nil {
|
||||
if err := os.Chmod(target, 0o600); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tempPath, target)
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) readMetadata(spec MachineCredentialSpec) (MachineCredentialMetadata, error) {
|
||||
contents, err := os.ReadFile(s.metadataPath(spec))
|
||||
if err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
var metadata MachineCredentialMetadata
|
||||
if err := json.Unmarshal(contents, &metadata); err != nil {
|
||||
return MachineCredentialMetadata{}, err
|
||||
}
|
||||
if metadata.SecretID != spec.ID || metadata.Version < 1 || metadata.Purpose != spec.Purpose || metadata.Owner != MachineCredentialOwner {
|
||||
return MachineCredentialMetadata{}, ErrCredentialArtifactUnsafe
|
||||
}
|
||||
return metadata, nil
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) writeMetadata(spec MachineCredentialSpec, metadata MachineCredentialMetadata) error {
|
||||
contents, err := json.Marshal(metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return atomicPrivateFile(s.metadataPath(spec), contents)
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) appendAudit(audit MachineCredentialAudit) error {
|
||||
contents, err := json.Marshal(audit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
file, err := os.OpenFile(filepath.Join(s.metadata, audit.SecretID+".audit.jsonl"), os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.Write(append(contents, '\n')); err != nil {
|
||||
return err
|
||||
}
|
||||
return file.Sync()
|
||||
}
|
||||
|
||||
func (s *LocalMachineCredentialStore) artifactPath(spec MachineCredentialSpec) string {
|
||||
return filepath.Join(s.root, spec.ID)
|
||||
}
|
||||
func (s *LocalMachineCredentialStore) metadataPath(spec MachineCredentialSpec) string {
|
||||
return filepath.Join(s.metadata, spec.ID+".json")
|
||||
}
|
||||
|
||||
func randomCredential(source io.Reader, bytes int) (string, error) {
|
||||
if bytes < 32 {
|
||||
return "", fmt.Errorf("machine credential entropy must be at least 32 bytes")
|
||||
}
|
||||
value := make([]byte, bytes)
|
||||
if _, err := io.ReadFull(source, value); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(value), nil
|
||||
}
|
||||
|
||||
func validateMachineCredentialSpec(spec MachineCredentialSpec) error {
|
||||
if strings.TrimSpace(spec.ID) == "" || strings.Contains(spec.ID, "/") || spec.Bytes < 32 || len(spec.Consumers) == 0 {
|
||||
return ErrUnsupportedMachineCredential
|
||||
}
|
||||
switch spec.Kind {
|
||||
case MachineCredentialServiceToken:
|
||||
if spec.Purpose != secretcontracts.SecretPurposeServiceAuthentication {
|
||||
return ErrUnsupportedMachineCredential
|
||||
}
|
||||
case MachineCredentialDatabaseRole:
|
||||
if spec.Purpose != secretcontracts.SecretPurposeDatabasePassword {
|
||||
return ErrUnsupportedMachineCredential
|
||||
}
|
||||
case MachineCredentialInternalAPI:
|
||||
if spec.Purpose != secretcontracts.SecretPurposeServiceAuthentication && spec.Purpose != secretcontracts.SecretPurposeProviderAPIKey {
|
||||
return ErrUnsupportedMachineCredential
|
||||
}
|
||||
default:
|
||||
return ErrUnsupportedMachineCredential
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func safeArtifact(info os.FileInfo) bool {
|
||||
if !info.Mode().IsRegular() || info.Size() <= 0 {
|
||||
return false
|
||||
}
|
||||
// Windows does not preserve POSIX permissions on a temporary test volume.
|
||||
return runtime.GOOS == "windows" || info.Mode().Perm() == 0o400
|
||||
}
|
||||
|
||||
func atomicPrivateFile(path string, contents []byte) error {
|
||||
temp, err := os.CreateTemp(filepath.Dir(path), ".metadata-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tempPath := temp.Name()
|
||||
defer os.Remove(tempPath)
|
||||
if err := temp.Chmod(0o600); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := temp.Write(contents); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Sync(); err != nil {
|
||||
temp.Close()
|
||||
return err
|
||||
}
|
||||
if err := temp.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tempPath, path)
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package secrets
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
secretcontracts "git.cin.su/m/Assistant/contracts/secrets"
|
||||
)
|
||||
|
||||
func TestMachineCredentialEnsureIsIdempotentAndKeepsValueOutOfMetadata(t *testing.T) {
|
||||
now := time.Unix(1_700_000_000, 0)
|
||||
store, err := NewLocalMachineCredentialStore(t.TempDir(), -1, -1, func() time.Time { return now })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
first, err := store.Ensure(ControlPlaneServiceTokenSpec())
|
||||
if err != nil || !first.Created || first.Metadata.Version != 1 {
|
||||
t.Fatalf("first provision = %#v, %v", first, err)
|
||||
}
|
||||
second, err := store.Ensure(ControlPlaneServiceTokenSpec())
|
||||
if err != nil || second.Created || second.Metadata.Version != 1 {
|
||||
t.Fatalf("second provision = %#v, %v", second, err)
|
||||
}
|
||||
metadata, err := os.ReadFile(filepath.Join(store.metadata, ControlPlaneServiceTokenID+".json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
artifact, err := os.ReadFile(filepath.Join(store.root, ControlPlaneServiceTokenID))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(metadata), strings.TrimSpace(string(artifact))) {
|
||||
t.Fatal("metadata unexpectedly contains a credential value")
|
||||
}
|
||||
info, err := os.Stat(filepath.Join(store.root, ControlPlaneServiceTokenID))
|
||||
if err != nil || (runtime.GOOS != "windows" && info.Mode().Perm() != 0o400) {
|
||||
t.Fatalf("artifact mode = %v, %v", info.Mode(), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMachineCredentialSpecSupportsMachineCredentialKinds(t *testing.T) {
|
||||
cases := []MachineCredentialSpec{
|
||||
ControlPlaneServiceTokenSpec(),
|
||||
{ID: "database_role_password", Kind: MachineCredentialDatabaseRole, Purpose: secretcontracts.SecretPurposeDatabasePassword, Consumers: []secretcontracts.RuntimeConsumer{secretcontracts.RuntimeConsumerCore}, Bytes: 32},
|
||||
{ID: "internal_api_credential", Kind: MachineCredentialInternalAPI, Purpose: secretcontracts.SecretPurposeServiceAuthentication, Consumers: []secretcontracts.RuntimeConsumer{secretcontracts.RuntimeConsumerCommit}, Bytes: 32},
|
||||
}
|
||||
for _, value := range cases {
|
||||
if err := validateMachineCredentialSpec(value); err != nil {
|
||||
t.Fatalf("credential kind %s is unsupported: %v", value.Kind, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMachineCredentialRotateAtomicallyReplacesArtifactAndAdvancesVersion(t *testing.T) {
|
||||
store, err := NewLocalMachineCredentialStore(t.TempDir(), -1, -1, time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Ensure(ControlPlaneServiceTokenSpec()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(store.root, ControlPlaneServiceTokenID)
|
||||
oldValue, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rotated, err := store.Rotate(ControlPlaneServiceTokenSpec(), "exposure detected")
|
||||
if err != nil || !rotated.Rotated || rotated.Metadata.Version != 2 {
|
||||
t.Fatalf("rotation = %#v, %v", rotated, err)
|
||||
}
|
||||
newValue, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(oldValue) == string(newValue) {
|
||||
t.Fatal("rotation retained old credential")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMachineCredentialRejectsUnsafeExistingArtifact(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
if err := os.Mkdir(filepath.Join(root, ControlPlaneServiceTokenID), 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store, err := NewLocalMachineCredentialStore(root, -1, -1, time.Now)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.Ensure(ControlPlaneServiceTokenSpec()); err != ErrCredentialArtifactUnsafe {
|
||||
t.Fatalf("unsafe artifact error = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package secrets
|
||||
|
||||
import "strings"
|
||||
|
||||
const Redacted = "REDACTED"
|
||||
|
||||
// RedactDiagnosticFields removes known credential/header values before a
|
||||
// diagnostics boundary. Callers must still avoid passing raw values at all.
|
||||
func RedactDiagnosticFields(fields map[string]string) map[string]string {
|
||||
redacted := make(map[string]string, len(fields))
|
||||
for key, value := range fields {
|
||||
if isSensitiveDiagnosticField(key) {
|
||||
redacted[key] = Redacted
|
||||
continue
|
||||
}
|
||||
redacted[key] = value
|
||||
}
|
||||
return redacted
|
||||
}
|
||||
|
||||
func isSensitiveDiagnosticField(key string) bool {
|
||||
key = strings.ToLower(strings.TrimSpace(key))
|
||||
return key == "authorization" || key == "proxy-authorization" || strings.Contains(key, "secret") || strings.Contains(key, "token") || strings.Contains(key, "password") || strings.Contains(key, "credential")
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package secrets
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestRedactDiagnosticFieldsNeverReturnsKnownCredentialFields(t *testing.T) {
|
||||
fields := RedactDiagnosticFields(map[string]string{"Authorization": "Bearer value", "control_plane_service_token": "value", "status": "PASS"})
|
||||
if fields["Authorization"] != Redacted || fields["control_plane_service_token"] != Redacted || fields["status"] != "PASS" {
|
||||
t.Fatalf("unexpected diagnostic redaction: %#v", fields)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user