Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions internal/longhorninventory/v2_replicas.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package longhorninventory

import "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"

// V2ReplicaQuorum requires three running replicas of the exact volume on
// distinct nodes and disks.
func V2ReplicaQuorum(volume map[string]any, replicas []map[string]any) bool {
backend := unstructured.Unstructured{Object: volume}
name, uid := backend.GetName(), backend.GetUID()
if name == "" || uid == "" || replicas == nil {
return false
}
nodes, disks, identities := map[string]bool{}, map[string]bool{}, map[string]bool{}
for _, replica := range replicas {
rawSpec, _, _ := unstructured.NestedFieldNoCopy(replica, "spec")
spec, _ := rawSpec.(map[string]any)
if spec["volumeName"] != name {
continue
}
resource := unstructured.Unstructured{Object: replica}
owners := resource.GetOwnerReferences()
node, _ := spec["nodeID"].(string)
disk, _ := spec["diskID"].(string)
id := string(resource.GetUID())
state, _, _ := unstructured.NestedString(replica, "status", "currentState")
deleted, _, _ := unstructured.NestedFieldNoCopy(replica, "metadata", "deletionTimestamp")
healthyAt, _ := spec["healthyAt"].(string)
failedAt, _ := spec["failedAt"].(string)
if len(owners) != 1 || owners[0].APIVersion != "longhorn.io/v1beta2" || owners[0].Kind != "Volume" ||
owners[0].Name != name || owners[0].UID != uid || resource.GetNamespace() != "longhorn-system" ||
spec["dataEngine"] != "v2" || healthyAt == "" || failedAt != "" || state != "running" || deleted != nil ||
node == "" || disk == "" || id == "" || nodes[node] || disks[disk] || identities[id] {
return false
}
nodes[node], disks[disk], identities[id] = true, true, true
}
return len(nodes) == 3
}
10 changes: 9 additions & 1 deletion internal/namespaceinventory/coverage.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ func (r *reader) nativeCoverage(ctx context.Context, resources discovery) ([]ser
}
result := make([]serviceRegistration, 0, len(items))
seen, seenUID := map[string]bool{}, map[string]bool{}
scanRegistered := false
for _, item := range items {
group, version := item.Spec.Group, item.Spec.Version
if !versionPattern.MatchString(version) || len(version) > 63 || group != "" && (!groupPattern.MatchString(group) || len(group) > 253) || item.Metadata.Name != version+"."+group || item.Metadata.Namespace != "" || item.Metadata.UID == "" || item.Metadata.ResourceVersion == "" || seen[item.Metadata.Name] || seenUID[item.Metadata.UID] {
Expand All @@ -79,11 +80,18 @@ func (r *reader) nativeCoverage(ctx context.Context, resources discovery) ([]ser
if remote && (item.Spec.Service.Name == "" || item.Spec.Service.Namespace == "") {
return nil, errors.New("aggregated API service binding is incomplete")
}
if remote && required[gv] {
scanBackend := r.scanRecords && scanStorage(item)
scanRegistered = scanRegistered || scanBackend
// Only the exact Kubescape backend may supply derived records for a
// recovery namespace this invocation owns.
if remote && required[gv] && !scanBackend {
return nil, errors.New("namespace deletion admission is unverified for a remote API backend")
}
result = append(result, serviceRegistration{item.Metadata.Name, item.Metadata.UID, gv, item.Metadata.ResourceVersion, remote})
}
if r.scanRecords && required[scanGroupVersion] && !scanRegistered {
return nil, errors.New("scan storage registration is unverified")
}
sort.Slice(result, func(a, b int) bool { return result[a].Name < result[b].Name })
return result, nil
}
35 changes: 35 additions & 0 deletions internal/namespaceinventory/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,41 @@ func LoadProtectedClient(getenv func(string) string) (*http.Client, *url.URL, er
return newProductionClient(config)
}

var emailRecoveryCredentialPath = regexp.MustCompile(`^/dev/shm/email-data-recovery\.[A-Za-z0-9]+/kubeconfig$`)

// LoadEmailRecoveryClient reads only the private memory-backed credential of
// the confirmed first-attempt Email recovery dispatch. It shares credential
// validation, never authorization, with the benchmark observer.
func LoadEmailRecoveryClient(getenv func(string) string) (*http.Client, *url.URL, error) {
for key, want := range map[string]string{
"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main",
"GITHUB_REPOSITORY": "devantler-tech/platform", "GITHUB_RUN_ATTEMPT": "1", "RUNNER_ENVIRONMENT": "github-hosted",
"GITHUB_ACTOR": "devantler",
"GITHUB_WORKFLOW_REF": "devantler-tech/platform/.github/workflows/verify-email-data-recovery.yaml@refs/heads/main",
"EMAIL_DATA_RECOVERY_CONFIRM": "verify-email-data-recovery",
} {
if getenv(key) != want {
return nil, nil, errors.New("protected Email recovery dispatch is unverified")
}
}
if !sourcePattern.MatchString(getenv("GITHUB_SHA")) || !runPattern.MatchString(getenv("GITHUB_RUN_ID")) {
return nil, nil, errors.New("email recovery source and run are required")
}
path := getenv("KUBECONFIG")
if !emailRecoveryCredentialPath.MatchString(path) || filepath.Clean(path) != path {
return nil, nil, errors.New("fixed private Email recovery kubeconfig is required")
}
raw, err := readPrivateKubeconfig(path)
if err != nil {
return nil, nil, err
}
config, err := clientcmd.Load(raw)
if err != nil {
return nil, nil, errors.New("protected Email recovery kubeconfig could not be decoded")
}
return newProductionClient(config)
}

// LoadBenchmarkAdmissionClient admits the protected V1 benchmark, native seed,
// or the explicitly confirmed recovery of originalRun. The caller must first
// join the selected address to its serving process and verified Hetzner server.
Expand Down
63 changes: 63 additions & 0 deletions internal/namespaceinventory/credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,69 @@ func TestCredentialLoaderRefusesOutsideProtectedDispatch(t *testing.T) {
}
}

func emailRecoveryDispatch() map[string]string {
return map[string]string{
"GITHUB_ACTIONS": "true", "GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/main",
"GITHUB_REPOSITORY": "devantler-tech/platform", "GITHUB_RUN_ATTEMPT": "1", "RUNNER_ENVIRONMENT": "github-hosted",
"GITHUB_ACTOR": "devantler",
"GITHUB_WORKFLOW_REF": "devantler-tech/platform/.github/workflows/verify-email-data-recovery.yaml@refs/heads/main",
"EMAIL_DATA_RECOVERY_CONFIRM": "verify-email-data-recovery",
"GITHUB_SHA": "0123456789abcdef0123456789abcdef01234567", "GITHUB_RUN_ID": "45123456789",
"KUBECONFIG": "/dev/shm/email-data-recovery.Ab12Cd34/kubeconfig",
}
}

// The Email loader admits only its own confirmed dispatch and private path;
// every refusal happens before a credential file is read.
func TestEmailRecoveryLoaderRefusesOutsideItsConfirmedDispatch(t *testing.T) {
for _, change := range []struct{ key, value string }{
{"GITHUB_WORKFLOW_REF", "devantler-tech/platform/.github/workflows/observe-longhorn-namespace-inventory.yaml@refs/heads/main"},
{"GITHUB_ACTOR", "another"},
{"GITHUB_RUN_ATTEMPT", "2"},
{"EMAIL_DATA_RECOVERY_CONFIRM", "observe-email-data-recovery"},
{"GITHUB_SHA", "main"},
{"KUBECONFIG", "/dev/shm/longhorn-namespace-inventory.Ab12Cd34/kubeconfig"},
{"KUBECONFIG", "/dev/shm/email-data-recovery.Ab12Cd34/../kubeconfig"},
} {
env := emailRecoveryDispatch()
env[change.key] = change.value
if client, _, err := LoadEmailRecoveryClient(func(key string) string { return env[key] }); err == nil || client != nil {
t.Fatalf("Email loader admitted %s=%s", change.key, change.value)
}
}
}

func TestEmailRecoveryLoaderBuildsTheFixedClient(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("the protected credential directory is Linux memory-backed storage")
}
server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { t.Error("loader contacted an API") }))
t.Cleanup(server.Close)
directory, err := os.MkdirTemp("/dev/shm", "email-data-recovery.")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := os.RemoveAll(directory); err != nil {
t.Error(err)
}
})
raw, err := clientcmd.Write(*fixtureConfig(server))
if err != nil {
t.Fatal(err)
}
path := filepath.Join(directory, "kubeconfig")
if err := os.WriteFile(path, raw, 0600); err != nil {
t.Fatal(err)
}
env := emailRecoveryDispatch()
env["KUBECONFIG"] = path
client, endpoint, err := LoadEmailRecoveryClient(func(key string) string { return env[key] })
if err != nil || client == nil || endpoint == nil || endpoint.String() != server.URL {
t.Fatal("confirmed Email dispatch could not construct its fixed client:", err)
}
}

func TestBenchmarkDirectClientPinsAddressAndNeverFollowsRedirect(t *testing.T) {
server := httptest.NewTLSServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
t.Error("the old endpoint must not receive direct-client credentials")
Expand Down
49 changes: 34 additions & 15 deletions internal/namespaceinventory/inventory.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,12 @@ type Binding struct{ Name, Namespace, UID, Kind, Resource string }

// Inventory holds the observed bindings. They remain private until a caller
// explicitly copies them into its private journal. Default JSON serialization
// never publishes object identities.
type Inventory struct{ bindings map[string]Binding }
// never publishes object identities. Accepted Kubescape scan records are kept
// apart by resource and name, since the storage omits some of their UIDs.
type Inventory struct {
bindings map[string]Binding
scanRecords map[string]string
}

// Bindings returns a copy of the observed bindings ordered by UID.
func (i Inventory) Bindings() []Binding {
Expand Down Expand Up @@ -101,24 +105,27 @@ func CalibrateLonghornSystem(ctx context.Context, client *http.Client, endpoint
return result, nil
}

// ObserveRetainedEmailRecovery inventories only the fixed retained diagnostic
// copy. A complete inventory alone never authorizes removing any resource.
func ObserveRetainedEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, uid string) (Inventory, error) {
return observeNamespace(ctx, client, endpoint, "email-data-recovery-41561215415", uid)
// ObserveEmailRecovery inventories one fresh Email recovery namespace. It also
// reads the scan records Kubescape's aggregated storage keeps there, accepting
// only the exact registration and record kinds in scan_records.go. A complete
// inventory alone never authorizes removing any resource.
func ObserveEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) {
if !emailRecoveryPattern.MatchString(namespace) {
return Inventory{}, errors.New("a fresh Email recovery namespace is required")
}
return observeNamespaceWith(ctx, client, endpoint, namespace, uid, true)
}

// ObserveFreshRetainedEmailRecovery inventories the fixed fresh restore with
// its separately witnessed namespace identity.
func ObserveFreshRetainedEmailRecovery(ctx context.Context, client *http.Client, endpoint *url.URL, uid string) (Inventory, error) {
return observeNamespace(ctx, client, endpoint, "email-data-recovery-42818236850", uid)
func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) {
return observeNamespaceWith(ctx, client, endpoint, namespace, uid, false)
}

func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string) (Inventory, error) {
func observeNamespaceWith(ctx context.Context, client *http.Client, endpoint *url.URL, namespace, uid string, scanRecords bool) (Inventory, error) {
if endpoint == nil {
return Inventory{}, errors.New("authenticated API root is required")
}
root := *endpoint
fixed := namespace == "longhorn-system" || namespace == "email-data-recovery-41561215415" || namespace == "email-data-recovery-42818236850"
fixed := namespace == "longhorn-system" || (scanRecords && emailRecoveryPattern.MatchString(namespace))
if client == nil || root.Scheme != "https" || root.Host == "" || root.Opaque != "" || root.ForceQuery || root.User != nil || root.RawQuery != "" || root.Fragment != "" || (root.Path != "" && root.Path != "/") || (!namespacePattern.MatchString(namespace) && !fixed) || len(namespace) > 63 || uid == "" || len(uid) > 128 {
return Inventory{}, errors.New("fixed benchmark namespace and authenticated API root are required")
}
Expand All @@ -127,7 +134,7 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR
if err := observationActive(ctx); err != nil {
return Inventory{}, err
}
r := reader{client: *client, endpoint: &root, namespace: namespace, uid: uid}
r := reader{client: *client, endpoint: &root, namespace: namespace, uid: uid, scanRecords: scanRecords}
r.client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
if r.client.Timeout == 0 || r.client.Timeout > 20*time.Second {
r.client.Timeout = 20 * time.Second
Expand All @@ -143,14 +150,17 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR
if err != nil {
return Inventory{}, err
}
result := Inventory{bindings: map[string]Binding{}}
result := Inventory{bindings: map[string]Binding{}, scanRecords: map[string]string{}}
for _, resource := range resources.resources {
raw, err := r.get(ctx, resource.prefix+"/namespaces/"+namespace+"/"+resource.name, metadataListAccept)
if err != nil {
return Inventory{}, err
}
// Kubescape's storage sets no list resourceVersion; a continuation or
// remainder still marks its collection as partial.
records := r.scanRecords && resource.prefix == "/apis/"+scanGroupVersion
var actual partialList
if decode(raw, &actual, metadataFields) != nil || actual.APIVersion != "meta.k8s.io/v1" || actual.Kind != "PartialObjectMetadataList" || actual.Metadata.ResourceVersion == "" || actual.Metadata.Continue != "" || actual.Metadata.Remaining != nil && *actual.Metadata.Remaining != 0 || actual.Items == nil {
if decode(raw, &actual, metadataFields) != nil || actual.APIVersion != "meta.k8s.io/v1" || actual.Kind != "PartialObjectMetadataList" || (actual.Metadata.ResourceVersion == "" && !records) || actual.Metadata.Continue != "" || actual.Metadata.Remaining != nil && *actual.Metadata.Remaining != 0 || actual.Items == nil {
return Inventory{}, errors.New("namespace collection is partial or not metadata-only")
}
// The native metadata converter leaves Items nil for a complete empty
Expand All @@ -159,6 +169,12 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR
if json.Unmarshal(actual.Items, &items) != nil {
return Inventory{}, errors.New("namespace collection items are malformed")
}
if records {
if err := scanRecordList(resource, namespace, items, result.scanRecords); err != nil {
return Inventory{}, err
}
continue
}
seenItems := map[string]bool{}
for _, item := range items {
m := item.Metadata
Expand All @@ -185,6 +201,9 @@ func observeNamespace(ctx context.Context, client *http.Client, endpoint *url.UR
result.bindings[m.UID] = binding
}
}
if err := scanRecordsComplete(result.scanRecords); err != nil {
return Inventory{}, err
}
checked, err := r.discovery(ctx)
if err != nil || !reflect.DeepEqual(checked, resources) {
return Inventory{}, errors.New("served namespace resources changed during inventory")
Expand Down
Loading
Loading